w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
  Home » C++ » Page 22
Simple auto_ptr
The statement auto_ptr ptr(auto_ptr(data)); Declares a function named 'ptr' that has a parameter named 'data' of type 'auto_ptr' and that returns a value of type 'auto_ptr'. So, don't make this mistake)

Categories : C++

How can I make boost::variant return T() when what() != T, or how do I check if T==what()?
In general you can't. If you know the type indices, you can - perhaps - do something brittle with variant::which. The sure-fire way would be to write a visitor yourself though. Here's a proof of concept: namespace detail { template <typename T> struct get_with_default_visitor : boost::static_visitor<T> { T default_; get_with_default_visitor(T dv) : default_(d

Categories : C++

Boost not working over network
You get this when the connection is refused. This, in turn, could happen when the client is not listening on the required interface. Make sure that the IP addresses are actually the public IP addresses on the network and the machines can reach eachother. E.g. use netstat -tlpn (or similar on your OS) to ascertain that the clients are listening: tcp 0 0 192.168.2.136:1234 0.0.

Categories : C++

Sorting images using hue comparison between original and smooth version on OpenCV: is that enough?
This works somewhat. It's not clear how to tune this. But I had failed in properly assembling elements to make the index with ImageMagick. I also had some issues with the script used to glue this together but was provided with some help. So I was able to make it work(properly): #!/usr/bin/env sh ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ## -=Try to sort imag

Categories : C++

Enable C++14 Intel Compiler
The feature you're trying to use is called a generic (polymorphic) lambda expression from N3649 and the table you linked shows that support has not been added yet. However, the feature(s) you think you're using, "decltype(auto), return type deduction for normal functions" from N3638 do have support. A generic lambda looks like: [](auto a) { return a; } Return type deduction for normal function

Categories : C++

Why no access to a memory location is given to another process?
All modern modern operating systems use virtual memory. In virtual memory each process gets its own virtual address space. The virtual address space is divided into two distinct areas: The user space and the system (or Kernel) space. The system space is the same for all processes. However, it is not writeable from user mode and most of the addresses are not readable or executable from user mode.

Categories : C++

QT - connecting wrong button from member QWidget
The way you do the connect does not appear to be conventional. Try using traditional Qt way: connect(pButtonToPress, SIGNAL(clicked()), pObjectToHandle, SLOT(onClicked)); Provided QPushButton* pButtonPress actually pointing to QPushButton and pObjectToHandle to some object (can be 'this' pointer): class ObjHandler { public slot: void onClicked(); }; ... should satisfy. SIGNAL and SL

Categories : C++

OpenGL version and programming
You shouldn't be using a deprecated version of OpenGL while serious about programming on it. Since glut is old and its design rather rusty, I suggest using a recent windowing API that allows you to program with OpenGL 3.3+. Examples of such windowing APIs include SDL, SFML, GLFW to name a few. Also, the red book on OpenGL although is useful in understanding how OpenGL works doesn't implement it in

Categories : C++

Command Pattern In C++
You need to use public inheritance instead of private. Either change class to struct everywhere or say class WTFCommand : public Command. This is what the error, "base class inaccessible," means.

Categories : C++

error: iostream: No such file or directory
Sounds like you somehow hosed your compiler. You'll need to reinstall it or something. A normal install wouldn't need search paths and you shouldn't be including iostream.h even though it probably exists (gcc's non-h headers include the .h headers). This of course assumes your compiler version isn't like 20 years old. If that's the case then iostream probably doesn't exist and iostream.h would

Categories : C++

How to build and load shared library on rstudio for package that uses C/C++ files in src folder inside a subdirectory?
I ran into the same issue. Looking at the example of the RSiena package mentioned as an example in "Writing R Extensions" section 1.2.1.3 I noticed that that package still has some .cpp files not in a subdirectory. So I added a dummy.cpp file in src/ with the following contents: void dummy (void) { } After this g++ was correctly used for the linking step and the .so file was created as expected

Categories : C++

Programming a custom Map class using an array
Use elements[i].key The elements array is a pointer, but when you array index it, you just get a regular old myElement object. Usually the compiler's error message is pretty clear on this. I'd go back and reread the error you got.

Categories : C++

bubble sort linked list not sorting
Try running it through a debugger. If you look at the value of current on the second time round the changed loop, you will see that current is still null, so the second time round the changed loop it will not go through the current loop.

Categories : C++

How static object destruction order is calculated?
GCC 4.8.1 with -std=c++11 produces the following f1: push %rbp mov %rsp,%rbp mov $0x6021c0,%eax movzbl (%rax),%eax test %al,%al jne 0x400a1d <f1()+80> mov $0x6021c0,%edi callq 0x400830 <__cxa_guard_acquire@plt> test %eax,%eax setne %al test %al,%al je 0x400a1d <f1()+80> mov $0x1,%esi mov $0x6021d0,%edi callq 0x400b3a <A::A(int)> mov $0x6

Categories : C++

Boost Ping Example
The program keeps going because at the end of handle_receive it calls start_receive again, unconditionally. Update To the comment: the code doesn't reach after io_service.run(); because the IO service never runs out of work (new async operations are scheduled each time). Only when the process is interrupted/killed will it stop and in the absense of a signal handler for that your "This line wo

Categories : C++

c++ (for) loop :calculating y=n/(n+1)!
In many math scenarios, the '-' or what you are calling the negative sign, also works as subtraction. You have two options: Negate the value then add. Subtract the value. By order of precedence, you need to figure out the factorial of the denominator, divide the numerator by the denominator, and finally add or subtract from the total. Edit 1: Another solution is to process two terms per

Categories : C++

Volatile related error in C++ code
pNextList, through a volatile access-path, is volatile too. But pNextList is the pointer. The pointee type has the same cv-qualification as before. That is, for struct A { lThreadInfo* p; }; someStruct volatile* volatile* p; *p is an lvalue of type someStruct volatile* volatile (*p)->d is an lvalue of type lThreadInfo* volatile. So in the type of (*p)->d you're missing the volat

Categories : C++

SDL2: how to have both a SDL2 Menu and an OpenGL context?
After some research, I've found out that this is not really possible. After initializing OpenGL from within SDL, you cannot use any SDL drawing capabilities anymore: you either have to stick with OpenGL for all of your menus, or use SDL for them only once (=before initializing OpenGL). SDL becomes responsible practically only for events, then.

Categories : C++

How to cleared off the whole memory for the unused array allocated on the heap
The memory is cleared - there's just no requirement that the compiler will actually zero out an int in its destructor. What you're seeing is that the compiler didn't think that was necessary, so it's still there. The destructor is called though and the memory is freed. You can see that more clearly if you did something like: struct A { int i; A() : i(7) { } ~A() { std::cout

Categories : C++

Creating a unique_ptr from ifstream in binary
Jonathan Potter has already given you a solution but I'll tell you why it works and why it didn't before. When you write out: ofs.write(reinterpret_cast<const char*>(&myCharacter_), sizeof(myCharacter_)); You are taking the address of myCharacter which is a std::unique_ptr and casting that pointer to a const char * when it is in fact the object which contains that pointer. So what yo

Categories : C++

I would like to understand parameter unpacking in C++
After staring at this for a while I finally arrived at something logical. This is currently my understanding of this unpacking implementation. I've added comments in-code for clarity. template <typename F, typename Tuple, bool Done, int Total, int... N> struct call_impl { static void call(F f, Tuple && t) { call_impl<F, Tuple, T

Categories : C++

How to take preference with virtual method overriding and inheritance
You're looking for a feature that does not exist in the C++ language. In C++, dynamic dispatch occurs only from the caller, not on any of the arguments. So when you call myMethod(*m[2]), *m[2] is a Shape so it will call bool myMethod(Shape& ) since that's what overload resolution prefers. Now, if you really want something special in the Triangle/Square case, you might want to look at double

Categories : C++

How to use templates with QT signals and slots?
You can do this with new signals and slots syntax: QSlider *slid = new QSlider; QLineEdit *lne = new QLineEdit; connect(slid,&QSlider::valueChanged,this,&MainWindow::random); connect(lne,&QLineEdit::textChanged,this,&MainWindow::random); lne->show(); slid->show(); Slot: void MainWindow::random(QVariant var) { qDebug() << var; } Output: QVariant(int, 11) QVa

Categories : C++

Key event handling
You can do this in derived class. Suppose you have QBase and QDerive classes. Then you can reimplenent event handlers: void QDerived::keyPressEvent(QKeyEvent *Ev) { if (Ev->key() == Qt::Key_G) //do something QBase::keyPressEvent(Ev); } And also in QDerive class: protected: void keyPressEvent(QKeyEvent *Ev); You can also handle events without subclassing with event filter:

Categories : C++

sorting linked list implementation, getting the same list
You need to check if nextElement is NULL too. Consider a list of two elements: A --> B --> NULL On your first iteration through the while loop, first you'll have current == A and nextElement == B... and then you'll have current == B and nextElement == NULL, which you will still try to grab data off of, hence your access violation. Just change your loop condition from: for (current; curr

Categories : C++

Are undeclared variables legal in C++?
C++ is a typed langage. One of the concequences is that you HAVE to declare variables before using them. This seems strange to many but it contributes to have good coding practices, as weel as giving you errors when you do typos in your variables names. On of the easy to understand concequences is that it helps you calling the good version of an overloaded function by checking the type of the ar

Categories : C++

Detect if a 32bit process is running in a 64bit environment under Linux
You could test for the presence of /lib64/ld-linux-x86-64.so.2. Theoretically this doesn't always work because it's possible for a Linux system to put the dynamic linker somewhere else, but this particular path is by far the most common, plus the path to the dynamic linker is hardcoded into ELF binaries, so this works at least as well as actually bundling a 64-bit library with your software (provi

Categories : C++

Implementing CRTP and issue with "undefined reference"
The member template <> vector<long int> subSeq<Fibonnacci>::memory; Should be defined somewhere. To achieve your desired result, you should do this explicitly yourself in only a single translation unit (cpp file). Or alternatively; template <class T> vector<long int> subSeq<T>::memory = {}; As some compilers do support common data folding (e.g COMDAT in m

Categories : C++

Installing Moses Translation Software. Error message: "ld: library not found for -lboost_thread"
This package expects a non-standard layout of boost (or maybe that's the standard liayout for installed boost on many systems, but it certainly isn't the default layout for boost in my working directories): bjam --help says: --with-boost=/path/to/boost If Boost is in a non-standard location, specify it here. This directory is expected to contain include and lib or lib64. When m

Categories : C++

How to catch an error with a character string not containing a null terminator
Consider using std::string as the container for your file name. Then File1.c_str() should always be a null terminated string. If you really want to do what you write in the question looping through the File1 array and checking if each char is '' would tell you if the sting is null terminated. I would not recommend using strcpy like that though since it may write out of bounds of your array.

Categories : C++

String return from member function in C++
In C and C++ as opposed to C# and Java, variables do not need to be allocated in dynamic memory, which includes strings and character arrays. If you need or want to return pointers from a function, they must point to some variable that won't disappear after execution leaves the function. The two popular techniques are to use static variables or variables allocated from dynamic memory. Both st

Categories : C++

C++ do I need to initialise an stl field in a default constructor?
You seem to have mistaken the constructor body for the member-initializer list. The member-initializer list is what's used to actually construct the data members and base classes by calling their constructors. It starts with a colon followed by a comma separated list of constructor calls. For your example, to call the default-constructor on my_map, you'd use this syntax: A::A() : my_map() { } T

Categories : C++

Command not found, c++ aplication
Your compilation command builds a Bingo executable. Your execution command tries to run a bingo program. Case is significant. You really should compile with all warnings and debug info and don't need to pass any header file to the compiler (header which you should #include inside Bingo.cpp and main.cpp): g++ -std=c++11 -Wall -Wextra -g main.cpp Bingo.cpp -o Bingo Then, edit your code till yo

Categories : C++

Count word in trie implementation
Here is a simple and clear way to do it(using depth-first search): size_t TrieNode::wordCount() const { size_t result = isEnd ? 1 : 0; for (size_t i = 0; i < 26; i++){ if (array[i] != null) result += array[i]->wordCount(); return result; }

Categories : C++

How do I add a library to my NetBeans C++ project?
You have to add two things: (a) Library header Go to … Project Properties -> C++ Compiler -> Include Directories add the header's directory path there. (b) Library binaries Go to … Project Properties -> Linker -> Additional Libraries Directory and add the directory path- that's where your library binaries are. Next add your library at: Libraries.

Categories : C++

OpenGL 4 core profile, shaders and MFC
Apparently OpenGL in MFC, when using a core profile, needs to have a view port set, via glViewport. Handling WM_SIZE and doing glViewport(0, 0, (GLsizei)cx, (GLsizei)cy) solved the issue. As a note, Andon was correct in saying that I shouldn't specify the pixel format twice. It didn't give any error, which is strange, but when I removed it everything kept on working.

Categories : C++

How to set a Qt program's icon under windows?
Please not that only that top left corner of the window icon is controlled by Qt: http://qt-project.org/doc/qt-4.8/appicon.html#notes The executable icon isn't a GUI element so it really has nothing to do with Qt. It can be embedded in the executable by visual studio though: How do I set the icon for my application in visual studio 2008?

Categories : C++

fast 'ball' pixel-rasterization routine with shading
Normal vector on sphere the normal for any point (x,y,z) is (x-x0,y-y0,z-z0) where (x0,y0,z0) is the sphere center so you need the Z coordinate too ... should normalize it by dividing the final dot product by radius... Rasterization to compute Z axis you need sqrt for small radiuses you can use lookup table for SQRT (and still be fast) so the rasterization looks like this: do 2 nested fors

Categories : C++

How to return a reference to a new object without memory leaks? c++
The most concise answer is: Don't do it using raw pointers! Use the c++ smart pointer features instead. The most straightforward implementation seems to be, creating a std::unique_ptr<MessageAssembler> instance and return this one. The calling client will receive ownership of the created instance and it will be deleted automatically, as soon that reference goes out of scope.

Categories : C++




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.