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
4,651,872
4,651,941
ofstream does not print out newline to txt in Windows7
I have some issue when I want to print out \n I'm using endl for that. And the problem is when I run the code on Windows7 it won't print out the newline. But it will print out newline in Ubuntu. Both OS is using the same compiler GNU g++. So I wonder if there are some different way to print newline to file in Windows? ...
Outputting either '\n' or using endl will result in the exact same content (the only difference is endl also flushes). When that \n character is written, if the file is in "text mode", the runtime library converts it to the platform's native mechanism to indicate lines. On unix, this is unnecessary because that mecha...
4,651,942
4,652,212
how to use a SWIG generated C++ class in a java program
I am successfully building a shared library that is C++ and loading it in my Java program with System.loadLibrary() My class in the C++ file was called Classifier How do I instantiate a new "Classifier" object in java? Do I have to compile and include the java files that are generated from Swig to do such a thing? If I...
Used correctly, SWIG will have generated a wrapper Java class called "Classifier." Yes, this needs to be compiled -- e.g., by including it in your IDE project and/or your build. The SWIG documentation for Java shows how to instantiate a C++ object from Java: C++ classes are wrapped by Java classes as well. For examp...
4,651,959
4,652,199
Is there a more elegant way to achieve a "cheat code" implementation for a game in C++?
I have been learning C++ by diving into a project, a simple 2d game. I have attempted to implement a set of cheats but I'm seriously novice at string manipulation. I'm sure there would be a more elegant way to achieve what I would like than my code below. As requested, stringBuffer is just a string that contains the l...
You might want to consider using: std::map<std::string, std::function<void ()>> (If you can use C++0x) std::map<std::string, std::tr1::function<void ()>> (If you can use TR1) std::map<std::string, boost::function<void ()>> (If you can use Boost) (Of course, the signature of the function can differ) Example using C++0x ...
4,652,144
4,652,551
How to correctly call on onsubmit event using IWebBrowser2 interfaces (using c++)
I'm trying to call the onsubmit programmatically without clicking in the form button. First i try to simply call the submit function of the IHTMLFormElement interface but the form does not correctly processed the input data: CComPtr<IHTMLFormElement> ppvForm; ppvForm->submit(); I read in the documentation and it says ...
If get_onsubmit() is returning S_OK and a NULL handler, then there is simply no onsubmit event handler assigned to the form to begin with.
4,652,157
4,652,179
Storage size of 'var' isn't known
I have a program which works fine under VC++, but is giving me an error under GCC. within log.h: namespace logType { enum Enum { None = 0, Info, Warning, Error, }; std::string Name[]; } within log.cpp: std::string logType::Name[] = { "None", "Info", "WARNING",...
Add extern to log.h's declaration of your Name. Your symbol appears in two places.
4,652,274
4,652,287
Which integer data type uses x64 CPU core most efficiently?
Adding up two 32-bit integers and two 64-bit integers takes the same instruction time in a x64 machine, doesn't it? If so, when I use 32-bit integers in a x64 CPU core, the other 32 bits do not do any good, do they? I want to do my calculations inside the largest possible numeric range that would fit in a 64-bit core. ...
m128i N 32-bit adds takes as long as N 64-bit adds only if you aren't using the SIMD unit.
4,652,291
4,653,062
C++ Xerces-c: Initializing a shared_ptr
I am new to shared pointers and was wondering how to initalize a shared pointer if it is also a member variable? Currently my code looks something like this: In the header file, I have: class Parser { public: Parser(); ~Parser(); boost::shared_ptr<XercesDOMParser> parser; { In the constructor, I...
You are calling XMLPlatformUtils::Terminate() before calling the destructor for XercesDomParser. Destructors for member variables are called after the destructor body runs. Member variables are constructed in order of declaration, and destroyed in reverse. You could do something like this: class Parser : boost::noncopy...
4,652,322
4,652,542
Win conditions for Match 3 game
I have a randomly generated 10x5 array that I want to check when 3 numbers match both horizontally, and vertically. I can't figure out a good way to do the check to see if the numbers match. The way I am currently doing it, it would take me over 70 if statements, and I know there is a better way. I don't think I can us...
The only difference I see between this question and your previous question is that you want to know the location and direction of the match. In that case, here is a minor modification to @templatetypedef's function. enum Direction { NONE, VERTICAL, HORIZONTAL, DIAGONAL_UP, DIAGONAL_DOWN }; Direction IsLineStartingAt(...
4,652,474
4,652,698
Transform camera position in OpenGL
I draw a sphere with OpenGL which will be transformed by glRotate(), glScale(), glTranslate(). How could I get the absolute Position of the Object without calculating all transformations on my own? I need the coordinates for setting the camera eye position to this point.
When using those transformations, you are manipulating the modelviewmatrix To get the current one you can use ( http://linux.die.net/man/3/glgetfloatv ) void glGetFloatv( GLenum pname, GLfloat * params ); for example: float modelview[16]; // save the current modelview matrix glPushMatrix(); // get the current modelv...
4,652,501
4,652,525
Where to store data?
I have created a c++ program but now I need to store on the hard disk permanently some settings about the program. Where do I have to store this data ? In a sqlite database ? In the windows registry ( if linux ? ) ? In a XML file In other files ?
It depends on the type and size of data. For small and less complex data simple text files are better. for complex data you can use XML or sqlite database. If you need to write complex queries go for sqlite. It stores data in files but will give better query options.
4,652,507
4,654,027
Capturing WM_MOUSEMOVE events in parent window
I have a (parent) window in which a child-window is created by a another library (Ogre3d). Window initialization uses the bare Win32 API. I'd like to capture the mouse input in my parent window, but it seems like I my WM_MOUSEMOVE events are received only by the child-window, which makes sense, since that fills all of ...
If you can obtain a handle to the window in question you can subclass it. In a nutshell, you get to register a callback function that gets a crack at all of the messages sent to the sub-classed window. The linked article should get you where you need to be.
4,652,519
4,652,962
Are UTF16 (as used by for example wide-winapi functions) characters always 2 byte long?
Please clarify for me, how does UTF16 work? I am a little confused, considering these points: There is a static type in C++, WCHAR, which is 2 bytes long. (always 2 bytes long obvisouly) (UPDATE: as shown by the answers, this assumption was wrong). Most of msdn and some other documentation seem to have the assumption...
Short answer: No. The size of a wchar_t—the basic character unit—is not defined by the C++ Standard (see section 3.9.1 paragraph 5). In practice, on Windows platforms it is two bytes long, and on Linux/Mac platforms it is four bytes long. In addition, the characters are stored in an endian-specific format. On Windows t...
4,652,638
4,652,889
How to pass strings to C++ function from Java using SWIG generated interface
I have a bunch of C++ functions that take C std:string as function parameters. I want to pass java Strings to those functions. I have generated a SWIG JNI interface between Java and C++. I can see the no-args constructor fine, but if I try to compile my java with the String arguments in the constructor, I get "cannot f...
One way, if you have a small set of functions to call, might be to simply wrap the C++ methods that take std::string with methods that take char* and call them from Java with Java Strings since the default type-map between Java String C++ char* will work as expected. You could also add something like this to your inter...
4,652,783
4,652,843
is it proper to have a construction function?
My class has many constructors and it has a lot to do in the constructor so I was thinking of making a private construct() function to promote code reuse. Is this a good idea? Because I see many libraries that do not do this and have code duplication. Thanks
This is totally fine and is probably a good idea. What might be concerning is having so many constructors. But it's impossible to say.
4,652,855
4,652,941
What runs before main()?
After testing on msvc8, I found: Parse GetCommandLine() to argc and argv Standard C Library initialization C++ Constructor of global variables These three things are called before entering main(). My questions are: Will this execution order be different when I porting my program to different compiler (gcc or armcc),...
1: Will this execution order be different when I porting my program to different compiler (gcc or armcc), or different platform? Yes. 2: What stuff does Standard C Library initialization do? So far I know setlocale() is a must. I am sure there is other stuff. You should not rely on any global objects util after mai...
4,652,874
4,653,048
Resize an array of images with OpenCV
I'm passing an array of images (IplImage**) to an object in C++ using OpenCV. I'm then trying to iterate over that array and resize them all to a fixed size (150x150) I'm doing it this way: for(int i = 0; i< this->numTrainingFaces; i++) { IplImage* frame_copy = cvCreateImage( cvSize(150,150), this->faceImageArray[0...
Why do you use the C interface when you're using C++? The C++ interface is far friendlier and you wouldn't have had this problem with it. Your error is simple - your image differ in type, so you can't use the type from the first image for all images. The line IplImage* frame_copy = cvCreateImage( cvSize(150,150), thi...
4,652,878
4,653,134
Initializing a GLfloat
Why can't I do this? #include <gl/gl.h> GLfloat posX; posX=0.0f; Visual Studio says: error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
The text posX=0.0f; is at global scope, so is treated as a declaration, not a statement. Consider: #include "stdafx.h" #include <windows.h> #include <gl/gl.h> GLfloat posY = 0.0f; GLfloat posX; posX = 0.0f; GLfloat posZ; int _tmain(int argc, _TCHAR* argv[]) { posZ = 0.0f; return 0; } Then posY, posZ com...
4,652,932
4,652,965
Why define operator + or += outside a class, and how to do it properly?
I am a bit confused about the differences between Type operator + (const Type &type); Type &operator += (const Type &type); and friend Type operator + (const Type &type1, const Type &type2); friend Type &operator += (const Type &type1, const Type &type2); which way is preferred, what do they look like and when sh...
The first form of the operators is what you would define inside class Type. The second form of the operators is what you would define as free-standing functions in the same namespace as class Type. It's a very good idea to define free-standing functions because then the operands to those can take part in implicit conve...
4,652,959
4,652,972
Iterator to LONG_PTR
would I be able to cast iterator that is pointing to a set element to a LONG_PTR? PS: I don't fully understand what is LONG_PTR? Here is an example code which pops an error at runtime #include <windows.h> #include <set> #include <string> using namespace std; void func(LPARAM lp) { set<string>::iterator *it = reint...
A LONGPTR is an __int3264. In any case, you can't cast an iterator to this type because an iterator is not a pointer. You can, however, take the address of the element pointed to by the iterator (using &*it), assuming the type of object stored in the container does not overload the unary & (if it does overload the una...
4,652,970
4,892,086
How can I prevent Visual Studio from warning about a lack of debugging information?
How do I prevent VS from showing user the following warning: No Debugging Information Debugging information for 'MyExe.exe' cannot be found or does not match. Cannot find or open the PDB file. Do you want to continue debugging? In my situation the user of my product wants to develop a plugin and (s)he want to debug...
You don't say which version and edition of VS your customer is using, but at least in VS 2005 and VS 2010, open Tools->Options->Debugging->General, there is a list of settings, scroll down, find the "Warn if no symbols on launch (Native only)" setting and clear the check mark. I believe that this will accomplish what ...
4,653,119
4,653,144
Cannot convert from char (*)[10] to char** in return
Possible Duplicate: Declaring a function that return a 2D array in a header file? I am trying to have a simple getter function for a 2D array, and I can't seem to figure out the correct syntax to send it. Currently, I have the following: class Sample { public: char **get2D(); private: static const int x ...
An array of arrays is different from an array of pointers to arrays. In your case, you can't return the correct type without the width of your array (y) being published in your public interface. Without that, the compiler doesn't know how wide each row of the returned array is. You could try the following: class Sample...
4,653,390
4,653,422
Is it fair for us to conclude XOR string encryption is less secure than well known encryption (Say Blowfish)
I was wondering, is it fair to conclude, XOR string encryption is less secure than other encryption method, say Blowfish This is because for both methods, their input are Unencrypted string A secret key string XOR(string value,string key) { string retval(value); short unsigned int klen=key.length(); sho...
If your key is (a) truly random, (b) at least as long as the plaintext, and (c) never re-used then XOR encryption is proveably unbreakable. If you can't meet those stringent criteria then XOR encryption is proveably weaker than proper encryption algorithms like Blowfish, though I'm not in a position to prove it myself....
4,653,507
4,653,536
Equivalent C++ nested print in python
I'm trying to run this C++ statement in python and I'm having trouble placing the print in the loop. for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) { cout<<_3x3x3[i][j][k]<<" "; } } //print here in python cout<<endl; } in ...
for i in range(3): for j in range(3): for k in range(3): # something here print _3x3x3[i][j][k], print
4,653,658
4,653,892
Why should non-POD types in C++ be opaque to C clients?
gcc 4.4.4 c89 I was just reading a discussion at DevX about calling C++ code from C since I have to do something similar. I am just wondering what user Vijayan meant by "make sure that non POD types in C++ are opaque to C clients." Many thanks for any suggestions,
For a type to be opaque means you can't look inside it: it's a "black box" that can be passed around but not inspected or manipulated directly by the C code. You typically refer to the object using either heap-allocated memory and void*s, or using functions to determine the necessary length and buffers. For example, a...
4,653,745
4,653,781
Why setting null in the middle of std string doesn't have any effect
Consider #include <string> #include <iostream> int main() { /* hello 5 hel 3 */ char a[] = "hello"; std::cout << a << std::endl; std::cout << strlen(a) << std::endl; a[3] = 0; std::cout << a << std::endl; std::cout << strlen(a) << std::endl; /* hello 5 h...
A std::string is not like a usual C string, and can contain embedded NUL characters without problems. However, if you do this you will notice the string is prematurely terminated if you use the .c_str() function to return a const char *.
4,653,836
4,653,874
Set of vectors in c++
How I can get the elements in the vectors set? This is the code I have : std::set< std::vector<int> > conjunto; std::vector<int> v0 = std::vector<int>(3); v0[0]=0; v0[1]=10; v0[2]=20; std::cout << v0[0]; conjunto.insert(v0); v0[0]=1; v0[1]=11; v0[2]=22; conjunto.insert(v0); std::set< std::vector<int> >::iterator it; ...
You're close. You need to pull the vector out of the set iterator. See below. main() { std::set< std::vector<int> > conjunto; std::vector<int> v0 = std::vector<int>(3); v0[0]=0; v0[1]=10; v0[2]=20; std::cout << v0[0] << endl; conjunto.insert(v0); v0[0]=1; v0[1]=11; v0[2]=22; conjunto.insert(v0); ...
4,653,846
4,653,856
Is it DLL-Safe to return iterators?
I'm referring to if the class comes from a DLL with its own heap, and it has a private vector, is it safe to have public functions which return iterators to that vector? Thanks
It is not. The fact that it has its own heap is what will prevent it from working correctly.
4,653,891
4,653,946
How can I get a stack trace of a remote (that is, not within my process) thread?
Let's say I'm writing a debugger. How do I build a stack trace on Windows systems? I don't need to enumerate symbols and such; just the addresses of the various function calls on the stack. I already have a handle to the thread with VM_READ access.
Billy, DBGHELP.DLL is your friend here. All sorts of useful functions for those who wish to perform debugger like activities... In it you find goodies like StackWalk64 and others that allow you to specify the target process to manipulate. Of course, you'll likely need to ensure that your debugger process has SeDebugP...
4,654,012
4,654,107
Unicode version of base64 encoding/ decoding
I am using base64 encoding/decoding from http://www.adp-gmbh.ch/cpp/common/base64.html It works pretty well with the following code. const std::string s = "I Am A Big Fat Cat" ; std::string encoded = base64_encode(reinterpret_cast<const unsigned char*>(s.c_str()), s.length()); std::string decoded = base64_decode...
Base64 encodes binary data as text. So you'll just need to convert your wide chars into their corresponding bytes using wcstombs & co and you're good to go.
4,654,017
4,671,746
Vectors of std::shared_ptr Lose Data
I am attempting to build std::vectors and std::maps of std::shared_ptrs, but they seem to have a habit of losing data. By that, I mean that when I push std::shared_ptrs into them, some of them will delete the data they point to. Specifically, the first std::shared_ptr to be pushed into a std::vector is deleted. This i...
Run your program through valgrind to locate the source of the segfault.
4,654,187
4,654,247
C++ Return sprite object from class in vector
I have an Entity baseclass which the classes Player and Enemy Inherit. Both player and enemy contain a sprite object (From the SFML api) that looks like this: class Player : Entity { sf::Sprite sprite } Player and Enemy are created inside a vector which is set up like this: class EntityManager { public: vo...
Since entityVector holds Entity* you'll need to use the proper syntax: entityVector[0]->sprite instead of entityVector[0].sprite.
4,654,224
4,654,234
Retrieve the Value of An Integer Variable
This is probably easily figured out, but I can't find a solution anywhere, for some reason. Perhaps I'm not searching for the right thing. And maybe it's in some beginner tutorial I haven't watched. Anyway, I was wondering how to retrieve the value of an integer variable in C++? I know you can use cin.getline() for str...
what is the problem with this? cin>>n; For math functions, float or double would be better option. int main() { double number; double result; cout<<"Enter a number:"<<endl; cin>>number; result = sin (number); //if you consider number is in radians //result = sin(number*3.14159265/180.0) //if you c...
4,654,261
4,654,428
Basic Bitmap Font Rendering
While I have made a topic like this in the past, this is from start to finish the most basic approach to bitmap font render. I am hoping someone can see what I am doing wrong here. Although this is a long post, if Bug#1 gets fixed, it could fix everything. This question deals with C# (Bug#1) and C++ (Bug#2, Bug#3). For...
1 - points and pixels are different units. So there is no bug there. Search for "fonts points pixels" for explanations. 3 - For proportional fonts (like Arial) each character have different width. In more advanced sceanrios combinations of characters can have different width compared to the sum of their individual widt...
4,654,269
4,654,976
Several errors during building shockwave ActiveX(Flash) in C++ Builder 2010
I have found one site where there is an instruction on how to build Shockwave ActiveX in C++ Builder but with errors. It comes from Chinese ... http://hi.baidu.com/luoshupeng/blog/item/c5bdaf446aed0988b3b7dc20.html Does anyone know how to build ShockWave ActiveX in C++ builder 2010 as I had a transition from c++ builde...
There's a reported issue over here that sounds similar to your problem. This comment below, in particular, sounds like a hint to solving your linking issues: The TLB declares the interface IDispatchEx, but doesn't provide implementations of virtual methods. As methods are not declared pure, linker is looking f...
4,654,322
4,654,475
How does SFML use std:: throughout its libraries while being DLL safe?
I keep reading that if the DLL is linked against another version of the runtime that doesn't match the other modules using it and it returns a std:: object or one of its classes has std:: arguments, it will cause the program to crash. How does SFML do it then? I do not see any warnings about this anywhere and they heav...
In theory, there are no guarantees of interoperability between different C++ runtimes, not even between different releases of the same compiler. And it seems that SFML releases separate Windows library downloads for VC++ 2005, VC++ 2008, and MinGW. But to say that mixing different runtimes will cause a crash is an exa...
4,654,431
4,654,451
How do I create an array in C++ using new and initialize each element?
Without iterating through each element, how do I create an array using new and initialize each element to a certain value? bool* a = new bool[100000]; Using VS 2008. Thanks!
In that case, the only value you can set it to is false with: bool* a = new bool[100000](); That said, I'm not sure why you'd think you can't use a loop. They're there for a reason. You should just use the ready-made function fill or fill_n (depending on taste). Note using new "raw" like that is terrible programming ...
4,654,611
4,654,648
Why does random() work in cstdlib? (Ubuntu 10.10)
I always thought the random functions in cstdlib were only rand and srand, but the following works (compiled with g++ on Ubuntu 10.10)? I actually found this out when moving from Windows to Ubuntu, my compilation failed as it was ambiguously overloading (I had declared my own 'random()' function). #include <cstdlib> #i...
Because compiler writers are free to add extra things to the language library to make your job easier. Normally, it wouldn't be a problem, because it puts them in a namespace which you won't be adding things to, std. Your problem arises from that little line using namespace std; This pulls everything from std into you...
4,654,636
4,654,718
How to determine if a string is a number with C++?
I've had quite a bit of trouble trying to write a function that checks if a string is a number. For a game I am writing I just need to check if a line from the file I am reading is a number or not (I will know if it is a parameter this way). I wrote the below function which I believe was working smoothly (or I accide...
The most efficient way would be just to iterate over the string until you find a non-digit character. If there are any non-digit characters, you can consider the string not a number. bool is_number(const std::string& s) { std::string::const_iterator it = s.begin(); while (it != s.end() && std::isdigit(*it)) ++...
4,654,701
4,654,732
Access object in derived class from Vector
I have an Entity baseclass which the classes Player and Enemy Inherit. class Entity { public: virtual void Update(sf::RenderWindow &window) {}; virtual void Draw(sf::RenderWindow &window) {}; }; Both player and enemy contain a sprite object that looks like this: class Player : Entity { public: sf::S...
If everything in your code that derives from Entity has a sprite object, then you should declare that object in the base class. Not declaring the object in the base class means that there could be a class inheriting from Entity that does not have a sprite object, which means that ColCheck has no valid basis for assumin...
4,654,731
4,655,849
BigInt conversion (gmp Bigint to botan bigint)
I am using gmp to perform complex operation. I want to use Botan to perform cryptography functions. Problem is Both of them have their own Bigint function. So its creating problem on supplying bigint value used in gmp function to Botan function. Can anyone help in this?
Use mpz_export to export the GMP integer and the BigInt(const byte[], size_t) constructor to import it.
4,654,748
4,655,002
get processes icon mfc c++
I am making a Process-Viewer like app. in windows which displays all the processes currently running in a CListCtrl . Now i want to get the icons of the processes and show them to the listCtrl. please help me how can i do that ?? thanks.
You can accomplish this using any of the following methods: The ExtractAssociatedIcon function. The SHGetFileInfo shell function The IExtractIcon shell interface The ExtractIconEx function Of these, the SHGetFileInfo may be the easiest.
4,654,856
4,655,070
QT_TR_NOOP: translation files are generated, but translated strings never used, why?
In an application I have a lot of classes that are apparently not descendants of QObject, and these objects apparently throw exceptions, and those exceptions apparently need to be translated. So, I enclosed every string thrown in exception in QT_TR_NOOP macro. That allowed me to generate translation files. But when I r...
It seems that I got the whole thing wrong :( QT_TR_NOOP is for marking strings for translation outside functions; it is supposed to return original text. What I needed was to apply translations to the non-qt classes, which is described in detail here: Internationalization with Qt: Translating Non-Qt Classes Sorry for b...
4,655,060
4,655,123
C++ (semi) Reflection for file save/load? (Hack?)
I have a bunch of structs in C++. I'd like to save it to file and load them up again. Problem is a few of my structs are pointers to base classes(/structs). So i'd need a way to figure out the type and create it. They really are just POD, they all have public members and no constructors. What is the easiest way to save...
Don't roll your own here - use something well-developed and tested. One idea is Protocol Buffers
4,655,149
4,655,840
elegant way to create&pass multi-dimensional array in c++?
first question: for known dimensions, we don't need new/malloc for the creation const int row = 3; const int col = 2; int tst_matrix[row][col] ={{1,2},{3,4},{5,6}} however, there is no easy to pass this two-dimensional array to another function, right? because int matrix_process(int in_matrix[][]) is...
My solution using function template: template<size_t M,size_t N> void Fun(int (&arr)[M][N]) { for ( int i = 0 ; i < M ; i++ ) { for ( int j = 0 ; j < N ; j++ ) { /*................*/ } } }
4,655,206
4,655,232
Is it valid, to use std::string to hold binary data, to avoid manual dynamic memory management
Pay attention to base64_decode in http://www.adp-gmbh.ch/cpp/common/base64.html std::string base64_decode(std::string const& encoded_string) The function is suppose to return byte array to indicate binary data. However, the function is returning std::string. My guess is that, the author is trying to avoid from perform...
Yes, you can store any sequence of char in a std::string. That includes any binary data.
4,655,217
4,655,416
How are software and game templates designed?
please don't mind my question since I don't know much about software because I come from a web perspective.. For example, in web css is used for the design and appearance so.. How are the designs, templates, and environments created for software and games made with programs like c++ and java? Are they designed with the...
There are many facets to developing a game. Most games consist of the following: 1) A rendering engine. This is the presentation layer and provides scene-graphs, math, particle effects, post-processing effects, and a whole host of other things. Unreal is such an engine. A good free rendering engine is Ogre 2) A sou...
4,655,332
4,655,718
UDP packets are dropped when its size is less than 12 byte in a certain PC. how do i figure it out the reason?
i've stuck in a problem that is never heard about before. i'm making an online game which uses UDP packets in a certain character action. after i developed the udp module, it seems to work fine. though most of our team members have no problem, but a man, who is my boss, told me something is wrong for that module. i hav...
Just to get one of the non-obvious answers in: maybe UDP checksum offload is broken on that card, i.e. the packets are sent, but dropped by the receiver? You can check for this by looking at the received packets using Wireshark.
4,655,403
4,655,485
Help using PCRE in C++
this is my first time trying to build a C++ application, so I'm kind of lost. I've looked at some examples but I still dont really know what's wrong. #include <iostream> #include <stdio.h> #include <windows.h> #include <pcrecpp.h> #include <string> #include <cstring> using namespace std; int main() { char title[2...
_imp___ZN7pcrecpp2RE6no_argE is a mangled name. Since it contains the parts pcrecpp and no_arg, I suspect that the problem is that you fail to link against Pcrecpp. Therefore, the no_arg symbol is not defined.
4,655,947
4,655,980
inline and good practices
Possible Duplicate: When to use inline function and when not to use it ? I have seen many source codes using different syntaxes regarding the inline directive. namespace Foo { class Bar { public: // 1 - inline on the declaration + implementation inline int sum1(int a, int b) ...
No, and no! inline is not just a hint to the compiler and it doesn't enforce internal linkage. inline is implicit on functions defined in a class body so you only need it on functions defined outside of classes. You should use it when, and only when, you need to enable the changes to the one definition rule that inline...
4,655,963
4,656,025
Pointer to Pointer to Pointer
Possible Duplicate: Uses for multiple levels of pointer dereferences? I was reading another post and this led me to this question. What the heck would something like this mean? Also how deep do people go with a pointer to a pointer to a pointer to a pointer.... I understand Pointer to Pointer but why else you would ...
It is rare in C++ certainly. In C it may well show up where: You use "objects" which are structs, and you always pass them around or create them on the heap as pointers. You have collections of such pointers as dynamically allocated arrays thus T** where T is the type. You want to get an array so you pass in a T*** an...
4,656,274
4,656,317
help using CWinThread in MFC
in my project im having manager class and calc class. calc class derived from CWinThread. and manager have a pointer to calc class. how do i using AfxBeginThread and where? note im new in mfc so im sorry if there is mistakes. thanks
You should be able to call Calc::CreateThread(). You need to override the CWinThread::Run() method to implement your functionality, and you might also want to override the CWinThread::InitInstance() and CWinThread::ExitInstance() methods too.
4,656,432
4,656,455
C++: how to store a sorted set of tuples?
Using GCC 4.x, g++ and STL. Which internal structure should be used to hold such array: ( (1,4), (2,8), (3,7) )? It should have static element numbers to keep the original (as added) order. Variants: set<map(int,int)> array<map> array {array[2], array[2]} Can this be done with vectors in a better looking way?
std::set holding std::pair is what first comes to mind however this might not comply with this requirement: It should have static element numbers to keep the original (as added) order.
4,656,568
4,795,668
Multiple Internet Explorer versions side-by-side in one application
in the MFC application I am working on, I need to have an Internet Explorer (we are using the component CHtmlView) displayed, currently we are able to change the rendering mode the IE works in by using the FEATURE_BROWSER_EMULATION registry keys. However that only allows us to change the rendering mode of all the CHtml...
In the end I have solved this by using our own proxy server (implemented using boost asio), and modifying the http request/response headers to force IE into the correct compatibility mode. several executables with unique names, with the compatibility mode set in the registry. Each browser version ran in a separate proc...
4,656,608
4,656,745
Performance question: Inverting an array of pointers in-place vs array of values
The background for asking this question is that I am solving a linearized equation system (Ax=b), where A is a matrix (typically of dimension less than 100x100) and x and b are vectors. I am using a direct method, meaning that I first invert A, then find the solution by x=A^(-1)b. This step is repated in an iterative p...
Test, test, test. Especially in the field of Numerical Linear Algebra. There are many effects in play, which is why there is a number of optimized libraries that have solved that burden for you. Some effects to consider: Memory locality and cache effects Multithreading effects (some algorithms that are optimal while r...
4,656,848
4,657,739
How to add to Qt books example something like add item to list possibility?
So there is a great example that comes with Qt. it is in Examples Books Demonstration. I am new to c++ and even more new to Qt so I wonder what shall be done to add such functionality? I mean what code changes shall be made to it to add 2 buttons like new and submit and what functions they shall trigger?
You definitely need to read a Qt tutorial (and maybe a C++ tutorial depending on your knowledge of C++). Have a look at this SO question : https://stackoverflow.com/questions/475345/ Doing the tutorial, you'll learn how to add buttons to a form and how a function will be triggered when a button is clicked. I also recom...
4,656,969
4,657,319
Find a substring in a String returns -1 although substring is available
I have again a strage C++ thing on the following: l is an incomming line (string.c_str()) > becomes line pos is the position from where to start searching s is a string (string.c_str()) to look for > becomes command It all works fine until command is "-1". In this case the string "-1" is not found although line is con...
This should help you find the problem: bool Converter::commandAvailable(const char* l, int pos, const char* s) { string line = l; string command = s; std::cout << "INPUT" << std::endl; std::cout << "LINE: " << line << std::endl; std::cout << "CMD: " << command << std::endl; std::cout << "STA...
4,657,099
4,657,266
Unexpected results when looking at ASCII codes in C++
The bit of code below is extracting ASCII codes from characters. When I convert characters in the normal ASCII region I get the value I expect. When I convert £ and € from the extened region I get a load of 1's padding the INT that I'm storing the character in. e.g. the output of the below is: 45 (ascii E as expecte...
First, there's no € in ASCII (extended or otherwise) because the euro didn't exist when ASCII was created. However, several ASCII-friendly 8-bit encodings do support the € character, but the conversion is done by your source code editor (the compiler merely sees a byte which happens to represent € in your editor, but m...
4,657,141
4,804,703
Strategies for handling cross-platform user authentication and authorization
I'm interested in what strategies can be used for handling user authentication and authorization in a cross-platform distributed system. I would like to be able to mark actions in the system as belonging to a certain user and also to only allow certain users to do certain actions. Background: The system is currently us...
You chould use claims based authentication with SAML tokens, which work cross platform. On the windows side there is a library for this: Windows Identity Foundation. See: http://msdn.microsoft.com/en-us/security/aa570351
4,657,152
4,657,278
how can i perform discrete integration of gyroscope data?
gyroscopes which measure rate of rotation of angles when integrated produce angles right? my question is how do i do this? what im doing so far is just adding all the angles ive detected and that seems to be very wrong AngleIntegrated = GyroDegPersec * (1/GyroBandWidth); suggestions are very welcome. thanks
Knowing that of course you can't count on having a correct value in the long run (by integration your error window will always increase over time) what I would do is reading the gyroscope, interpolating the current read and previous few ones to get a smooth curve (e.g. a parabola using current read and previous two) an...
4,657,188
5,253,321
Visual Studio not able to show the value of 'this' in release mode (with debug information)
Original question: Why is the this pointer 0 in a VS c++ release build? When breaking in a Visual Studio 2008 SP1 release build with the /Zi (Compiler: Debug Information Format - Program Database) and /DEBUG (Linker: Generate Debug Info, yes) options, why are 'this'-pointers always 0x00000000? EDIT: Rephrased question:...
As some others have mentioned, compiling in Release mode makes certain optimizations (especially eliminating the use of ebp/rbp as a frame pointer) that break assumptions on which the debugger relies for figuring out your local variables. However, knowing why it happens isn't very helpful for debugging your program! He...
4,657,423
4,657,558
Eclipse plugin developement : Schematic Editor
I need to develop an Eclipse plug-in as a schematic editor in Eclipse. So some questions concerning this. Is it possible to draw geometrical objects (rectangle/line/triangle/etc) using Eclipse native API ? If not please suggest alternative methods of doing it. Are there C++ APIs for doing this, preferably native Eclip...
No, unless you consider adding the plugin GEF as native Eclipse. "The Graphical Editing Framework (GEF) provides technology to create rich graphical editors and views for the Eclipse Workbench UI." Eclipse being developed mainly in Java, I doubt there is C++ APIs for this.
4,657,468
4,657,849
Fast fixed point pow, log, exp and sqrt
I've got a fixed point class (10.22) and I have a need of a pow, a sqrt, an exp and a log function. Alas I have no idea where to even start on this. Can anyone provide me with some links to useful articles or, better yet, provide me with some code? I'm assuming that once I have an exp function then it becomes relative...
A very simple solution is to use a decent table-driven approximation. You don't actually need a lot of data if you reduce your inputs correctly. exp(a)==exp(a/2)*exp(a/2), which means you really only need to calculate exp(x) for 1 < x < 2. Over that range, a runga-kutta approximation would give reasonable results with ...
4,657,513
4,664,519
comparing iterators from different containers
Is it legal to compare iterators from different containers? std::vector<int> foo; std::vector<int> bar; Does the expression foo.begin() == bar.begin() yield false or undefined behavior? (I am writing a custom iterator and stumbled upon this question while implementing operator==.)
If you consider the C++11 standard (n3337): § 24.2.1 — [iterator.requirements.general#6] An iterator j is called reachable from an iterator i if and only if there is a finite sequence of applications of the expression ++i that makes i == j. If j is reachable from i, they refer to elements of the same sequence. § 24....
4,657,592
4,657,638
Looking for a portable SOAP Client C++ Library
I'am going to have to interact with a SOAP web service, using a C++ application. I am looking for a library that could help me do that, knowing that there's a few requirement I need to full fill: It needs to be portable (Windows/Linux) It needs to be free and open source (but I don't need to sell/distribute my code) I...
the library that comes to mind to handle SOAP in C++ is gsoap I think it matches your requirements. If I remember correctly some of their tools are not open-sourced if you use them to produce non open-source code. Check the license ... Great toolkit. Worked very well for me some times ago ... my2c EDIT: As said in comm...
4,657,618
4,657,647
Do you consider multiple initialization steps "poor form"?
I'm writing a physics simulation (Ising model) in C++ that operates on square lattices. The heart of my program is my Ising class with a constructor that calls for the row and column dimensions of the lattice. I have two other methods to set other parameters of the system (temperature & initial state) that must get cal...
It is recommended to put all mandatory parameters in the constructor whenever possible (there are exceptions of course, but these should be rare - I have seen one real-world example so far). This way you make your class both easier and safer to use. Note also that by simplifying your constructor you make the client cod...
4,657,655
4,657,669
Should downcasting be avoided while using a class hierarchy in C++?
Let's say I'm writing an application which works with projects, and exposes different functionality depending on the type of the project. I have a hierarchy of classes for the different types of projects: class AbstractProject { }; class ProjectA : public AbstractProject { }; class ProjectB : public AbstractProject {...
Better way is to define pure virtual methods in base class and later implement all specific functionality in overloads in derived classes. Then call that method.
4,657,976
4,658,065
checking if pointer points within an array
Can I check whether or not a given pointer points to an object within an array, specified by its bounds? template <typename T> bool points_within_array(T* p, T* begin, T* end) { return begin <= p && p < end; } Or do the pointer comparisons invoke undefined behavior if p points outside the bounds of the array? In t...
Although the comparison is valid only for pointers within the array and "one past the end", it is valid to use a set or map with a pointer as the key, which uses std::less<T*> There was a big discussion on this way back in 1996 on comp.std.c++
4,658,121
4,780,565
How to include ODBC ver 3.0 libraries in my MFC app in Visual C++ 2010?
I created my own ODBC wrapper class which handles SQL from C++ Win32 application. I have copied and Added (as existing) this class to my MFC application. Now I have terrible linking problems with unresolved external symbols (which were NOT present in the Win32 perfectly working app), such as this: " Error 56 error ...
Solved. Solution: I created a DLL from my ODBC class and then used it in my project. Now it is compiled independently so it does not restrict each other's INCOMPATIBLE environment and compiler settings anymore!
4,658,378
4,658,624
What's the difference between inline member function and normal member function?
Is there any difference between inline member function (function body inline) and other normal member function (function body in a separate .cpp file)? for example, class A { void member(){} }; and // Header file (.hpp) class B { void member(); }; // Implementation file (.cpp) void B::member(){}
There is absolutely no difference. The only difference between the two is that the member inside the class is implicitly tagged as inline. But this has no real meaning. See: inline and good practices The documentation says that the inline tag is a hint to the compiler (by the developer) that a method should be inlined....
4,658,527
4,658,672
error: expected unqualified-id before string constant
After some research, i still don't understand the problem. Const.hpp : #ifndef CONST_HPP #define CONST_HPP #include <QString> const QString CONFFILENAME("dsibubble.ini"), STRSEP(" | "); const int MAXIMGWIDTH = 960; #endif // CONST_HPP TabDataBase.cpp : #include "Const.hpp" f...
I think you have defined STRSEP as a string literal somewhere like: #define STRSEP "blahblah" Because I compiled your snippet and it's fine, but adding a define like the previous one I get the same error.
4,658,692
4,658,921
How to use file bandwidth reservation (scheduled file IO) in Windows
I need to implement an application that streams data from disk. It is important that the data throughput is fairly constant and is not interupted by any other activity on the disk. From Windows Vista onwards, the GetFileBandwidthReservation() and SetFileBandwidthReservation() functions have been introduced specifically...
This requires support from the disk device driver. The kind of driver that you'd find in an upscale server, not a consumer level machine. Ask more questions about this at serverfault.com
4,658,764
5,363,858
OpenCV unable to capture image from isight webcam
I can not capture image from my webcam using following OpenCV code. The code can show images from a local AVI file or a video device. It works fine on a "test.avi" file. When I make use my default webcam(CvCapture* capture =cvCreateCameraCapture(0)), the program can detected the size of the image from webcam,but just u...
Latest update! Problem solved! This happen to be one of OpenCV 2.2′s bug Here is how to fix it: http://dusijun.wordpress.com/2011/01/11/opencv-unable-to-capture-image-from-isight-webcam/
4,659,062
4,664,570
A Dialog derived from CDialog returns -1 after DoModal (MFC/C++)
I have created a Dialog which it's derived from CDialog (MFC does this automatically), but I had to override the OnInitDialog method to make initialization of a ComboBox: BOOL CLogin::OnInitDialog() { CDialog::OnInitDialog(); InitCommonControls(); if ( FillInCombo() != 0 ) //erro ao tentar ler leitoras return ...
I suspect some thing goes wrong in your OnInitDialog(). I suggest you to go for debug steps: a) remove InitCommonControls() in OnInitDialog() b) remove FillInCombo() in OnInitDialog() c) remove InitCommonControls() and FillInCombo() in OnInitDialog() After removing one by one, check with the DoModal returns value.
4,659,105
4,659,161
How enable dragging a file on the *.exe and get it as parameter?
What do I have to do to make my program use a file that has been dragged and dropped onto its icon as a parameter? My current main method looks like this: int main(int argc, char* argv[]) { if (argc != 2) { cout << "ERROR: Wrong amount of arguments!" << endl; cout << "\n" << "Programm closed...\n\n"...
Your program does not need to do anything special apart from handling command-line arguments. When you drag-drop a file onto an application in Explorer it does nothing more than to pass the file name as argument to the program. Likewise for multiple files. If all you expect is a list of file names, then just iterate ov...
4,659,113
4,659,349
Why does cout return smanip?
Could anyone explain me the declaration of the setw manipulator? I was completely blown off trying to understand it.! The declaration of the setw in iomanip is as follows smanip setw(int) now what is smanip? what happens when we give std::cout << setw(10) << "Hai" [ i want to know how the output is actually affected ...
smanip is an implementation-defined type. The library can define or typedef it to anything it likes, as long as the job gets done. In practice, it will be some kind of structure representing (a) the manipulation to be performed, and (b) the argument 10 to be used in this manipulation. It might also have a function to p...
4,659,157
4,659,232
Using templates with anonymous classes scoped inside a function
Let's say I have the following snippet: template <class T> void f(T arg) { arg(); } void g() { struct { void operator()(void) { } } foo; f(foo); } Visual C++ accepts this. However, when I try GCC, I get: $ g++ --version # just in case this matters g++ (Debian 4.4.5-8) 4.4.5 ... $ g++ foo.cc foo.cc: In functio...
14.3.1 paragraph 2: A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a templateargument for a template typeparameter. In other words, not valid. Although it would be handy imo, that's maybe why VC allows it.
4,659,162
4,659,274
Int Argument in operator++
class myClass { public: void operator++() { // ++myInstance. } void operator++(int) { // myInstance++. } } Besides letting the compiler distinguish between myInstance++ and ++myInstance, is the optional int argument in operator++ actually for anything? If so, what is it?
As @Konrad said, the int argument is not used for anything, other than to distingush between the pre-increment and post-increment forms. Note however that your operators should return a value. Pre-increment should return a reference, and post-increment should return by-value. To wit: class myClass { public: myClass...
4,659,226
4,659,322
Struct Cannot take Constructor When using with __declspec(dllexport)
I try to define a constructor for C++ struct, and coincidently, this is also a struct I want to export. So here's my code: extern "C"__declspec(dllexport) typedef struct { double x; double y; PointCg(double xx, double yy); }PointCg; However, I got a compilation error saying that error C4430: missing type...
typedefs are just aliases to the base type. This implies that typedefs are a compile time, not a link time construct. In your sample code you are attempting to dllexport a typedef, of an anonymous struct - which is going to confuse the compiler on two levels: first, you're exporting an alias, which it doesn't want to d...
4,659,240
4,659,737
File management in C++
I have a requirement for reading, updating and deleting a file. I want to write a class for this. For example class FileManagement { private: fstream myFile; public: void read(); void update(); void delete(); }; My question is while updating is it possible to delete only one line in a file in C++ an...
You appear to be asking two different questions at once, in a confusing way. To delete a file, use the remove function, found in stdio.h. To erase one line of a file, you have to read the entire file and write it back out with the line removed. There is no library routine for this. The standard "safe" technique is t...
4,659,294
4,659,486
Linking against older version of runtime with newer version of MSVC?
I own VS 2008 Pro, and would like to do compatibility testing with VS 2005's runtime MSVCRT80, but I do not want to buy it just for that. Is there a way to link against MSVCRT80 without getting VS 2005? Thanks
Official support for native multi-targeting didn't appear until Visual Studio 2010, which allows you to select either v100 or v90 as your "Platform Toolset". There is no such feature in Visual Studio 2008. There is a discussion here on how one can achieve the same effect in Visual Studio 2008, but it appears you need t...
4,659,364
4,663,780
Writing Socket Servers in PHP is it good idea?
Is it good idea to write Socket Servers using php?? here is how to article: http://devzone.zend.com/article/1086 question: What is different from writing socket servers in other languages like c, c++, python, ..? how about security? speed? "Socket Servers normally run continuously as a service or a daemon." php runni...
It is not generally a good idea to write a (nontrivial) PHP program which executes for a long time. This is because its memory management is deficient in various ways, in particular, it fails to ever deallocate circularly referenced structures. Some other objects also leak. For example http://uk.php.net/manual/en/funct...
4,659,571
4,659,989
volatile unsigned __int64 with Visual Studio 2005 behaves strangely
I have a server, which uses a global variable to store the next available unique ID. Originally, this was defined as unsigned long g_nextUniqueId volatile; I'm changing all IDs to be 64-bit integers, so this line was changed to unsigned __int64 g_nextUniqueId volatile; There are only two pieces of code that directly ac...
Sounds like you need to do a full recompile. This is often the case when you make a change to a type used in multiple translation units. Sometimes the dependency checker gets confused.
4,659,774
4,659,796
Fastest C++ Container: Unique Values
I am writing an email application that interfaces with a MySQL database. I have two tables that are sourcing my data, one of which contains unsubscriptions, the other of which is a standard user table. As of now, I'm creating a vector of pointers to email objects, and storing all of the unsubscribed emails in it, initi...
If your C++ Standard Library implementation supports it, consider using a std::unordered_set or a std::hash_set. You can also use std::set, though its overhead might be higher (it depends on the cost of generating a hash for the object versus the cost of comparing two of the objects several times). If you do use a nod...
4,659,939
4,660,115
statvfs issue - printf / debugger
Im trying to use statvfs to find free space on a file system. Here's the code: const char* Connection::getDiskInfo() { struct statvfs vfs; int nRet = statvfs( "/u0", &vfs ); if( nRet ) return NULL; char* pOut = (char*)malloc( 256 ); memset( pOut, 0, 256 ); sprintf( pOut, "<disk letter='%s' total='%lu' free='%lu' tota...
What is the size of fsblkcnt_t? If it's 32-bit then it's an overflow problem and you simply need to temporarily use a 64-bit size during the calculation.
4,659,944
4,660,019
setbase(8) and std::cout<<std::oct
Whats the difference between std::cout<<std::setbase(8)<<32; and std::cout<<std::oct<<32; Are they equivalent? And also, what is the purpose of std::cout.oct??
std::oct Sets the basefield format flag for the str stream to oct. std::setbase Sets the basefield format flag to one of its possible values: hex, dec or oct depending on the value of the base parameter. I think the big difference is that setbase takes an argument so you could pass it a variable containing the numer...
4,660,123
4,661,372
overloading friend operator<< for template class
I have read couple of the questions regarding my problem on StackOverflow.com now, and none of it seems to solve my problem. Or I maybe have done it wrong... The overloaded << works if I make it into an inline function. But how do I make it work in my case? warning: friend declaration std::ostream& operator<<(std::ost...
This is one of those frequently asked questions that have different approaches that are similar but not really the same. The three approaches differ in who you are declaring to be a friend of your function --and then on how you implement it. The extrovert Declare all instantiations of the template as friends. This is w...
4,660,528
4,660,722
How do I add some external executable to a Borland C++ Builder 2010 project?
So the question is how to add to c++ builder 2010 some external .exe file? Let's say that i made some program in visual basic and have the exe file, so that does not need to make the same code in c++ i want to just include that exe in my project? Is it possible to make portable application one exe that have inside him ...
I don't understand exactly what you're trying to accomplish. If you want to use the functionality of a given program, you're going to have to know things about how that program works. If you want to take a given executable, and call it as you would a shell script, then you would need to start the given program with it...
4,660,651
4,660,810
Managing changes in memory-based data format
So I've been using a compact data type in c++, and saving from memory or loading from the file involves just copying the bits of memory in and out. However, the obvious drawback of this is that if you need to add/remove elements on the data, it becomes kind of messy. There's also problems with versioning, suppose you d...
I don't know what your 'technical reasons' are, but if they involve speed or data size then I might suggest Protocol Buffers as your solution. It's explicitly designed to handle versioning. It will be slightly slower and slightly larger than simply dumping a struct, but only slightly, and it will be much more portabl...
4,660,820
4,660,866
With GCC, can I disable -Wframe-larger-than on a per-function basis?
Using GCC, is it possible to specify a set of functions that are exempt from -Wframe-larger-than? (For example, main.)
GCC supplies you with pragmas for this purpose: http://gcc.gnu.org/onlinedocs/gcc-4.5.2/gcc/Diagnostic-Pragmas.html#Diagnostic-Pragmas Currently it won't do exactly what you want, since it seems to do it on a file by file basis, but in the next version of gcc (4.6), it appears as though it is context aware: http://gcc....
4,661,326
4,661,396
What is the advantage of c++ in writing device drivers?
As I know in order to write device drivers people usually use c++ or assembly? The choice of assembly is clear for me. But why c++? I guess it is possible to do in java (for example), or in other high level language as well. So why c++ is so common? Is there a specific feature of C++ programming language that is necess...
I would say that C is much more commonly used as a language for device drivers (over C++). There are a couple of reasons for this: Most of the major operating systems are written in a combination of C and assembler and provide C language interfaces to the operating system. Writing a device driver usually involves comm...
4,661,561
4,661,578
C++: What GNU G++ parameters?
Possible Duplicate: Best compiler warning level for C/C++ compilers? GCC has thousands of options to add more warnings; I was hoping that -Wall -Wextra -pedantic included all the useful ones, but just now I met -Woverloaded-virtual which seems really nice to me. What other G++ parameters do you use or would you reco...
Not quite the same category but I always compile with -Werror to flag warnings as errors. Very useful. To make this work with 3rd party headers, I include those headers via -isystem instead of -I … otherwise warnings in those headers will break the build. There’s also -Weffc++ which warns for specific issues outlined i...
4,661,571
4,662,013
Is there an elegant way to activate a tab in which a focused widget is located?
I have a QLineEdit inside a widget inside a QTabWidget. Let's say that tab is at tab index 2. When currently active tab is at index 1, and I call setFocus() (and show(), and raise()) on the QLineEdit, the active tab doesn't switch to index 2 to show the focused widget. Is there any elegant way to show the focused widg...
Here's a more generic function to switch to the tab containing a widget: void SwitchToTabContaining(QTabWidget * tabsW, QWidget * w) { for(int i=0;i<tabsW->count();++i) { QWidget * tab = tabsW->widget(i); if(tab->isAncestorOf(w)) { tabsW->setCurrentWidget(tab); break; ...
4,661,708
4,661,831
On different ways of filling a vector
I can think of three ways of filling a std::vector Suppose we have vector<int> v(100, 0); Then I want it to hold (1, 1, 1). We can do: v.clear(); v.resize(3, 1); Or v = vector<int>(3, 1); And I learned another approach: vector<int>(3, 1).swap(v); First question is: Is any of them the best approach? Second question...
So, here's the differences and I'll let you decide what is best for your situation. v.clear(); v.resize(3, 1); In this case we have marked the vector as cleared. It still holds whatever it allocated in order to hold 100 elements (which can be more than the space necessary for 100 elements). Then we added 3 items wit...
4,661,875
4,661,946
Is a C++ is_lambda trait, purely implemented as a library, impossible?
I have a question regarding C++0x lambdas. In my code, it would be beneficial to know whether or not a given type is the type of a C++0x lambda expression. To give an example: struct foobar { void operator()() { } }; auto lambda = []{}; typedef is_lambda < decltype(lambda) > ::type T; // T would be a true_type t...
Since evaluation of lambda results in creating closure object, there isn't any difference as soon as the object passed to a function or copied. And, frankly, I can't imagine a problem that would require to know whether an object came from lambda. Edit. A standard even has a note in 5.1.2/2: Note: a closure object beh...
4,661,883
4,661,911
Qt/C++ Error handling
I've been doing a lot of research about handling errors with Qt/C++ and I'm still as lost as when I started. Maybe I'm looking for an easy way out (like other languages provide). One, in particular, provides for an unhandled exception which I use religiously. When the program encounters a problem, it throws the unhandl...
Override QCoreApplication::notify() and add try-catch there. That, and something in main() covers most cases in my experience. Here's sort-of how I do it. Note that I'm using C++ RTTI here, not Qt's version, but that's just for convenience in our apps. Also, we put up a QMessageBox with the info and a link to our log-f...
4,661,903
4,667,341
PCA in OpenCV using the new C++ interface
As an aside: Apologies if I'm flooding SO with OpenCV questions :p I'm currently trying to port over my old C code to use the new C++ interface and I've got to the point where I'm rebuilidng my Eigenfaces face recogniser class. Mat img = imread("1.jpg"); Mat img2 = imread("2.jpg"); FaceDetector* detect = new HaarDet...
Your error is probably here: Mat data; data.create(2,1, img2_roi.type()); data.row(0) = img_roi; data.row(1) = img2_roi; PCA expects a matrix with the data vectors as rows. However, you never scale the images to the same size so that they have the same number of pixels (so the dimension is the same), also data.create(...
4,662,026
4,662,923
Releasing C++ resources and fork-exec?
I'm trying to spawn a new process from my C++-project using fork-exec. I'm using fork-exec in order to create a bi-directional pipe to the child process. But I'm afraid my resources in the forked process won't get freed properly, since the exec-call will completely take over my process and is not going to call any dest...
There are excellent odds that you don't need to call any destructors in between fork and exec. Yeah, fork makes a copy of your entire process state, including objects that have destructors, and exec obliterates all that state. But does it actually matter? Can an observer from outside your program -- another, unrelat...
4,662,112
4,662,165
Are there any c++ metaprogramming alternatives besides templates?
I have been using metaprogramming quite a lot, but sometimes the combination of c macros and templates are just not enough. I suppose the drawback would potentially be lack of cross-platform compatibility if the metaprogramming platform is only for, say, linux etc. So yeah, is there such thing available right now, besi...
You can also metaprogram with the preprocessor. You could consider using special purpose preprocessors to generate code as "metaprogramming" as well. Then you could include things like lex/yacc and the Qt MOC.
4,662,366
4,662,694
What /else/ causes this?
MFC Toolbox Library.lib(SimpleFileIO.obj) : error LNK2005: _wcsnlen already defined in libcmtd.lib(wcslen_s.obj) fatal error LNK1169: one or more multiply defined symbols found This is driving me nuts. Normally, one would get this if the various projects that are a part of their solution do not agree on which CRT to ...
Sorry to waste everyone's time. Your answers were all the sorts of things I'd been looking at, though I haven't really used the /verbose option and would consider it in the future. However, this one boils down to the fact that the CRT that is supplied with VS 2010 defines the function wcsnlen() whereas the CRT in 2008...
4,662,946
4,663,349
How do I remove border around a custom CProgressCtrl?
I have created a custom progress control, derived from CProgressCtrl, to display the progress using a bitmap by overwriting the OnPaint function (CProgressCtrl::OnPaint is not called). When viewed in the application, there is a border around the progress bar. WS_BORDER is not set for the progress control, nor any other...
The progress control is a single window - this can easily be verified with Spy++. I think you need to override OnNcPaint as well as OnPaint.