question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
7,573,857
7,573,923
Passing C++ Lambda Functions
I've been searching everywhere for this, and I don't seem to be able to find a straight answer. Some sources say this isn't possible, but that only raises more questions for me, which I'll explain further below. So here's the situation. Suppose I have a custom container class with a selection function like below (this ...
You need to declare your lambda as stateless (that is, with an empty capture specification [](int x)-> bool {...}) for it to be convertable to a function pointer.
7,574,025
7,574,056
Inserting complex values to a map in C++
I am having trouble inserting data into this map. I honestly can not figure out the way to do this, but the last line of the code I gave is the part that I need fixed. map<string, vector<vector<Obj*>* >* > the_map; vector<vector<Obj*> *>* vectors = new vector<vector<Obj*> *>; vector<Obj*> Obj_vector; vectors->push_ba...
Try this: the_map.insert(make_pair(string("field1"), vectors)); //you forgot this ^ ^ // | // & is not needed here By the way, I suspect the usage of so many pointers in your code, and especially these two lin...
7,574,125
7,574,510
Multiplying a matrix and a vector in GLM (OpenGL)
I have a transformation matrix, m, and a vector, v. I want to do a linear transformation on the vector using the matrix. I'd expect that I would be able to do something like this: glm::mat4 m(1.0); glm::vec4 v(1.0); glm::vec4 result = v * m; This doesn't seem to work, though. What is the correct way to do this kind o...
glm::vec4 is represented as a column vector. Therefore, the proper form is: glm::vec4 result = m * v; (note the order of the operands)
7,574,350
7,636,532
Segmentation fault using FFTW
I have a pretty involving program that uses an in house FFT algorithm. I recently decided to try using FFTW for a performance increase. Just as a simple test to ensure that FFTW would link and run, I added the following code to the beginning of the application, however, when I run, I get a segmentation fault when I cre...
Aparently the issue stems from multi-threading. Even though the main functions are thread safe in FFTW (e.g. fftwf_execute), the functions to create a plan are not. This doesn't fully explain why just running a test on startup failed, however, when I excapsulated the plan creation in mutex locks, the segmentation fault...
7,574,378
7,574,939
type wrapper error with boost::mpl::for_each (section 9.1.1 from Abrahams & Gurtovoy book)
The following code is copied almost verbatim from section 9.1.1 of the book C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond by David Abrahams & Aleksey Gurtovoy. The only change is that I want to be able to change the type wrapper template from the book with the regular Boost templa...
Some terminology, paraphrased from the Boost.MPL reference manual: A metafunction is a type with a nested type named type A metafunction class is a type with a nested metafunction named apply A placeholder expression is a type that is either an MPL placeholder or a class template specialization with at least one argum...
7,574,430
7,585,059
C++ member function pointers in class and subclass
I have one base class which holds a map for function pointers like this typedef void (BaseClass::*event_t)(); class BaseClass { protected: std::map<std::string, event_t> events; public: // Example event void onFoo() { // can be added easily to the map } }; Handling t...
After some thought and a redesign i was able to achieve what i wanted. Although i am stubborn and still using inheritance i have reimplemented the map. This is how it works now: class Location { // ... protected: std::map<std::string, std::function<void(void)>> m_mEvents; }; And now i can handle it li...
7,574,578
7,574,733
C++ Memory/Input Problem
I'm trying to create a small program in c++ where the user puts in multiple lines and the program outputs all the lines of after a EOT command is given (ctrl-d) But i'm getting some error's when executing the program. I think i did a lot wrong. (This is an hypothetical exersise, i don't want to use any vectors, lists e...
Try something like this (untested, edited in notepad): #include <iostream> using namespace std; int main() { //Temp input string string input_string; //Array with input lines string * lines = 0; // Array used for temporary storage string * temp_lines = 0; //Counter for input lines ...
7,574,653
7,574,703
Will everything work the same if I cut and paste my .cpp to the bottom of my .h?
I have a very simple class and I'd like to consolidate it to a single .h file. Will everything work the same if I cut and paste the guts of my .cpp to the bottom of my .h? In particular, there are static member variable initializations int MyClass::myStaticVar = 0; outside of any class definition at the top of the .cp...
If you're left with a single cpp file in the entire project, then it will work (but it's bad practice). If you have two cpp files that both include that header, you're breaking the one definition rule, and you (should) get linker errors. You can do this if (A) All the functions are templates (in fact, you must in this...
7,575,070
7,575,181
Prevent temporary from extending its lifetime?
This may be impossible, but I was wondering if it was possible to keep a temporary from ever lasting past its original expression. I have a chain of objects which point to parent objects, and a member function which will create a child object, a simplified example is here class person{ string name; person * mom...
It looks like you are creating a data structure here where children have pointers to their parents. Using temporaries is guaranteed to cause you grief in this case. In order to make this safe, you will need to dynamically allocate and possibly use some sort of reference counting. Have you considered using boost::shared...
7,575,172
7,575,310
How to add a timestamp to OutputDebugString()?
I am writing a C++ application, and I want to add a timestamp to OutputDebugString(). I already know that if I watch the application using DebugView, it automatically show timestamps. But for a particular reason I want to add TimeStamps to any string I pass to OutputDebugString(). What would some sample code be?
You could use QueryPerformanceCounter and QueryPerformanceFrequency to get a high-resolution timestamp. If you set a variable to the value returned by QueryPerformanceCounter before your program really starts executing, you can achieve the same effect as debug view by subtracting this initial value from the current pe...
7,575,298
7,575,545
Static library debug symbols
In VS2010 there is an option to generate debug info for exes/dlls under linker but no such option under librarian for libs. Is the debug info embedded in the static library? There is an option in the C/C++ properties for Program Database File Name for libs, exes, and dlls. By default it goes into my intermediate direct...
If you use /ZI or /Zi (C/C++ -> General -> Debug Information Format), then the vc$(PlatformToolsetVersion).pdb is created, which contains the debug info for all of the .obj files created. If alternately you use /Z7, the debug info will be embedded into the .obj file, and then embedded into the .lib. This is probably th...
7,575,459
7,575,528
C++: Should I initialize pointer members that are assigned to in the constructor body to NULL?
Suppose I have: // MyClass.h class MyClass { public: MyClass(); private: Something *something_; } // MyClass.cpp MyClass::MyClass() { something_ = new Something(); } Should I initialize something_ to NULL (or 0) in the constructor initialization list of the MyClass constructor? Or is that not necessar...
Generally you only assign it once, in the initialization list or the body, unless the body initialization may or may not happen, or has prerequisite code: MyClass::MyClass() { //this code must happen first // _now_ max is known something_ = new Something(max); } MyClass::MyClass() { if (max) some...
7,575,481
7,575,549
Minimum element in empty array
If you have a function int getMin(int a[], int n) then what would you say is the cleanest solution to deal with the empty array case?
Return a pointer to the minimum element instead of the element itself. This way, a pointer value of one past the end of the array can indicate not found. (Or in this case empty) This is the strategy taken by std::min_element, which already implements what you're doing. You can even implement this in terms of std::min_e...
7,575,708
7,576,090
Concise way to initialize a block of memory with magic numbers
A few examples of what I'm referring to: typedef struct SOME_STRUCT { unsigned int x1; unsigned int x2; unsigned int x3; unsigned int x4; // What I expected would work, but doesn't; the 2nd parameter gets // turned into an 8-bit quantity at some point within memset SOME_STRUCT() { memset( this, 0xFEEDFAC...
Here’s a partial example of using std::generate() safely: #include <algorithm> struct Wizard { size_t i; static unsigned char magic[4]; Wizard() : i(0) {} unsigned char operator()() { size_t j = i++; i %= sizeof(magic); // Not strictly necessary due to wrapping. return magic[j];...
7,575,714
7,575,825
C++ Windows add option to menu
In windows, when you click the small icon in the upper left of the window, you get a menu with Move, Minimize, Maximize, and Close options. Is there anyway I can add my own options to that menu?
Absolutely. GetSystemMenu(hWindow, FALSE) gets you menu handle and you are free to modify it. A nice way is to add a separator and append your additional items like "About...". ATL code snippet is here: http://www.assembla.com/code/roatl-utilities/subversion/nodes/trunk/FilterGraphSpy/GraphBuilderCallbackPropertySheet...
7,575,720
7,575,763
C++ Windows remove maximize box
I'm using these window styles when calling CreateWindow WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX This disables the maximize box, but is there any way I can completely remove it?
No easy way, but if you are going to draw the title bar yourself - in this case you can do it. To give you an idea, this article Adding a 'Minimize to tray'-button to a Form's caption bar explains how to add a button. Removing standard button is about the same - customization of non-client area.
7,575,891
7,576,094
invalid conversion from 'char' to 'char*' using strcpy
Ok so here are the parts of my code that I'm having trouble with: char * historyArray; historyArray = new char [20]; //get input cin.getline(readBuffer, 512); cout << readBuffer <<endl; //save to history for(int i = 20; i > 0; i--){ strcpy(historyArray[i], historyArray[i-1]); //ERROR HERE// } strcpy(hi...
Stop using C idioms in a C++ program: std::deque<std::string> historyArray; //get input std::string readBuffer; std::getline(std::cin, readBuffer); std::cout << readBuffer << std::endl; //save to history historyArray.push_front(readBuffer); if(historyArray.size() > 20) historyArray.pop_back(); As a result, ...
7,575,925
7,576,000
Is it possible to specialize a template definition based on the existence of a nested typedef of a template type parameter?
I have a template, template <typename T> class wrapper, that I would like to specialize based on the existence of typename T::context_type. If typename T::context_type is declared, then the constructors and assignment operator overloads of the wrapper<T> instantiation should accept a mandatory typename T::context_type ...
Yes, it is possible. I have implemented such behavior in the past by using some metaprogramming tricks. The basic build blocks are: BOOST_MPL_HAS_XXX_TRAIT_DEF, to define a metafunction predicate that will evaluate to a true type if the argument is of class type and has a nested type with a given name (context_type in ...
7,576,223
7,576,234
What is the difference between `void f1(const Class &c)` and `void f2(Class const &c)`?
What is the difference between these below functions ( Look at keyword const ) ? void f1(const Class &c) and void f2(Class const &c)
There is no difference. The two versions are interchangeable.
7,576,303
7,576,318
Help with a c++ statement
The following statement is from WebKit. I am not 100% sure what it means. Any clues? new ((void*)&nullAtom) AtomicString;
It's a placement-new. It means that the AtomicString object will be constructed at the memory location pointed to inside the parentheses (&nullAtom), rather than the usual behavior (constructed on top of a bit of memory taken off of the heap).
7,576,313
7,576,334
How to use a pointer's methods in C++?
I have a code in which I use a pointer to a class that I made. As an example lets say I have a Person method, and each Person had a name. Now lets say I use a pointer for a person like Person& * person_; Now lets say I'm trying to get the name of the person using the pointer I have. If I do something as simple as per...
You use the pointer notation: person_->getName() -> is what you want.
7,576,317
7,576,920
Display an image 2nd edition
I have a problem with my c++ opencv program. It should show a picture I loaded in, but after debugging only a grey window pops up. Here is my code: #include <cv.h> #include <highgui.h> int main(int argc, char* argv[]) { IplImage* img = cvLoadImage( "IMG_7321_.jpg" ); cvNamedWindow( "IMG_7321_", CV_WINDOW_AUTOS...
You should check to see if you are successfully loading the file. Try this: int main(int argc, char* argv[]) { IplImage* img = cvLoadImage( "IMG_7321_.jpg" ); if (!img) { fprintf(stderr, "Image not found\n"); return -1; } cvNamedWindow( "IMG_7321_", CV_WINDOW_AUTOSIZE ); cvShowImage(...
7,576,421
7,695,207
Is it possible to get the rotation and scale between two images with only a Surf Descriptor of each?
I'm using Surf for landmark recognition. This is the process I thought: 1) save before hand one Surf Descriptor for each landmark 2) A user takes a photo of a landmark (eg building) 3) A Surf Descriptor is computed for this image (the photo) 4) This descriptor is compared against each landmark descriptor stored and the...
Just comparing scale of descriptors and their rotation is naive and generally will not work. What you need is applying some geometrical model to find relationship between photos. See more in this book http://www.robots.ox.ac.uk/~vgg/hzbook/, especially PART II: Two-View Geometry.
7,576,537
7,576,614
Optimal way to fill std::vector<char> buffer
This buffer should contain slots (three in this example) of equal length ( 20 in this example) The buffer has to have contiguous memory so that it can be passed to a C function in non-const fashion. const int slot_size = 20; std::vector<char> vbuffer; This function takes a string, copies to a temporary buffer of the ...
How about this: vbuffer.reserve(vbuffer.size() + 20); vbuffer.insert(vbuffer.end(), s.begin(), s.end()); vbuffer.insert(vbuffer.end(), 20 - s.size(), '\0'); An additional check on the string length is recommended, along with a policy for handling over-long strings (e.g. assert(s.size() < 20);).
7,576,541
7,576,629
Help with c++ logic?
Something::methodname() { (unsigned char*) ptr = (unsigned char*) m_pptr; while ((*ptr || *(ptr+1)) && (((unsigned char*)m_pptr+BUFSIZE)<ptr)) ptr++; if(ptr == m_pptr) return ptr; return ptr + 1; } m_pptr is a protected member of a class. ptr is local to this function Could someon...
(((unsigned char*)m_pptr+BUFSIZE)<ptr)) looks backward: (((unsigned char*)m_pptr+BUFSIZE)>ptr)) would be more likely; Even more sane: while (ptr < ((unsigned char*) m_pptr + BUFSIZE)) // until end of buffer { if (!*ptr) // null char reached break; if (!*(ptr+1)) // null char almost reached ...
7,576,554
7,576,581
Why does calling 'delete' in a specific way on a dynamic array not work?
I'm wondering why this code doesn't work: void KeyValueList::Release() { //(m_ppKeyValueList is a dynamic array of pointers to objects on the heap) if (m_ppKeyValueList) { for (int i = 0; i < m_iCapacity; ++i) { if (m_ppKeyValueList[i]) { delete m_ppKeyValueList[i]; }...
A dynamic array is more than just a sequence of elements. It contains information about the array size as well. Moreover, there is just one chunk of memory known to the allocator. So just like with any dynamic memory, you can only free what you allocated, not smaller subsets of it. That's why the language requires that...
7,576,933
7,576,973
C++ windows pause timer
I'm using SetTimer to create a timer in my application with an interval of 50ms, this timer is going to be used to draw an object, and move it around. Now I don't want the object to move when the window is out of focus, but I still need it to be painted. And having it paint every 50ms, seems unnecessary. And performanc...
When you get WM_ACTIVATE, decide whether to call KillTimer or SetTimer.
7,576,935
7,577,039
Getting started with SQLite and C++?
For an online game I'm making, I need to be able to add users and their stats to a database, an example table: Username, Password, Email, Wins, Loses The username will be the unique key, and from there I need to retrieve the other information. I also need to do other things such as find all the usernames with a given e...
The SQLite documentation is quite good: Documentation main page Quickstart C/C++ API intro
7,576,948
7,576,981
Does pointer arithmetic have uses outside of arrays?
I think I understand the semantics of pointer arithmetic fairly well, but I only ever see examples when dealing with arrays. Does it have any other uses that can't be achieved by less opaque means? I'm sure you could find a way with clever casting to use it to access members of a struct, but I'm not sure why you'd both...
If you follow the language standard to the letter, then pointer arithmetic is only defined when pointing to an array, and not in any other case. A pointer may point to any element of an array, or one step past the end of the array.
7,576,950
7,577,083
OpenCV hand recognition?
After spending on a while on this, I finally managed to detect the hands through thresholding. The only problem is that VERY FEW pixels in the background remain, which will mess up the next step. Any suggestions on how to get rid of the few background pixels? Because I don't want to go through the whole background subt...
It's hard to be sure without a more detailed description of your hand detection algorithm. If you have a few background pixels that are isolated from the hands you have detected, I would suggest morphological operation like opening to eliminate single pixel detections in your binary mask. In openCV, I think you need to...
7,576,953
7,577,088
C++ auto keyword. Why is it magic?
From all the material I used to learn C++, auto has always been a weird storage duration specifier that didn't serve any purpose. But just recently, I encountered code that used it as a type name in and of itself. Out of curiosity I tried it, and it assumes the type of whatever I happen to assign to it! Suddenly STL ...
auto was a keyword that C++ "inherited" from C that had been there nearly forever, but virtually never used because there were only two possible conditions: either it wasn't allowed, or else it was assumed by default. The use of auto to mean a deduced type was new with C++11. At the same time, auto x = initializer dedu...
7,577,126
7,577,148
allocating memory when overriding + operator in c++
I am creating a custom object and overriding the + operator. I am return a new object of the same type. Is it bad practise to allocate memory inside this method? because I then I will need to delete the memory out of scope.
Yes, without further information, it is bad. Usually you do: struct X { int m_i; X(int i) : m_i(i) { } X operator+(const X& another) const { return X(m_i + another.m_i); // note, not new X(...) } } That said, you could return a unique_ptr if you really had to allocate dynamically.
7,577,176
7,577,613
QComboBox fused to QSpinBox
So I am writing a Qt GUI for some scientific software and I have QSpinBoxes and QDoubleSpinBoxes for a quantities that user should set the units of. Because I have several of these spinbox-combobox pairs in a row I think it would be least confusing to have the ComboBox on the right fused to the SpinBox on the left. I h...
If by fused you mean that distance between spinbox and combobox should be zero, then you should create QProxyStyle descendant, reimplement styleHint to return -1 if asked for QStyle::PM_LayoutHorizontalSpacing, and declarie a slot called layoutSpacingImplementation (read QStyle documentation) that is recieving both wid...
7,577,345
16,528,589
How do I collect input from an external window using SDL?
I'm currently trying to re-write my binder between Ogre and SDL in my game engine. Originally I used the method outlined in the Ogre Wiki here. I recently updated my version of SDL to 1.3 and noticed the "SDL_CreateWindowFrom()" function call and re-implemented my binder to allow Ogre to build the window, and then ge...
It has been a while, but I figured I would put in the answer for others that may need it. It turned out to be a bug/incomplete feature in SDL 1.3. The "CreateWindowFrom" method wasn't originally intended to be used exclusively as an input handler. At the time of this writing I know myself and another on my team wrot...
7,577,410
7,577,462
boost-python select between overloaded methods
Assume exist some class Foo with two overloaded methods: class Foo { ... void m1(A& a); void m1(B& b); I need expose one of these methods over boost-python: boost::python::class_<Foo>("Foo") .def("m1", &Foo::m1) How should I specify that signature of m1(A&a) should be used over m1(B&b)
void (Foo::*m1)(A&) = &Foo::m1; boost::python::class_<Foo>("Foo") .def("m1", m1)
7,577,635
7,577,804
Taking input for fstream::seekp and fstream::put
How would I go about taking input for seekp and put for use with hex? Something like this? Cin>>hex>>mychar; How about printing the correct value in hex? Say at 0x16 the byte is FF or 255 unsigned 8bit(decimal?) when I do this fstream mystream; mystream.seekp(0x16); long myvar; myvar=mystream.tellp(); cout<<"Value ...
There are a couple of problems with your code: ostream::seekp sets the "put" pointer, i.e. the location at which one writes data, not the position at which one reads data. Use istream::seekg to set the "get" pointer ostream::tellp doesn't perform any I/O. It merely reports the value of the 'put' pointer, it doesn't ac...
7,577,643
7,577,647
What is the effect of calling sleep(0) on a UNIX system?
I see people doing this in some parts of heavily multi-threaded, multi-process application systems I work with. It seems to be done around debug lines: std::cerr << "DEBUG: Reaching: " << __FUNCTION__ << " @ " << __LINE__ << std::endl; sleep(0); If I macro out sleep(0); (i.e. change it to ""), the debug output from t...
Basically, it yields control back to the scheduler, and lets you be re-scheduled instantly. That said, it's basically a hack to try and fool the operating system into doing something. And it's never a good idea to fool the operating system. If the system is suitably underloaded, then going to sleep will mean the OS ge...
7,577,883
7,577,952
C++ GetLine() Problem, Command Line Program
I am writing this program for my programming class and it has a bunch of stupid constraints like I must use nested if else statements and I have to use the cin.getLine() to get a players name. It is supposed to grab the name of each player and calculate their batting average. This is not the entire program but up to t...
I think it's a buffer problem. Try to flush the cin before the second getline: cin.clear(); // clear the buffer cin.sync(); if that does not work, try something like this: cin.ignore(256, '\n'); // ignore the endline and char(256)
7,577,906
7,578,644
In gdb sizeof(Apple::record_) is zero. But It runs well
I encounterd a very strange g++ problem. The output of the flowing program is "24 8 3", All things seems ok. But when I use gdb, to print sizeof(Apple::record_), it turns out to be 0. My gcc version is 4.5.2 (GCC)(MinGw), gdb version is GNU gdb (GDB) 7.3 Can anybody help me ?? #include <iostream> using namespac...
In the following version of GDB, p sizeof(Apple::record_) returns 48. (This is not 24 because the int and pointer on my system are 8 bytes each). Perhaps the version of GDB you are using is buggy in this regard? GNU gdb 6.3.50-20050815 (Apple version gdb-1705) (Fri Jul 1 10:50:06 UTC 2011) Copyright 2004 Free Software...
7,577,984
7,577,997
How do I jump from while(getline(cin,tmp))?
I am reading 'generic programming and the stl' in chapter1, this is a sample like this, int main() { vector<string> v; string tmp; while(getline(cin,tmp)) //problem is here, it keep asking me to input value v.push_back(tmp); sort(v.begin(), v.end()); copy(v.begin(), v.end(), ostream_iter...
Send an end-of-file character: you can use CTRL-Z Return (Windows), or CTRL-D (Unix terminals). Then, getline will return false as there is nothing more to read from stdin. An alternative is: pipe the output of another program into this one.
7,578,083
7,578,147
I'm in trouble with inheritance and polymorphism in C++
I'm new to C++, and I'm trying to use inheritance but I have an error. It says Error 6 error LNK1120: 2 unresolved externals L:\2011-08\C++\Assignment\Drug Management\Debug\Drug Management.exe 1 1 Drug Management There're three classes which are Animal, Sheep, and Cattle. What I've done so far is: //Animal.h...
You declared but did not define a default constructor and a destructor for Animal, and for Cattle (and presumably the others as well). Define them, or don't declare them (you probably do need a destructor though, even if it does nothing). Another problem is your calcDose method. One way to deal with that is to make it ...
7,578,265
7,578,284
Error: expected a declaration
So far all I have in my DecisionTree.h file is namespace DecisionTree { public static double Entropy(int pos, int neg); } and Visual Studio is already highlighting the public and saying Error: expected a declaration. What am I missing?
public is an access specifier. Access specifiers are applicable only within class/struct body and not inside namespace. In C++ (unlike Java) it must be followed by a colon : inside the class body. For example, class DecisionTree { // <----- 'class' (not 'namespace') public: // <------ access specifier static double...
7,578,487
7,578,567
Optimizing unnecessary string copying in vector<string>
Presenting the minimal code to describe the problem: struct A { vector<string> v; // ... other data and methods }; A obj; ifstream file("some_file.txt"); char buffer[BIG_SIZE]; while( <big loop> ) { file.getline(buffer, BIG_SIZE-1); // process buffer; which may change its size obj.v.push_back(buffer); // <--...
Well, you get two allocations, but not both of them are of the string: one of them creates the string, while the other creates just a pointer inside of the vector (note that this depends on the compiler: some compilers/settings might indeed create two strings, but most won't). Look at this code for the demo. One way t...
7,578,649
7,578,666
BingoBoard Segmentation Fault
I keep getting a segmentation fault with this Bingo Board I'm trying to create in C++. Valgrind didn't tell me much more than this: ==2734== Memcheck, a memory error detector ==2734== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al. ==2734== Using Valgrind-3.6.1 and LibVEX; rerun with -h for copyright i...
The problem is with: delete bingo; where bingo is not pointing to memory obtained from use of new but is pointing to a string literal. Also the format specifier or the argument to printf is incorrect: printf(" %s ", bingo[i]); %s expects argument to be a char * but your argument type is integer. Either change the for...
7,578,682
7,580,505
Why should I overload a C++ operator as a global function (STL does) and what are the caveats?
Why would I want to overload a C++ operator() as global and not member function. For example, the == operator. Why is this done? for example in STL libraries.
The usual rule is for operators which modify the left hand object to be members, and binary operators which return a new object to be free functions; the main motivation for the latter is because the compiler will not convert the left hand side to match a member; if your class supports any implicit conversions, then al...
7,578,842
7,578,912
Logic / Algorithm for this Series
I have an array of characters from a to z, my task is to extract the vowels out of this array, the series that will extract the indexes of vowels goes like this, 1, 5, 9, 15, 21, 25... i am unable to create this series through loops, these numbers are actually the vowels in the array. I don't want Vowel Matching techni...
If you really want to do this algorithmically, you could: int v = 1; for (int i = 0; i < 6; i++) { printf("%d\n", v); v += 4 + (i & 2); } ...but I'm not sure I see the point.
7,579,109
7,579,147
How do i fix error?? Error: expected ";" before "factorial"? it says in Line 16
I'm getting an error and do not know how to fix it. My code is as follows: #include <iostream> using namespace std; int main(){ int factorial = 1, current = 2, n; cout << "enter number to calculate factorial of: "; cin >> n; while (current <= n){ factorial = current * factorial; current++; } cout...
You're missing an operator: cout << n << "!= " factorial << endl; Should be: cout << n << "!= " << factorial << endl;
7,579,112
7,579,143
Allocating large amount of memory and usage of size_t?
In my application ,I am allocating memory to store "volume data" which read from stack of bitmap images. I stored the data in a "unsigned char" and ,during allocation, first I try to allocate continuous memory-block for entire data.if that fails then tries for scattered allocation.(one small memory-block for each image...
I encounter the same problem very often when working on workstations with > 32GB of memory and large datasets. size_t is generally the right datatype to use for all indices in such situations as it "usually" matches the pointer size and stays compatible with memcpy() and other library functions. The only problem is tha...
7,579,400
7,579,855
c++ code using libnet not compiling
I'm trying to compile my libnet script and am getting this error: [root@whyme]# gcc -Wall `libnet-config --defines` mysocket.cc -o mysocket `libnet-config --libs` -lpcap -lnet /tmp/ccUPbuVg.o: In function `main': mysocket.cc:(.text+0x1e): undefined reference to `net_init' mysocket.cc:(.text+0x2a): undefined reference t...
I'm able to compile & execute this source file with your exact command (changing only the filenames): https://github.com/repolho/Libnet-1.1-tutorial-examples/blob/master/01_init.c I therefore suspect the problem is in your source after all. Most libnet function names are of the form libnet_[funcname], but in your linke...
7,580,009
7,580,064
GCC error: cannot convert 'const shared_ptr<...>' to 'bool' in return
I'm switching to GCC 4.6.1, and it starts to complain about code which works fine with GCC 4.4 and MSVC10. It seems that it doesn't want to convert between shared_ptr and bool when returning from a function like this: class Class { shared_ptr<Somewhere> pointer_; }; bool Class::Function () const { return pointer_;...
In C++11, shared_ptr has an explicit operator bool which means that a shared_ptr can't be implicitly converted to a bool. This is to prevent some potentially pitfalls where a shared_ptr might accidentally be converted in arithmetic expressions and the similar situations. Adding an explicit cast is a valid fix to your c...
7,580,156
7,580,211
String Output to File
So I'm trying to write a large string to a .txt file, but am having some trouble. The string I want to output is this: 0.x.y.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t....
Without even having tried it, I can confidently say that it works for me. The error is not in the code but elsewhere: I suspect that you open the text file in Notepad on Windows, or a similar program. The application will try to guess the file’s encoding and (wrongly) guess that it’s a Unicode-encoded file (UTF-16). To...
7,580,345
7,580,381
Local variable or a pointer
Given a class in a any random C++ framework, how do you know if you have to create a simple object on stack or a pointer to an object on heap? Assume a function which accepts argument in the form of a reference(&) variable. The caller can pass a local variable to it or a pointer too(*ptr). The called function may or ma...
In general, every well-designed C++ library will allow both. In most cases the library doesn’t care where the caller allocates memory, since the caller handles its own memory. If the library has additional requirements (e.g. that it takes over possession of a pointer) then it will carefully document this. Furthermore, ...
7,580,352
7,580,469
Float comparison gives different results
Look at the following two codes, and tell me the reason why answers vary a lot. #include<stdio.h> int main() { float a = 0.9; if(a<0.9) printf("hi"); // This will be the answer else printf("bye"); return 0; } And if we change 0.9 to 0.8, then else's statement is printed: #include<stdio....
You have to know how floating points works. Floating points are represented by using powers of two, each digit is used to represent 2^-x where X is the n-th digit. For example, 0.011 (binary) would be 2^-2 + 2^-3, which is 0.25 + 0.125 = 0.375 Now try to represent 0.9. You are in trouble, since no power of two to repre...
7,580,523
7,580,575
Why comparing 2 strings doesn't give desired result?
Below is the code I've come up with and in all honesty tonight is my first attempt at coding at all. However I cannot seem to get my if statement to work properly. It just simply jumps to else even if I type Westley or westley or (space)Westley. I want the program to be able to accept any of my team members names ...
First of all, if you are coding with C++ you should use std::string instead of char []. It has the convenience that you can compare two strings (alas with char [] you have to call functions like strcmp or the like). For example: #include <iostream> #include <string> // <-- important using namespace std; int main () {...
7,580,635
7,581,655
How to copy (or swap) objects of a type that contains members that are references or const?
The problem I am trying to address arises with making containers such as an std::vector of objects that contain reference and const data members: struct Foo; struct Bar { Bar (Foo & foo, int num) : foo_reference(foo), number(num) {} private: Foo & foo_reference; const int number; // Mutable member data elided ...
If you implement this with move operators there is a way: Bar & Bar :: operator = (Bar && source) { this -> ~ Bar (); new (this) Bar (std :: move (source)); return *this; } You shouldn't really use this trick with copy constructors because they can often throw and then this isn't safe. Move constructors sh...
7,580,668
7,580,741
Binary search tree doesn't work
I'm having a pretty confusing problem in building a binary tree. Apparently this should be an easy task but somehow I may mess up with the pointers in it. Here's the simplified code (of course it's not the real code) : #include <string.h> #include <iostream> using namespace std; #define DIM1 2 typedef enum {LEFT,...
Within the following lines struct Rectangle rect; ... point = &rect; ... recTree = point; you assign a reference to a local variable to a global pointer. After leaving the function it may no longer contain valid data.
7,580,904
7,581,069
Effective search of number pairs
I have a problem, where i have big list of number pairs. something like that: (0, 1) (10, 5) (5, 6) (8, 6) (7, 5) ..... I need to make that i can make very fast lookups if the pair exist in list. My first idea was make map< std::pair<int,int> > container. and do searches using container.find(). Second idea was to mak...
If you want faster-than-set lookups (faster than O(lg n)) and don't care about items being in a random order, then a hashtable is the way to go. This is not part of the standard, but a hash_set is available in most compilers. The reference for it is here. If you want to have really fast searches, you can try a Bloom fi...
7,581,223
7,587,347
how to print time in micro seconds using ctime() function?
HI how to print time in macro second also with the use of following function in c++, I am using, time_t rawtime; time(&rawtime); std::cout<<"Cuuent TIme is :: "<< ctime(&rawtime)<< std::endl; Above code will give me only hours, minutes and second. I also need the micro seconds. Any suggestion how to get time with mi...
I used following code to get time in H,M,S,mS: char timeBuf [256]; struct timeval tv; struct timezone tz; struct tm *tm; gettimeofday(&tv, &tz); tm=localtime(&tv.tv_sec); sprintf (timeBuf, "%02d:%02d:%02d:%03ld",tm->tm_hour, tm->tm_min, tm->tm_sec, (tv.tv_usec/1000) );
7,581,257
7,584,087
Threads/Sockets limits in Linux
First of all: sorry for my english. Guys, I have a trouble with POSIX sockets and/or pthreads. I'm developing on embedded device(ARM9 CPU). On the device will work multithread tcp server. And it will be able to process a lot of incoming connections. Server gets connection from client and increase counter variable(unsig...
Whenever you hit the thread limit - or as mentioned run out of virtual process address space due to the number of threads - you're.... doing it wrong. More threads don't scale. Especially not when doing embedded programming. You can handle requests on a thread pool instead. Use poll(2) to handle many connections on few...
7,581,350
7,581,463
Problem with memory deallocation for non-dynamically created std::vectors storing normal (i.e. non-dynamically allocated) data
Consider the following code, compiled with g++ problem.cpp -o problem: #include <vector> using namespace std; int main() { while(1){} return 0; } When this code is executed, the command top reports that ~80K of memory is being consumed. Now consider this code: #include <vector> using namespace std; int mai...
You should probably just ignore it. The swap trick frees the memory from the vector, but that does not mean that the allocator (or even the malloc or equivalent implementation underneath) will yield the memory back to the system. That is, the vector is most probably not the one holding the memory up.
7,581,654
7,584,145
About catching exception good practices
I'm writing a little program in C++11 and really use exceptions for one of the first time. I've got a question about how to catch the exceptions efficiently, and after some googling I still don't have the answer. Here is the question : What is the more efficient (or recommended) between catching the exception by (const...
You should catch by const lvalue reference (2): try { throw std::exception{"what"}; } catch (const std::exception& ex) {} Rationale: In C++11 it is possible (via use of shared_future) that two threads could be unwinding the same exception at the same time. This can happen in your code even if you are not aware of sha...
7,581,680
7,581,713
pass c_str return value of temporary object to printf
Is the following piece of code valid? class A { string m_name; public: string getName() { return m_name; } } ..... printf("%s", object.getName().c_str()) ...... where object.getName() returns a temporary string object.
The temporary string will persist for until printf() completes so yes, it is safe and legal.
7,582,264
7,582,304
Using hyphen or underscore as word separator for files under Linux
I get always confused when I have to give a new name for a new data or executable file under linux, to use underscore or the dash to separate words in the name. My question: Are there any standard or guide to follow to know when to use this or that?
$ ls /usr/bin/*_* | wc -l 120 $ ls /usr/bin/*-* | wc -l 717 Some files are actually duplicated in both lists: x86_64-linux-gnu-cpp, but you probably get the idea that there are more dashes that underscores. Additionally there are files where there is no separation whatsoever as in atktopbm, bdftruncate... not really s...
7,582,300
7,582,343
Jsoncpp stop making it write based on elements alphabetical order
I am using Jsoncpp to write a Json::value to a string using the Json::FastWriter. string s; s.append("me?json="); val["firstname"] = firstname; val["lastname"] = lastname; val["x"] = me->myPos.X; val["y"] = me->myPos.Y; val["z"] = me->myPos.Z; val["lookx"] = me->myOri.X; val["looky"] = me->myOri.Y; val["lookz"] = me->m...
Most likely Jsoncpp uses a std::map to store the key/value pairs, and it will return you an alphabetically-ordered key/value pairs. I've not looked into the code of Jsoncpp, but you have two alternatives: Change the code to use internally a std::list or some other ordered container (vector, etc.). That may result in p...
7,582,398
7,582,487
Rotate a vector about another vector
I am writing a 3d vector class for OpenGL. How do I rotate a vector v1 about another vector v2 by an angle A?
The easiest-to-understand way would be rotating the coordinate axis so that vector v2 aligns with the Z axis, then rotate by A around the Z axis, and rotate back so that the Z axis aligns with v2. When you have written down the rotation matrices for the three operations, you'll probably notice that you apply three matr...
7,582,546
7,582,576
Using generic std::function objects with member functions in one class
For one class I want to store some function pointers to member functions of the same class in one map storing std::function objects. But I fail right at the beginning with this code: #include <functional> class Foo { public: void doSomething() {} void bindFunction() { // ERROR ...
A non-static member function must be called with an object. That is, it always implicitly passes "this" pointer as its argument. Because your std::function signature specifies that your function doesn't take any arguments (<void(void)>), you must bind the first (and the only) argument. std::function<void(void)> f = std...
7,582,548
7,582,634
Understanding C++ member function template specialization
I have the following class: #pragma once #include <string> #include <iostream> class testclass { public: template <class T> T item(const std::string& key) { std::cout << "non-specialized\n"; return T(); } }; For the item method I would like to provide a specialization for strings. I try to...
The problem boils down to the common problem of not having the templates in the header file. The compiler, when processing main does not see the specialization and it generates its own instantiation of the generic template for std::string. This is a violation of the ODR, as there are now 2 different specializations for...
7,582,597
7,582,661
How does this forces singleton?
In some code, I saw singleton template template<typename T> class Singleton { public: Singleton(T& instance) { assert(!sfpInstance || (sfpInstance==&instance)); sfpInstance = &instance; } static T& getInstance() { assert(sfpInstance); return *sfpInstance; } privat...
This code won't work at all since there is no publicly available constructor of MyClass and Singleton is no friend of MyClass. Now, if the MyClass constructor /were/ public, each call of the MyClass constructor would check whether the global sfpInstance pointer already points somewhere object, and triggers the assertio...
7,582,601
7,582,623
Overload operator= to exchange data between to classes
I'd like to use two classes A and B for some different types of task. But i want to exchange some data, which should be similar in both, so i'd like to use a A = B for ex. So, how to use this, with avoiding two-way including in header files? Example: in class_a.h: #include class_b.h class A { private: int i; pu...
You must forward-declare the other class: class B; class A { private: int i; public: A& operator=(B& const b); } Also note that you should probably declare friend class B; inside the definition of A if you don't have getters and need to access B::n.
7,582,690
7,582,912
two's complement finding algorithm
I am trying to see how compiler writes in binary negative numbers, so here is code which should do it #include <cstdlib> #include <iostream> using namespace std; void complement(int n) { int l = n; int s = 0; int k = 0; int m = 0; while (n != 0) { s = n % 2; n /= 2; c...
If you want to see the bits of number you better use such constructs: int main(int argc, _TCHAR* argv[]) { int i = -10; //my value std::string result; for (int bit = 0; bit < sizeof(int)*8; ++bit) { int bit_val = 1 & i; result = (bit_val ? "1" : "0") + result; i = i >> 1; } ...
7,582,937
7,583,014
How to provide free begin/end functions for your own types
In one of his latest talks, Herb Sutter recommended to prefer the free begin(container) end(container) functions templates over container.begin(). I like it, because these function can be provided for all iterable types that don't come with begin()/end() methods. Since most of my domain classes have interfaces that tal...
I would let ADL do its work. While you are allowed to add specializations in the std namespace, there is no strong reason I can think of for doing so when a plain free function in your namespace suffices. In particular for the range for loops, the standard states: §6.5.4/1 (definition of begin-expr and end-expr): ot...
7,583,074
7,583,144
How to realise long-term high-resolution timing on windows using C++?
I need to get exact timestamps every couple of ms (20, 30, 40ms) over a long period of time (a couple of hours). The function in which the timestamp is taken is invoked as a callback by a 3rd-party library. Using GetSystemTime() one can get the correct system timestamp but only with milliseconds accuracy, which is not ...
Deleted article from CodeProject, this seems to be the copy: DateTimePrecise C# Class The idea is to use QueryPerformanceCounter API for accurate small increments and periodically adjust it in order to keep long term accuracy. This is about to give microsecond accuracy ("about" because it's still not exactly precise, b...
7,583,090
7,583,178
split function for C++
Is there a split type function for C++ similar to Java? I know of ignore, but I don't quite understand it, and how it'll work for my case. My input is: { item = ball book = lord of the rings movie = star wars } My input given is an <attribute> = <value> and I have to store the two in different strings, or integ...
Use Boost::tokenizer as it does what you want to do. From the manual: // simple_example_1.cpp #include<iostream> #include<boost/tokenizer.hpp> #include<string> int main(){ using namespace std; using namespace boost; string s = "This is, a test"; tokenizer<> tok(s); for(tokenizer<>::iterator beg=tok.be...
7,583,163
7,600,236
How do I retrieve the path to my dylib at runtime?
On OS X, how can code in a dylib find the path it was loaded from, at runtime? Coming from a Windows background, I'm used being able to call GetModuleFileName(dllHandle,...). There exists NSGetExecutablePath() which will give me the path of the executable for the current process. Is there an equivalent to give me the c...
Use dladdr(3). Given a memory address, dladdr() outputs a structure that has, amongst other data, the path of the library containing the address. For example, inside your library: #include <stdio.h> #include <dlfcn.h> void test(void) { Dl_info info; if (dladdr(test, &info)) { printf("Loaded from path =...
7,583,216
7,584,361
Is the C++ boost binary serialization library backward/foward compatible?
Possible Duplicate: Boost Serialization Library upgrade I am trying to find a serialization solution for a C++ application. I would really like to be able to use boost binary serialization. If I were to serialize an object using an older version of the boost binary serialization library, will an application that is ...
They do it by incrementing the version in the header. So yes, it's compatible in a sense that you will get a graceful failure if you try to read binary data serialized with incompatible version as 1.45.0 release notes tend to indicate. Moreover there are bugs in 1.42 and 1.43 that break it! Native binary archives crea...
7,583,361
7,583,830
Find out character at particular console location
Is there any way to read a character from a specific location on the console? For example Read_Console_Char(10, 40);?
I don't know if there is a standard way to do this, but in Windows environment you can do that. I've never read from arbitrary location, just writing to it with the use of SetConsoleCursorPosition and GetStdHandle. I Just looked on MSDN and there are related API's to get the contents, such as ReadConsoleOutput. Here i...
7,583,447
7,583,503
Is this correct C++0x code?
Tried this in GCC 4.6 and it compiles and links, but gives a "bus error" message on runtime on MacOS. VS2010 doesn't even compile it. But the question is, should this actually work in standard C++0x? #include <cstdio> int (*main)()=[]()->int{printf("HEY!\n");return 0;}; Yes, what it's trying to do is to define "main" ...
This is not a valid C++ program, because the symbol main is not defined to be a function, but rather a pointer to function. That's why you get segmentation fault -- the runtime is attempting to execute a pointer.
7,583,710
7,583,793
Including .cpp at end of template header file
I was reading an older data-structures book and it said that when you're doing template class programming you should include the .cpp at the end of the .h file. As far as I know you have to do full function implementations in your .h file for any template class member functions - it's due to the way the template compil...
Most likely the author prefers having declaration and definition in different files, I can guess this is because it makes it easier to jump between declarations and definitions. But having "cpp" file extension is a bit confusing. Usually those files are called "ipp" for "Inline C++".
7,583,832
7,583,862
Passing parameter from one class to another
Problem: I have a function that gets passed data and a size. But I want another function dedicated to "getting the size" so i can call it and find out what it is. Is there any way to point to what is passed into my function (the one passed data and size) and bring the size to my GetSize function so it can return size?...
Make a class variable that contains size, something like: In class.cc int getSize() { return size_; } void func(int data, int size) { size_ = size; } In header.h int size_;
7,583,976
7,584,035
sprintf with C++ string class
I really liked the answer given in sprintf in c++? but it still isn't quite what I'm looking for. I want to create a constant string with placeholders, like const std::string LOGIN_URL = "%s://%s/chronicle/spring/api/logout"; and then build the string with replaceable parameters like: sprintf(url, LOGIN_URL, protocol,...
Boost format library sounds like what you are looking for, e.g.: #include <iostream> #include <boost/format.hpp> int main() { int x = 5; boost::format formatter("%+5d"); std::cout << formatter % x << std::endl; } Or for your specific example: #include <iostream> #include <string> #include <boost/format.hpp> in...
7,584,127
7,584,229
how to set in a binary form of number at some position 1 or 0
Suppose I have an eight bit number, I want to set at each bit position number 1 or zero, it is dynamic situation. Suppose for example such situation, user enters two numbers which are equal or differs only by one, and I want that at each iteration from 0 position to seven, write these 0 and 1 in binary form of number, ...
I don't know what happens if your inputs are different by two but you might want something like this: int result = 0; for (int i = 0; i < num_bits; ++i) { int a, b; std :: cin >> a >> b; result |= (a != b); result <<= 1; }
7,584,139
7,584,255
How do I setup libxml in Eclipse Indigo CDT C++
This all is under Mac OS X 10.6 and the libxml libraries seem to be in /usr/local/libxml2/libxml, I added this to the GNU C++ support but still I get errors for the code that uses libxml. I couldn't find anything that explains what to do to get it working and my project to compile. edit: Example errors void printElemen...
I got this here: forum Right-click your CDT project and select Properties. Expand C/C++ General and select Paths and Symbols. Select GNU C++ under Languages Click Add to define new element Write in the Directory field /usr/local/libxml2/libxml Re-build
7,584,320
7,585,567
Sorting the EdgeList in boost::graph
I would like to to sort the edge List of boost::graph defined as followed: struct Vertex{ int index; }; struct Edge{ double weight; }; boost::adjacency_list<boost::listS, boost::listS, boost::undirectedS, Vertex, Edge> Graph; After adding the vertices and edges, how to I sort the edge list. Getting the edge with the...
Sorting the edges is not idiomatic boost::graph. Look at the BGL implementation of Kruskal's algorithm for spanning trees. The algorithm needs to look at each edge in increasing order of weight. std::priority_queue<Edge, std::vector<Edge>, weight_greater> Q(wl); /*push all edge into Q*/ typename graph_traits<Gr...
7,584,589
7,584,650
c++: class declaration and definition separated inside header causes Duplicate Symbol
I usually only have the definitions of my classes inside a header if they are template classes.- If this is the case, i still like to split declaration and definition inside the header like that: template<class T> class Foo { public: Foo(); void fooFunc(); }; template<class T> Foo<T>::Foo() { } template<c...
Yes, it's expected behavior. Inline functions are meant to be compiled separately into each call site so duplication is no problem. For template functions, the compiler flags them in the object file such that the linker will basically ignore duplicates, since it can be difficult to predict where the template will or w...
7,584,627
7,584,873
How to get a list of physical storage devices?
I want to get a list of physical storage devices. I've seen some code but that actually loops and does something like brute force. I want to know what is the general way of getting the list of physical storage disks. I've found CreateFile(). But I cannot understand how to use it properly. I need a non-wmi solution. an...
I've used the following code, that enumerates all the volumes and then looks for their corresponding physical drives: #include <windows.h> #include <commctrl.h> #include <winioctl.h> typedef struct _STORAGE_DEVICE_NUMBER { DEVICE_TYPE DeviceType; ULONG DeviceNumber; ULONG PartitionNumber; } STORAGE_DEVICE_NUM...
7,584,781
7,584,956
Inclusion of header files in case of templates.
When we make a class we declare its functions in a header files and define them in a source file... then the header file can be included in the main file to use the class... But if we declare a template class in header files and define it in the .cpp file and then if we include the header file in the main(containing in...
Templates don't actually produce any object code at the point where the compiler reads their source code; they're (typically) only "instantiated" when something actually uses the template. So if you define a template function in one source file, and call it from another, the code for the template function doesn't get ...
7,584,949
7,585,391
Screen resolution change notification message?
I have a WTL app running and would like to know when the screen resolution has changed. The most likely candidate would appear to be SPI_SETWORKAREA sent via the WM_SETTINGCHANGE message but I wondered if this is the correct message to use. This has to work on XP and Windows 7.
WM_DISPLAYCHANGE is the better mouse trap.
7,585,050
7,585,119
How to share share widgets pointers with another widgets
I have a kind of video player application written in QT, the idea is that I can click in an video frame and the app will get the coords and color information from this exact pixels, so far so good the application already works as spected, but the thing is that I have a control panel wish has an List Widget that I fill ...
You are trying to do it in lower level code, that is why it is awkward. Neither widget has the context of the other. Just create signal/slots on the two widgets you want to communicate, then have the calling scope connect them after they are created.
7,585,165
7,585,216
C++ won't let me use a struct as a template argument
Perhaps it is a header problem of sorts... But this is what's happening: The compiler is giving me an error on the line: Queue<Email> mailbox; This is the error: ..\EmailSystem.h:25: error: ISO C++ forbids declaration of `Queue' with no type ..\EmailSystem.h:25: error: expected `;' before '<' token Queue.h: #ifndef Q...
You have a circular include. Queue.h includes EmailSystem.h and EmailSystem.h includes Queue.h so the include guards make sure that the header has no effect the second time it is being included. This means if Queue.h is the first to be included then Queue will not yet be declared before it is first used in EmailSystem....
7,585,275
7,585,290
c++ win32 changing the application display name
I've developed a win32 api application using c++. It was developed using visual studio 2010. When i started developing i gave it a codename and now when it's done i would like to change the applications name, but don't know where to change it (i'm quite new to win32 and visual studio). I would like to change the .exe ...
Edit the version resource in your .rc file.
7,585,523
7,643,851
Generate SOAP Envelope and digital signature
So currently we have a model of just writing a SOAP Body and then manually wrapping that into a SOAP Envelope that is done in a script. That then gets passed to an app that makes a request to a webservice. Also, the language the app that would generate the soap would be C++ not C#. I am looking into building a SOAP Ge...
For the XML signature part you could use Apache Santuario.
7,585,534
7,585,688
Fill template of one class from another template class
If I have two classes: template <typename T> struct Node { ... }; tempalte <typename T_Node, typename T> struct NodeIterator { T m_value; }; NodeIterator<Node<int>, int> can I deduce the template argument T from T_Node without the class Node explicitly creating a typedef like this: // To make it clear, yes I kno...
Without the typedef, that's not possible. The point is that the compiler has no idea that T_Node is itself an instantiation of a template. Node<T> is just a type, nothing more. C++ knows three tiers of entities: values, types, and templates. Node is a template, and Node<T> is a type. When your class template accepts a ...
7,585,625
7,585,678
Precedence of post and pre incrementation operators
There is code: #include <iostream> class Int { public: Int() : x(0) {} Int(int x_) : x(x_) {} Int& operator=(const Int& b) { std::cout << "= from " << x << " = " << b.x << std::endl; x = b.x; } Int& operator+=(const Int& b) { std::cout << "+= from " << x << " + " << b.x << s...
The order of evaluation of the different operands is unspecified which means that the compiler is free to reorder the evaluation of the ++a, b++ and ++c subexpressions as it pleases. The precedence of the operators does not really have any impact in that example. It does have an effect if you try to write ++i++ (where ...
7,585,656
7,585,748
Why does LLVM complain about missing function prototypes?
LLVM 2.1 has an option that enables warnings for "missing function prototypes." When enabled, the warning will complain about a file like this: double square( double d ) { return d*d; } void main() { // ... } The function "square" will trigger a warning because it is defined without having been declared (proto...
The compiler uses the prototype declaration to match types for the function definition. If you are writing the prototype in a header(interface) file and the implementation in the source file then this warning (by forcing you to provide a declaration, effectively) would prevent you from making a typo error where functio...
7,585,686
7,585,763
C++ Operator Problem
I don't know if this question is already answered on stackoverflow. But I simply can not find the right keyword to search for. I inserted some stripped down version of my code below. So basically what I'm trying to do in my main(), is to subtract 122 from t2. I suppose my compiler converts the integer to a Timestamp ob...
Contrary to what the other answers propose, you do not need to provide an specialized operator- that takes an int and a Timestamp, rather you can (and probably should) make operator- a non-member function: Timestamp operator-( Timestamp lhs, Timestamp const & rhs ); // Returns a timestamp?? really?? That way the compi...
7,585,694
7,585,889
Will clearing an already empty vector lead to undefined behavior?
What happens if I clear a vector which was already cleared before? I tried it out in Visual Studio and it did not lead to any run-time errors. But I'm hunting for a possible cause to an exception (below) And wanted to know if this could be the reason? *** glibc detected *** process.out: double free or corruption (out...
Calling the clear method twice in a row should be fine. Your error looks like you are freeing something which was already freed. This can happen because you called free twice on the same object or possibly put an object in your vector which was then deleted. Calling clear on your vector would then cause that error (...
7,585,696
7,585,899
Is there any way how to use Java window and input with Ogre3D and c++?
I'm not very familiar with wrapping between Java and C++. But i need to wrap Java window input to c++ and get window context, that i assign to ogre. I know it's possible, because Ogre4J uses something similar. "Use Ogre4j" isn't answer.
I never tried it because JOGL was easier to use but here, you have an example how to use opengl directly with Java. That should be similar with OGRE. I guess. Or you could look at Ogre4j and see how they get the native context from the Java window.
7,585,736
7,585,755
What Kind Of Macro Is this?
I came across this following code: #include<stdio.h> #define d(x) x(#x[3]) int main(){ d(putchar); } Which prints c as the output. I wonder what does the macro #define d(x) x(#x[3]) does? In C language is there an operator like #? I can see this inside the macro body i.e here x(#x[3]). According to my normal eye it l...
The character '#' is a stringizer -- it turns a symbol into a string. The code becomes putchar("putchar"[3]);
7,585,744
7,598,784
How to pass a parameter of type pointer to PVOID from LabView to DLL?
I'm calling a DLL written in C++ from LabView. The function prototype is: ULONG DAQ_Open(PVOID *pHandle); How can I pass the correct parameter from LabView? Is it just impossible to pass parameters of type pointer to pointer from LabView to DLL?
As long as you're not expecting to pass a pointer to a LabVIEW VI to use as a callback (which is a seperate, and much more difficult answer), the parameter is just a pointer. When you configure your call library node, use the type "numeric" and the data type "unsigned pointer-sized integer" and pass "pointer to value....
7,585,918
7,585,950
Can a class still be pure abstract if it has a non-pure destructor?
I am working on an exercise which asks me to take a base class Rodent and make it a pure abstract class. My understanding of a pure abstract class is that it acts as an interface and only contains pure virtual functions. Although this is an easy exercise I have a problem with the solution provided by the book: class Ro...
An Abstract class must contain atleast one pure virtual function. Your class already has two pure virtual functions run() and squeak(), So your class is Abstract because of these two pure virtual functions. You cannot create any objects of this class. EDIT: A pure abstract class, is a class that exclusively has pu...