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
2,102,921
2,102,950
Strange behaviour of ldr [pc, #value]
I was debugging some c++ code (WinCE 6 on ARM platform), and i find some behavior strange: 4277220C mov r3, #0x93, 30 42772210 str r3, [sp] 42772214 ldr r3, [pc, #0x69C] 42772218 ldr r2, [pc, #0x694] 4277221C mov r1, #0 42772220 ldr ...
This is correct. When pc is used for reading there is an 8-byte offset in ARM mode and 4-byte offset in Thumb mode. From the ARM-ARM: When an instruction reads the PC, the value read depends on which instruction set it comes from: For an ARM instruction, the value read is the address of the instruction plus 8 bytes. ...
2,102,942
2,103,188
lua_pop vs lua_remove
Currently I'm building my own script VM manager class in C++. I have no problems with any of the Lua & Lua C or C++ stuff, but the one section that confuses me is when to use lua_pop and when to use lua_remove. From what I understand, lua_pop is to remove multiple values(on the stack) from the top down, eliminating dat...
A typical example of lua_remove is accessing tables. Snippets from Lua reference manual. lua_getfield(L, LUA_GLOBALSINDEX, "t"); /* table to be indexed */ lua_getfield(L, -1, "x"); /* push result of t.x (2nd arg) */ lua_remove(L, -2); /* remove 't' from the stack */ lua_getfield pushes t[x] o...
2,103,349
2,103,377
Next value in std::map
I have an std::map<std::string, float> so I can do quick lookups for float values based on names, but I have a situation now where I need to find the next float value in the list as if it were sorted numerically. I cannot just use an iterator, as far as I know, since the map is key sorted. So if my set contains: std:...
You probably want to use a Boost::bimap instead of a normal map -- it provides this capability quite directly.
2,103,411
2,103,424
Is creating an empty class purely to distinguish it from another class good practice?
I have a class CardStack. I have several classes that inherit from CardStack e.g. Cascade, Deck, Foundation etc. Foundation doesn't need to add any functionality to CardStack, but for display purposes my app needs to know which of the CardStacks are actually Foundations. Incidentally, I have no such function CardStack....
Nothing wrong with this. Do it all the time. In the future, there may be a difference in structure, behavior or implementation. For now, they happen to share a lot of common features.
2,103,484
2,103,870
c++ container for checking whether ordered data is in a collection
I have data that is a set of ordered ints [0] = 12345 [1] = 12346 [2] = 12454 etc. I need to check whether a value is in the collection in C++, what container will have the lowest complexity upon retrieval? In this case, the data does not grow after initiailization. In C# I would use a dictionary, in c++, I could eithe...
Just to detail a bit over what have already been said. Sorted Containers The immutability is extremely important here: std::map and std::set are usually implemented in terms of binary trees (red-black trees for my few versions of the STL) because of the requirements on insertion, retrieval and deletion operation (and n...
2,103,728
2,103,850
Selecting An Embedded Language
I'm making an application that analyses one or more series of data using several different algorithms (agents). I came to the idea that each of these agents could be implemented as separate Python scripts which I run using either the Python C API or Boost.Python in my app. I'm a little worried about runtime overhead TB...
Yes, tons. Lua and Python seems to be the most popular: Embedding Lua http://www.lua.org/pil/24.html https://stackoverflow.com/questions/38338/why-is-lua-considered-a-game-language Lua as a general-purpose scripting language? Embedding Python http://docs.python.org/extending/embedding.html Embedding Tcl http://wik...
2,103,833
2,105,527
how to set base index in ublas matrix?
I have searched the web but could not find an answer. how do I have set base index in the matrix, such that indexes start from values other than zero? for example: A(-3:1) // Matlab/fortran equivalent A.reindex(-3); // boost multi-array equivalent thanks
Your search appears to be correct; it appears not to have such a function.
2,103,873
2,103,912
C++: casting to void* and back
* ---Edit - now the whole sourse* When I debug it on the end, "get" and "value" have different values! Probably, I convert to void* and back to User the wrong way? #include <db_cxx.h> #include <stdio.h> struct User{ User(){} int name; int town; User(int a){}; inline int get_index(int a){ return town; } //for anoth...
Unless User is a POD this is undefined in C++. Edit: Looking at db_cxx.h, aren't you supposed to do call get_doff(), get_dlen(), and get_data() or something on Dbt instead of just casting (and assigning) it to the user type?
2,104,208
2,104,243
Is it possible to use boost::foreach with std::map?
I find boost::foreach very useful as it saves me a lot of writing. For example, let's say I want to print all the elements in a list: std::list<int> numbers = { 1, 2, 3, 4 }; for (std::list<int>::iterator i = numbers.begin(); i != numbers.end(); ++i) cout << *i << " "; boost::foreach makes the code above much simpl...
You need to use: typedef std::map<int, int> map_type; map_type map = /* ... */; BOOST_FOREACH(const map_type::value_type& myPair, map) { // ... } The reason being that the macro expects two parameters. When you try to inline the pair definition, you introduce a second comma, making the macro three parameters inst...
2,104,459
2,104,619
Is it possible to replace the global "operator new()" everywhere?
I would like to replace the global operator new() and operator delete() (along with all of their variants) in order to do some memory management tricks. I would like all code in my application to use the custom operators (including code in my own DLLs as well as third-party DLLs). I have read things to the effect tha...
The C++ standard explicitly allows you to write your own global operator new and delete (and array variants). The linker has to make it work, though exactly how is up to the implementors (e.g., things like weak externals can be helpful for supplying something if and only if one isn't already present). As far as DLLs go...
2,104,471
2,104,479
C++ Class using header and implemenation files
I've put together a simple C++ "Hello World" program to practice; unfortunately, upon compilation I get a few errors: expected ')' before fName error: prototype for 'HelloWorld::HelloWorld(std::string, std::string)' does not match any in class 'HelloWorld' Below is my code, can anyone help me understand what I'm miss...
You need to change your header file to reference std::string instead of string because they are defined inside the std namespace. HelloWorld(std::string fName, std::string lName); It works in your .cpp file because you specifically import this namespace. The solution however is not to import this namespace in your he...
2,104,523
2,105,513
c++ rapidxml node_iterator example?
I just started using rapidXML since it was recommended to me. Right now to iterate over multiple siblings i do this: //get the first texture node xml_node<>* texNode = rootNode->first_node("Texture"); if(texNode != 0){ string test = texNode->first_attribute("path")->value(); cout << test << endl; } //get al...
The documentation that I could find documents no node_iterator type. I can't even find the word iterator on that page except in reference to output iterators, which you clearly don't want. It could be that it's an internal API, or one under development, so you're probably best not to use it right now.
2,104,598
2,104,702
_CrtMem* and the debug heap
When I use the following code, it detects a memory leak. How can I make it not? _CrtMemState startState; _CrtMemState endState; _CrtMemState temp; _CrtMemCheckpoint(&startState); const char* foo = "I'm not leaking memory! Stop saying I am!"; _CrtMemCheckpoint(&endState); _CrtMemDifference(&temp, &startState, &endStat...
I cut and pasted your code and tested it on my machine under VS2008 and _CrtMemDifference returns 0 ... As the oft heard adage goes: "Works on my machine" ;) Edit: Have you got multiple threads running? Is it possible another thread has allocated something between the 2 _CrtMemCheckpoint calls?
2,104,978
2,105,302
Why might trigger a breakpoint when I return TRUE from my OnCopyData?
I'm using Visual Studio to debug an ATL application. When I step over return TRUE in this code, the error occurs: BOOL CMainFrame::OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct) { // Code snipped from here - maybe this causes stack/heap corruption? // I have a breakpoint here, if I step over (F10), A...
Microsoft's Application Verifier may help with this. If the application has heap corruption, this utility can cause the exception to occur when the error occurs. It can use a lot of memory when running, though, since it can produce big changes in memory allocation schemes. The following obviously flawed code gives a s...
2,105,077
2,105,116
Initializing static struct tm in a class
I would like to use the tm struct as a static variable in a class. Spent a whole day reading and trying but it still can't work :( Would appreciate if someone could point out what I was doing wrong In my class, under Public, i have declared it as: static struct tm *dataTime; In the main.cpp, I have tried to define and...
You can wrap the above in a function: tm initTm() { time_t rawTime; ::time(&rawTime); return *::localtime(&rawTime); } tm Indice::dataTime = initTm(); To avoid possible linking problems, make the function static or put it in an unnamed namespace.
2,105,272
2,105,293
Extract Digits From An Integer Without sprintf() Or Modulo
The requirements of this are somewhat restrictive because of the machinery this will eventually be implemented on (a GPU). I have an unsigned integer, and I am trying to extract each individual digit. If I were doing this in C++ on normal hardware & performance weren't a major issue, I might do it like this: (Don't hat...
Remember that the modulo operator can actually be implemented as: mod(a, n) = a - n * floor(a / n) Hence, you can use your favorite modulo based algorithm. You can simulate floor itself by typecasting.
2,105,411
2,105,482
Windows: How do I calculate the time it takes a c/c++ application to run?
I am doing a performance comparison test. I want to record the run time for my c++ test application and compare it under different circumstances. The two cases to be compare are: 1) a file system driver is installed and active and 2) also when that same file system driver is not installed and active. A series of tests ...
You can put this #if _DEBUG time_t start = time(NULL); #endif and finish with this #if _DEBUG time end = time(NULL); #endif in your int main() method. Naturally you'll have to return the difference either to a log or cout it.
2,105,612
2,105,677
How to code Const and Mutable overloads?
I seem to have this pattern occuring pretty often in my code, with two functions performing the same task apart from the constness of their parameters/returns. int& myClass::getData() { return data; } // called for const objects const int& myData::getData() const { return data; } This offends my sens...
Use the following trick (which I originally got from Scott Meyers' book Effective C++): int& myClass::getData() { // This is safe because we know from out here // that the return value isn't really const return const_cast<int&>(const_cast<const myClass&>(*this).getData()); } const int& myData::getData() co...
2,105,716
2,105,796
Header Guards and LNK4006
I have a character array defined in a header //header.h const char* temp[] = {"JeffSter"}; The header if #defined guarded and has a #pragma once at the top. If this header is included in multiple places, I get an LNK4006 - char const * * temp already defined in blahblah.obj. So, I have a couple of questions about this...
Why does this happen if I have the guards in place? I thought that they prevented the header from being read in after the first access. Include guards make sure that a header is included only once in one file (translation unit). For multiple files including the header, you want the header to be included in each file...
2,105,816
2,105,874
Trying to use/include/compile 3rd party library, libmagic. C/C++ filetype detection
After looking for a way to detect the filetype of a file stream, I found that the Unix file command uses libmagic and I'm trying to make use of the library myself, but I can't get it to work. I've rarely integrated 3rd party code in my own, so that's probably a big part of my problem as well. Why: I'm doing this becaus...
__FILE__ is a reserved pre-processing symbol macro used for debugging/logging purposes. Consider this as an example: // This file is called test.c char *p = NULL; if (!(p = malloc((1 * sizeof(char) + 1)))){ printf("Error in file: %s @ line %d\n\tMalloc failed\n", __FILE__, __LINE__); exit(-1); } If the call to ...
2,105,901
2,105,906
How to fix 'expected primary-expression before' error in C++ template code?
Here's yet another VC9 vs. GCC 4.2 compile error problem. The following code compiles fine with VC9 (Microsoft Visual C++ 2008 SP1) but not with GCC 4.2 on Mac: struct C { template< typename T > static bool big() { return sizeof( T ) > 8; } }; template< typename X > struct UseBig { static bool test() ...
That should be return X::template big< char >(); Dependent names from templates are taken to not be types unless you specify that they are via typename and assumed to not be templates unless specified via template.
2,106,073
2,107,577
How would one setup autotools to build a project for separate architectures, concurrently, on multiple systems?
I've got a C++ project which uses automake and autoconf. I'm new to both of these. My home directory is network mounted -- the same on every server we have -- and I want to compile and run the project (and its executable) concurrently on separate machines. Our servers are frequently different architectures. My desktop ...
If you don't do anything "wrong" or unusual in your configure.ac and Makefile.am setup, this is supported automatically: mkdir /some/where/build cd /some/where/build /else/where/source/configure --options... make make install Basically, you create the build directory anywhere you want (in your case probably on a non-n...
2,106,200
2,106,683
Starting wxWidgets C++ need a gentle nudge
So I've been learning C# for like a year now (I'm 20 years old) and I'm getting pretty confident with it. I've also been meddling with C++ every now and again. For example just recently I've been following the Nehe OpenGL tutorials for C++ and I find it a fun way of learning. I want to start looking at creating cross p...
My suggestion is to learn how to do GUI layout with wxWidgets in code, then when you get good at it learn how to use the GUI tools. Doing this kind of work manually for a while gives you the understanding about what you need ("Ok, I need a wxSizer, vertical, to put these two horizontal wxSizers into, where I put my a w...
2,106,218
2,106,229
quickly invalidate cache
Is there a way in c++ to quickly invalidate the L2 cache of a processor other than iterating through a large fake array?
I'm going to assume this is for performance testing and you want to eliminate cache effects between runs. In that case, what you'd need to know to do this efficiently is: The allocation size of the L2 cache How many allocations there are in the L2 cache Then it's basically a matter of touching memory allocation_size ...
2,106,386
2,106,412
When are C++ destructors explicitly called?
What are the instances where you need to explicitly call a destructor?
When you use placement-new is a common reason (the only reason?): struct foo {}; void* memoryLocation = ::operator new(sizeof(foo)); foo* f = new (memoryLocation) foo(); // note: not safe, doesn't handle exceptions // ... f->~foo(); ::operator delete(memoryLocation); This is mostly present in allocators (used by co...
2,106,389
2,106,426
Basic Game DrawEngine question
i want to create a basic game Draw engine class for my 2D game. i'm not quite sure whether to share main window handle with class or keep it private as it is in the main class. The other way i'm thinking to do is pass the device context itself to draw engine class. which would be the standard way to work with draw engi...
I would say pass the Device Context in as you can always call GetDC(hWnd) in order to obtain the device context, however, the benefits of having the hWnd are that you can get the Client Size etc.. so, in that regard, the hWnd would be the best (perhaps save the hWnd in the class). In terms of speed, you probably want t...
2,106,496
2,106,513
Problems initializing glut
I have simplified my problem to this example: #include <GL/glut.h> int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize (600, 600); glutInitWindowPosition( 0, 0 ); int win = glutCreateWindow("Recon"); return 0;...
Do you have a display function? I'm not sure if this will help, but maybe putting in a display function in which you clear the buffers might help? e.g. glutDisplayFunc(myDisplay); void myDisplay() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the screen glutSwapBuffers(); } What compiler ...
2,106,576
2,106,590
C++ Disabling warnings on a specific include
I'm wondering if there's a way to disable all warnings on a specific file (for example, using a preprocessor directive). I'm using CImg.h and I want to get rid of the warnings involving that code. I'm compiling both with VS (the version for Windows) and gcc (the Linux one), so I would like to have a generic way... Than...
You can do it using #pragma in Microsoft compiler: http://msdn.microsoft.com/en-us/library/2c8f766e%28VS.80%29.aspx Something like this: #pragma warning (push, 0) //....header file #pragma warning (pop) Can't help you with gcc compiler, some info here: Selectively disable GCC warnings for only part of a translation ...
2,106,657
2,106,736
Getting Original Regular Expression Out From sregex (Boost Xpressive)
I have the following code. sregex rex = sregex::compile( "(\\w+) (\\w+)!" ); How I can get "(\w+) (\w+)!" out from rex?
Looking at the documentation for basic_regex<> (sregex is just a typedef for basic_regex), I don't see any function that looks like it can retrieve the original textual representation of the regular expression. If you really need that, you are going to have to create your own class that holds both a sregex and a std::s...
2,106,707
2,106,760
Mutual exclusion (in static library )
I have a static library to access a Database. It has a function readMaximum(). readMaximum() reads a maximum value from DB. This function is thread safe (using mutex). But problem is : There are two processes A.exe and B.exe; both are compiled with the static library. Is there any way where I can implement mutual excl...
Use CreateMutex() to created a named global mutex. Prefix the name with "Global\".
2,106,786
2,107,180
Variable Arguement With Class Reference As 1st Parameter
I have the following code : #include <cstdarg> #include <iostream> using namespace std; class a { }; void fun1(a& aa, ...) { va_list argp; va_start(argp, aa); char *p = 0; while ((p = va_arg(argp, char *)) != 0) { cout << p << endl; } va_end(argp); } void fun2(char *aa, ...) { va...
You can't use a reference parameter as the last named parameter with va_start. The reason is because va_start takes the address of the named parameter to find the location of the rest of the arguments. However, taking the address of a reference gives the address of the variable pointed at by the reference, not the ad...
2,106,796
2,106,822
C++ Version For Java String.replaceAll
Java String.replaceAll comes very handy. Has anyone encounter similar library in C++ (Even without regular expression match, but with exact match is OK)
C++ has no built in lib to do that, but Boost has string replace functions: http://www.boost.org/doc/libs/1_41_0/doc/html/string_algo/usage.html#id1701549 Also without STL here is an example: http://www.linuxquestions.org/questions/programming-9/replace-a-substring-with-another-string-in-c-170076/
2,106,834
2,107,128
C++ expression evaluation order
i ran into a curious problem regarding evaluation of expressions: reference operator()(size_type i, size_type j) { return by_index(i, j, index)(i, j); // return matrix index reference with changed i, j } matrix& by_index(size_type &i, size_type &j, index_vector &index) { size_type a = position(i, index); // find p...
In my opinion, this boils down to order of evaluation. The standard says - (5.4) Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified. Which fits the bill exactly. The values of i an...
2,106,899
2,106,919
Is the following C++ code equiv? (in a smart pointer implementation)
Code 1: template<class T> const PtrInterface<T>* PtrInterface<T>::newRef() const { PtrInterface<T>* me = (PtrInterface<T>*) this; ++me->references_; //++this->references_; return this; } Code 2: template<class T> const PtrInterface<T>* PtrInterface<T>::newRef() const { //PtrInterface<T>* me = (PtrInterface<...
Is there ever any situation where these two blocks of code will do different things? Yes, when you are in a const method. Currently, the one with me invokes undefined behavior. Here's why: As you know, when you call a member function, there is an implicit this pointer. The this pointer is const when a function is mar...
2,106,927
2,106,950
ROUNDUP? what does it do? in C++
Can someone explain to me what this does? #define ROUNDUP(n,width) (((n) + (width) - 1) & ~unsigned((width) - 1))
Providing width is an even power of 2 (so 2,4,8,16,32 etc), it will return a number equal to or greater than n, which is a multiple of width, and which is the smallest value meeting that criteria. So width = 16; 5->16, 7->16, 15->16, 16->16, 17->32, 18->32 etc. EDIT I started out on providing an explanation of why thi...
2,107,011
2,107,018
useful open source libraries/projects on Windows
Which open-source projects do you feel C/C++ Windows developers should be aware of? Boost Libraries: generic library (smart pointers, command line parsing, threads, formatting, etc) Postgresql: full-feature SQL database. MediaInfo: provides information about audio/video files.
I would say GTK+ Qt. SQLite is awesome. libxml. Mono Monodevelop Eclipse IDE Apache HTTP Server and APR, and all Apache top-levels GLib OpenGL Actually, just install Linux or another Free UNIX
2,107,122
2,118,787
cant get ifstream to work in XCode
No matter what I try, I cant get the following code to work correctly. ifstream inFile; inFile.open("sampleplanet"); cout << (inFile.good()); //prints a 1 int levelLW = 0; int numLevels = 0; inFile >> levelLW >> numLevels; cout << (inFile.good()); //prints a 0 at the first cout << (inFile.good());, it prints a 1 and a...
It turned out to be an issue with X-Code. I created a project in net beans using the same exact code and had no problems. Weird. Update: In my X-Code project, I changed my active SDK from Mac OS 10.6 to Mac OS 10.5 and everything works fine now.
2,107,260
2,107,462
How to make a Web Browser toolbar?
How do I make a Web Browser toolbar in C++. in dev-C++ for I.E with no addon libraries?
Since you use Dev C++ I am assuming you want to make IE Addons? If thats the case, this should get you started: Creating Add-ons for Internet Explorer: Toolbars on msdn.microsoft.com And you should also take a loot at the Guidelines for add-on developers over at IE Blog.
2,107,275
2,113,312
Does anyone have a FileSystemWatcher-like class in C++/WinAPI?
I need a .Net's FileSystemWatcher analog in raw C++/WinAPI. I almost started to code one myself using FindFirstChangeNotification/FindNextChangeNotification, but then it occurred to me that I am probably not the first one who needs this and maybe someone will be willing to share. Ideally what I need is a class which ca...
What about the ReadDirectoryChangesW function? http://msdn.microsoft.com/en-us/library/aa365465(VS.85).aspx It stores notifications in a buffer so you don't miss any changes (unless the buffer overflows)
2,107,601
2,111,344
Fastest cross-platform A* implementation?
With so many implementations available, what is the fastest executing (least CPU intensive, smallest binary), cross-platform (Linux, Mac, Windows, iPhone) A* implementation for C++ using a small grid? Implementations Google returns: http://www.heyes-jones.com/astar.html (Most links on that site are dead.) http://www.g...
Look at other path-finding algorithms (like Breath-First, Depth-First, Minimax, Negmax etc.) and weigh the positives and negatives for your scenario. Boost also has an A-star implementation. Try following these instructions to build boost on iPhone, but it might not work for you: it is not a "full port" of boost and it...
2,107,608
2,107,677
Using generic methods?
What are the benefits and disadvantages of using generic methods (in compile time, run time, performance, and memory)?
Okay, Java generics and C++ templates are so different that I'm not sure it's possible to answer them in a single question. Java Generics These are there pretty much for syntactic sugar. They are implemented through a controversial decision called type erasure. All they really do is prevent you from having to cast a ...
2,107,688
2,107,833
How to store a sequence of timestamped data?
I have an application that need to store a sequence of voltage data, each entry is something like a pair {time, voltage} the time is not necessarily continuous, if the voltage doesn't move, I will not have any reading. The problem is that i also need to have a function that lookup timestamp, like, getVoltageOfTimestamp...
You could use a binary search on your std::deque because the timestamps are in ascending order. If you want to optimize for speed, you could also use a std::map<Timestamp, Voltage>. For finding an element, you can use upper_bound on the map and return the element before the one found by upper_bound. This approach uses...
2,107,699
2,107,983
Credential manager for Vista/Windows 7
I have Credential manager implemented in VC++ which captures credentials during login process. It works well in XP/Vista/Windows 7 32 bit env. But is not working in 64 bit. Any idea ? Thanks in advance for any help
If you want your DLL to be loaded by a 64-bit process, your DLL has to be compiled for 64 bits. If you want your DLL to be loaded by a 32-bit process, your DLL has to be compiled for 32 bits. This is true on both 64-bit Windows systems and 32-bit Windows systems. John gave you a useful link, even though John's wording...
2,107,831
2,113,962
Problem using MIDI streams in Windows
I'm writing a Windows program using C++ and the Windows API, and, am trying to queue MIDI messages in a MIDI stream, but am receiving a strange error when I try to do so. If I use midiOutShortMsg to send a non-queued MIDI message to the stream, it works correctly. However, midiStreamOut always returns error code 68, wh...
The problem was that I was using the entire event structure as the buffer for the MIDI stream. It turns out that the fourth member of the structure, dwParms, should actually be omitted from short messages. To correct the code in the posted question, two of the lines of code could be changed to the following: header.dwB...
2,107,944
2,108,043
How to implement an associative array/map/hash table data structure (in general and in C++)
Well I'm making a small phone book application and I've decided that using maps would be the best data structure to use but I don't know where to start. (Gotta implement the data structure from scratch - school work)
Tries are quite efficient for implementing maps where the keys are short strings. The wikipedia article explains it pretty well. To deal with duplicates, just make each node of the tree store a linked list of duplicate matches Here's a basic structure for a trie struct Trie { struct Trie* letter; struct List *mat...
2,108,000
2,110,489
Debugging asserts in Qt Creator
When I hit a normal assert statement while debugging with Visual Studio I get the option to break into the debugger so I can see the entire stack trace and the local variables, not just the assert message. Is it possible to do this with Qt Creator+mingw32 and Q_ASSERT/Q_ASSERT_X?
You can install a handler for the messages/warnings that Qt emits, and do your own processing of them. See the documentation for qInstallMsgHandler and the example they give there. It should be easy to insert a break in a custom message handler (or indeed, just assert on your own at that point). The one small drawba...
2,108,084
2,108,109
Pass by reference more expensive than pass by value
Is there a case where pass-by-reference is more expensive than pass-by-value in C++? If so, what would that case be?
Prefer passing primitive types (int, char, float, ...) and POD structs that are cheap to copy (Point, complex) by value. This will be more efficient than the indirection required when passing by reference. See Boost's Call Traits. The template class call_traits<T> encapsulates the "best" method to pass a parameter of ...
2,108,099
2,108,245
Modifying old Windows program for Mac OS X
This application was written for windows back in 1998, I loved using this program, Now I want to learn how to make it work on Mac, And maybe changing and adding functionality, The problem is I don't know where to start, I Have studied C++ php, javascript, But don't really know how to read this code. or where to st...
Based on the screenshots and info on the TextCalc site, I think this is best implemented as a Mac OS X service. You can assign a hot key to trigger your service in the System Preferences -> Keyboard -> Services. It would actually be rather easy. You don't need to write the text editor portion, it will be available ...
2,108,172
2,108,209
C++ Namespaces, comparison to Java packages
I've done a bunch of Java coding recently and have got used to very specific package naming systems, with deep nesting e.g. com.company.project.db. This works fine in Java, AS3/Flex and C#. I've seen the same paradigm applied in C++ too, but I've also heard that it's bad to view C++ namespaces as direct counterparts to...
In C++ namespaces are just about partitioning the available names. Java packages are about modules. The naming hierarchy is just one aspect of it. There's nothing wrong, per-se, with deeply nested namespaces in C++, except that they're not normally necessary as there's no module system behind them, and the extra layers...
2,108,355
2,108,398
Difficult concurrent design
I have a class called Root which serves as some kind of phonebook for dynamic method calls: it holds a dictionary of url keys pointing to objects. When a command wants to execute a given method it calls a Root instance with an url and some parameter: root_->call("/some/url", ...); Actually, the call method in Root loo...
To avoid the deletion of 'target', I had to write a thread safe reference counted smart pointer. It is not that hard to do. The only thing you need to ensure is that the reference count is accessed within a critical section. See this post for more information.
2,108,389
2,108,460
C++ classes , Object oriented programming
I have a very simple class named person which is given below , I have a problem with only two functions , i.e setstring () function and setname() function , I am calling setstring() function from the setname function. The only problem is when in the main function I write Object.setname(“Zia”); The result is ok as sh...
The specific reason that nothing is being printed is that in setstring, p is copy of the name pointer, not a reference to it. Try changing the signature of setstring to: void setstring(const char* s, char*& p); (note the &). See the other answers for other significant errors in the code - unless these problems are fix...
2,108,467
2,108,502
Is Short Circuit Evaluation guaranteed In C++ as it is in Java?
In Java, I use if (a != null && a.fun()); by taking full advantage of short-circuit evaluation and expression are evaluated from left to right? In C++, can I do the same? Are they guarantee to portable across different platform and compiler? if (a != 0 && a->fun());
Yes, it is guaranteed for the "built in" types. However, if you overload && or || for your own types, short-circuited evaluation is NOT performed. For this reason, overloading these operators is considered to be a bad thing.
2,108,538
2,108,625
how to use my_alloc for _all_ new calls in C++?
Imagine I'm in C-land, and I have void* my_alloc(size_t size); void* my_free(void*); then I can go through my code and replace all calls to malloc/free with my_alloc/my_free. How, I know that given a class Foo, I can do placement new; I can also overload the new operator. However, is there a way to do this for all m...
In global scope, void* operator new(size_t s) { return my_alloc(s); } void operator delete(void* p) { my_free(p); } void* operator new[](size_t s) { return my_alloc(s); } void operator delete[](void* p) { my_free(p); }
2,108,668
2,108,682
basic question c++, dynamic memory allocation
Suppose I have a class class person { char* name; public: void setname(const char*); }; void person::setname(const char* p) { name=new char[strlen(p)]; strcpy(name,p); name[strlen(p)]='\0'; } My question is about the line name=new char[strlen(p)]; suppose the p pointer is pointing to string i.e “zia” , now strlen(p)...
You say: we have an array of 4 characters i.e char[3] Surprisingly enough, char[3] is an array of THREE characters, not FOUR!
2,108,899
2,109,083
Xcode cannot find #Include<> header
I'm trying to get Xcode to import the header file for Irrlicht. #include <irrlicht.h> It says "Irrlicht.h. No such file or directory". Yes Irrlicht.h with a capital I, even though the #include is lowercase. Anyway I added "/lib/irrlicht-1.6/include" in the header search paths for the Xcode project, yet it still doesn'...
I figured this out. Perhaps someone can comment as to why this is the case. The Header was located in this directory: /lib/irrlicht-1.6/include/ If I added that path to: "Header Search Paths" Xcode still wouldn't find the path when I built the project. Solution: Add the header path to: "User Header Search Paths" inste...
2,109,191
2,109,323
Ambiguous overload accessing argument-less template functions with variadic parameters
Yeah, the title can scare babies, but it's actually quite straightforward. I am trying to store a function pointer to a specialized template function, namely boost::make_shared (boost 1.41), as illustrated: boost::shared_ptr<int> (*pt2Function)() = boost::make_shared<int>; However, it won't compile (GCC 4.4.1) due to ...
Variadic template arguments mean you take 0..n template arguments, thus both your versions are matches. You could resolve the ambiguity by adding another template parameter to the second version, so that it takes 1..n arguments. Something like this should work: template< class T, class Arg1, class... Args > boost::sha...
2,109,283
2,109,313
How to detect if an application is running under KVM?
I already know how to detect VMWare and VirtualPC, but I want to know how to do this in Kernel Virtual Machine. I would like the code to be in C or C++.
This page implies that it's enough to check the kernel's boot messages, if Linux is your hosted OS: # dmesg | grep -i virtual CPU: AMD QEMU Virtual CPU version 0.9.1 stepping 03 That should be easy enough to implement in C.
2,109,450
2,109,473
I'm developing GUI apps on Mac. I have been using C++ for 10+ years. Do I need to switch to Objective C?
I've been coding on C++/Linux for 10+ years. I am switching to do Mac development. My development involves GUI components. Is my only choice to learn Cocoa/Objective-C, or is there a way to wrap Cocoa and use it from C++ land? Thanks!
Yes, you need to learn Objective-C. Besides, you wouldn't gain much if you didn't need to. It's not the language that's hard to learn but the Cocoa framework (not because it's inherently hard but because it's so huge).
2,109,483
2,109,516
Boost threads coring on startup
I have a program that brings up and tears down multiple threads throughout its life. Everything works great for awhile, but eventually, I get the following core dump stack trace. #0 0x009887a2 in _dl_sysinfo_int80 () from /lib/ld-linux.so.2 #1 0x007617a5 in raise () from /lib/tls/libc.so.6 #2 0x00763209 in abort ()...
start_thread is throwing an uncaught exception, see which exceptions can start_thread throw and place a catch around it to see what is the problem.
2,109,643
2,109,659
C++, GTK+, and String types
Excuse my ignorance here but I know neither C++ nor GTK+. Which String type is used when setting Strings in GTK+ widgets? In .NET, Strings passed to a control are obviously .NET System.String. In Cocoa, Strings passed to a control are NSString. But I understand C++ does not have a standardized String type (but indeed s...
All text in GTK+ is UTF-8-encoded, using char *, of course const where possible. Remember that GTK+ is implemented in C, so there is no use of STL for instance. The underlying glib's character-set conversion documentation begins by stating: Glib uses UTF-8 for its strings, and GUI toolkits like GTK+ that use Glib ...
2,109,648
2,109,675
What's the lifetime of memory pointed to typeinfo::name()?
In C++ I can use typeid operator to retrieve the name of any polymorphic class: const char* name = typeid( CMyClass ).name(); How long will the string pointed to by the returned const char* pointer available to my program?
As long as the class with rtti exists. So if you deal with single executable - forever. But for classes in a Dynamic Link Librariy it shifts a little. Potentially you can unload it.
2,109,767
3,468,766
MSXML's loadXML fails to load even well formed xml
I have written a wrapper on top of MSXML in c++ . The load method looks like as below. The problem with the code is it fails to load well formed xml sometimes. Before passing the xml as string I do a string search for xmlns and replace all occurrence of xmlns with xmlns:dns. In the code below I remove bom character. T...
For this specific issue, please refer to Strings Passed to loadXML must be UTF-16 Encoded BSTRs. Overall, xml parser is not designed for in memory string parsing, e.g. loadXML does not recognize BOM, and it has restriction on the encoding. Rather, an xml parser is designed for byte array form with encoding detection, w...
2,109,784
2,109,921
What am I missing in my compilation / linking stage of this C++ FreeType GLFW application?
g++ -framework OpenGL GLFT_Font.cpp test.cpp -o test -Wall -pedantic -lglfw -lfreetype - pthread `freetype-config --cflags` Undefined symbols: "_GetEventKind", referenced from: __glfwKeyEventHandler in libglfw.a(macosx_window.o) __glfwMouseEventHandler in libglfw.a(macosx_window.o) __glfwWindowE...
I tink those come from the Carbon framework. LIBS += -framework Carbon should do it then.
2,110,151
2,110,171
Using Templated Classes and Functions in a Shared Object/DLL
I am working on a fairly significantly-sized project which spans many shared libraries. We also have significant reliance on the STL, Boost and our own template classes and functions. Many exported classes contain template members and exported functions contain template parameters. Here is a stripped-down example of ...
As you may know, the templates in your export file are in fact a 'permission to fill in whatever you think necessary' for the compiler. That means that if you compile your header file with compiler A, it may instantiate a completely different deque<int> than compiler B. The order of some members may change, for one, o...
2,110,212
2,110,443
How to create good debugging problems for a contest?
I am involved in a contest, and in one event we have debugging questions. I have to design some really good debugging problems in C and C++. How can I create some good problems on debugging? What aspects should I consider while designing the problems?
My brainstorming session: Memory leaks of the subtle sort are always nice to have. Mess around with classes, constructors, copy-constructors and destructors, and you should be able to create a difficult-to-spot problem with ease. One-off errors for array loops are also a classic. Then you can simply mess with the minds...
2,110,215
2,110,281
Adding a field to a structure without breaking existing code
So I'm working with this huge repository of code and have realized that one of the structs lack an important field. I looked at the code (which uses the struct) as closely as I could and concluded that adding an extra field isn't going to break it. Any ideas on where I could've screwed up? Also: design advice is welcom...
From what you've written above I can't see anything wrong. Two things I can think of: Whenever you change code and recompile you introduce the ability to find "hidden" bugs. That is, uninitialized pointers which your new data structure could be just big enough to be corrupted. Are you making sure you initialize c be...
2,110,302
2,110,340
C++ will this function leak?
I have started out to write a simple console Yahtzee game for practice. I just have a question regarding whether or not this function will leak memory. The roll function is called every time the dices need to be re-rolled. What it does is to create a dynamic array. First time it is used it will store 5 random values. F...
Yes, it can leak. Just for example, using cout can throw an exception, and if it does, your delete will never be called. Instead of allocating a dynamic array yourself, you might want to consider returning an std::vector. Better still, turn your function into a proper algorithm, that takes an iterator (in this case, a ...
2,110,632
2,118,916
how to represent int * as array in totalview?
How do I 'dive' an int * which points to a dynamically allocated array of integers and represent it as a fixed int[] array? Put otherwise, if I dive an int * it shows the address and the int pointed to, but instead I would like to see the array of all of the integers.
I noticed the TotalView tag on this question. Are you asking how to see the values in your array in totalview? If so then the answer is pretty easy. Lets say you have a pointer p which is of type int * and you have it currently pointing towards an array with 10 integers. Step 1. Dive on the pointer. That's accomplish...
2,110,900
2,110,952
Reassignment of a reference
Suppose I have a class class Foo { public: ~Foo() { delete &_bar; } void SetBar(const Bar& bar) { _bar = bar; } const Bar& GetBar() { return _bar; } private: Bar& _bar; } And my usage of this class is as follows (assume Bar has a working copy constructor) Foo f; f.SetBar(*(new Bar)); ...
References cannot be "reseated", setBar() just copies the contents of bar to the object referenced by _bar. If you need such a functionality use pointers instead. Also your usage example would be much simpler if you were just using pointers.
2,111,297
2,111,364
Using relative filepaths on a portable C++ application
I am developing a portable C++ application. Development environment is Linux. I have a code that loads data from Xml file and create a object model out of it. Currently path to file is provided as /home/myuser/projectdir/xmlfilename.xml. This is problematic when I use from a different computer where the home directory ...
You need to locate the user's home directory. To do this, Use getpwent to get the user record and from there the home directory. Then add the rest of the path to your xml file /myuserprojectdir/xmlfilename.xml to the value you get. This will work even if the users's home directory is not /home/$USER. It works on lin...
2,111,314
2,111,346
What is std::vector::front() used for?
Sorry if this has been asked before, but I am wondering what the use of std::vector::front() is. Is there a reason to use e.g. myvector.front() rather than myvector[0] or myvector.at(0)?
Some of the generic algorithms that also work on lists use it. This is an example of a general principle: if you provide accessors for all the semantics you support, not just the implementation you support, it is easier to write generically and therefore easier to reuse code.
2,111,474
2,111,708
Reading from a file in C++
I'm trying to write a recursive function that does some formatting within a file I open for a class assignment. This is what I've written so far: const char * const FILENAME = "test.rtf"; void OpenFile(const char *fileName, ifstream &inFile) { inFile.open(FILENAME, ios_base::in); if (!inFile.is_open()) { ...
void Reverse(ifstream &inFile) { char myInput; while ( inFile.get( myInput ) ) { // do something with myInput } }
2,111,480
2,111,495
How do I know if HWND is desktop itself?
I use GetForegroundWindow to get the foreground window handle but if there is no window, then it returns the HWND to the desktop. How do I know if the HWND is the desktop?
Compare it with the result of calling GetDesktopWindow().
2,111,550
2,111,589
Is there a way, using templates, to prevent a class from being derivable in C++
I need to prevent a class from being derived from so I thought to myself, this is something that Boost is bound to have already done. I know they have a noncopyable, they must have a nonderivable... Imagine my surprise when I couldn't find it.... That got me thinking.. There must be a reason. Maybe it isn't possible to...
Under the current spec, it is explicitly forbidden to "friend" a template argument, so templatizing your example would make it not standards compliant. Boost probably would not want to add something like that to its libraries. I believe this restriction is being relaxed in Ox however, and there are workarounds for comp...
2,111,593
2,111,672
When is it good to use c++ iostreams over ReadFile, WriteFile, fprintf, etc ...?
I find that it is tremendously easier to use streams in c++ instead of windows functions like ReadFile, WriteFile, etc or even fprintf. When is it not good to use streams? When is it good to use streams? Is it safe to use streams? How come a lot of programmers don't use streams? This is just something I've always wonde...
When is it not good to use streams? Streams are not guaranteed to be thread safe. It's easy to dream up a situation where you can not use streams without some synchronization. Stream objects are typically pretty "heavy". They may be too heavy for low memory or embedded environments. When is it good to use stream...
2,111,667
9,842,857
Compile time string hashing
I have read in few different places that using C++11's new string literals it might be possible to compute a string's hash at compile time. However, no one seems to be ready to come out and say that it will be possible or how it would be done. Is this possible? What would the operator look like? I'm particularly in...
This is a little bit late, but I succeeded in implementing a compile-time CRC32 function with the use of constexpr. The problem with it is that at the time of writing, it only works with GCC and not MSVC nor Intel compiler. Here is the code snippet: // CRC32 Table (zlib polynomial) static constexpr uint32_t crc_table[2...
2,112,188
2,112,264
What are all of the well-known virtual folder GUIDs?
There seem to be a few virtual folders which have GUIDs associated to them (control panel, desktop) - ::{00021400-0000-0000-c000-000000000046} // desktop Where the blazes are these defined? When are they used? What I want is a way to have a string which represents a virtual folder without any ambiguity. If, for inst...
If i understand you correctly you are looking for the CSIDLs (pre-Vista, include Shlobj.h) or KNOWNFOLDERID (>= Vista, Knownfolders.h).
2,112,247
2,113,954
How to better organize the code in C++ projects
I'm currently in the process of trying to organize my code in better way. To do that I used namespaces, grouping classes by components, each having a defined role and a few interfaces (actually Abstract classes). I found it to be pretty good, especially when I had to rewrite an entire component and I did with almost no...
Especially I'd like to do a better separation between interfaces, the public face of the components, and their implementations in behind. I think what you're looking for is the Facade pattern: A facade is an object that provides a simplified interface to a larger body of code, such as a class library. -- Wikip...
2,112,252
2,112,336
How do I check whether a file exists in C++ for a Windows program?
This is for a Windows-only program so portable code is not an issue. I need simply: bool DoesFileExist( LPWSTR lpszFilename ) { // ... }
There are two common ways to do this in Windows code. GetFileAttributes, and CreateFile, bool DoesFileExist(LPCWSTR pszFilename) { DWORD dwAttrib = GetFileAttributes(pszFilename); if ( ! (dwAttrib & FILE_ATTRIBUTE_DEVICE) && ! (dwAttrib & FILE_ATTRIBUTE_DIRECTORY)) { return true; } return ...
2,112,302
2,112,358
Enumerate COM object (IDispatch) methods using ATL?
Using ATL (VS2008) how can I enumerate the available methods available on a given IDispatch interface (IDispatch*)? I need to search for a method with a specific name and, once I have the DISPID, invoke the method (I know the parameters the method takes.) Ideally I would like to do this using smart COM pointers (CCom...
You can't enumerate all the available methods unless the object implements IDispatchEx. However, if you know the name of the method you want to call, you can use GetIDsOfNames to map the name to the proper DISPID. HRESULT hr; CComPtr<IDispatch> dispatch; DISPID dispid; WCHAR *member = "YOUR-FUNCTION-NAME-HERE"; DISPPAR...
2,112,318
2,112,356
C++: Will structure be copied properly?
I have a pointer to a structure and I need to implement a method that will copy all of the memory contents of a structure. Generally speaking I need to perform a deep copy of a structure. Here's the structure: typedef struct { Size2f spriteSize; Vertex2f *vertices; GLubyte *vertex_indices; } tSprite; An...
As a rule of thumb, don’t ever use memcpy in C++ in normal code (it might crop up in very low-level code, e.g. in allocators)1). Instead, create a suitable copy constructor and overload operator = (the assignment operator) to match it (and a destructor – rule of three: “if you implement either of copy constructor, oper...
2,112,759
2,113,036
C++ Inherited Virtual Method Still Uses Base Class Implementation
I have a base class called Packet: // Header File class Packet { public: virtual bool isAwesome() const { return false; } } and an inherited class called AwesomePacket: // Header File class AwesomePacket : public Packet { public: virtual bool isAwesome() const { return true; } } Howeve...
By any chance is your code calling isAwesome in the Packet constructor: Packet::Packet() { // this will always call Packet::isAwesome if (isAwesome()) { } } Even if this Packet constructor is being used to construct the parent object of an AwesomePacket object, this will not call AwesomePacket::isAwes...
2,113,043
2,113,092
Concatenating strings in C++
I am rather inexperienced C++ programmer, so this question is probably rather basic. I am trying to get the file name for my copula: string MonteCarloBasketDistribution::fileName(char c) { char result[100]; sprintf(result, "%c_%s(%s, %s).csv", copula.toString().c_str(), left.toString().c_str(), right.toString()...
sprintf has 4 place holders while you give only 3 parameters. I would suggest: string MonteCarloBasketDistribution::fileName(char c) { std::ostringstream result; result << c <<"_"<<copula<<'('<<left<<", "<<right<<").csv"; return result.str(); } Your sprintf is not safe for buffer overflow, use rather C99 snpr...
2,113,136
2,114,094
Trying to know why the OpenMP code does not parallelise
I just started learning how to use OpenMP. I am trying to figure out why the following code does not run in parallel with Visual Studio 2008. It compiles and runs fine. However it uses only one core on my quad core machine. This is part of the code that I am trying to port to a MATLAB mex function. Any pointer is appre...
The v variable is computed using the v value of the previous iteration for(t = 0; t<T; t++) { ... v += ... ( tv - v ) .... ... } You cannot do that, it breaks the parallelism. The loop must be able to be run in any sequence, or with differents parallel chunks at once, with no side effects. From a fi...
2,113,231
2,113,413
Making CMake choose static linkage when possible?
I'm working on a project that's link against SOCI, which comes as both static and dynamic libraries. I'd like CMake to choose the static version when available, and dynamic otherwise. Is there a reasonable way to do this in CMake? I've come up with nothing looking through the docs so far.
Sounds like you need to add CMAKE_EXE_LINKER_FLAGS=-static
2,113,634
2,113,891
Problem with BOOST_CHECK_CLOSE_FRACTION
I'm using the Boost::Test library, and I am trying to check if an actual percent value is close to the expected value: BOOST_CHECK_CLOSE_FRACTION( items[i].ExpectedPercent, items[i].ActualCount / totalCount, 0.05); For some reason this check fails even when the values are close enough: difference between i...
After some testing, it turns out that the documentation for BOOST_CHECK_CLOSE_FRACTION is incorrect. The tolerance should be specified as a fraction of the expected value. So, TFAE: BOOST_CHECK(abs(x - y) < (min(x, y) * 0.1)); BOOST_CHECK_CLOSE(x, y, 10); BOOST_CHECK_CLOSE_FRACTION(x, y, 0.1);
2,113,950
2,113,967
How to send keystrokes to a window?
im using keybd_event(); and i want use SendMessage(); to send keystroke to notepad, can this be done?
using SendMessage to insert text into the edit buffer (which it sounds like you want): HWND notepad = FindWindow(_T("Notepad"), NULL); HWND edit = FindWindowEx(notepad, NULL, _T("Edit"), NULL); SendMessage(edit, WM_SETTEXT, NULL, (LPARAM)_T("hello")); if you need keycodes and arbitrary keystrokes, you can use SendInpu...
2,114,106
2,114,143
I have a wxwidgets that I want to add some cool effects. Using GDI would be impossibly hard. Could I use flash or something else?
I have an application that I want add some cool animations to show state changes. However, wxwidgets would be difficult because I'd have to program these animations in straight gdi. What's the best way to add these effect windows? Should I open a flash window and run a flash sequence or is maybe some other technology? ...
You could prepare animation as a bunch of images (wxImage loaded from PNG, GIF, JPG or whatever files), and then use a timer and paint them on a control. Maybe it sounds like too much, you I believe you could do it in 50-70 lines of code.
2,114,127
2,114,216
Include paths not found while compiling with g++ on MacOS
I'm trying to compile the simplest program on MacOS 10.6 like: $ g++ -o hello hello.cpp the following source: #include <iostream> int main (int argc, char * const argv[]) { std::cout << "Hello, World!\n"; return 0; } I'm getting the error: hello.cpp:1:20: error: iostream: No such file or directory hello.cpp:...
On my Mac, that include file is in /usr/include/c++/4.0.0/iostream . Are you sure you have all the command-line development tools installed? They might not be by default; I'm pretty sure I had to install it manually when I first set up my Mac. There should be a "developer tools" package somewhere on your OS X installa...
2,114,358
2,114,379
Using STL Allocator with STL Vectors
Here's the basic problem. There's an API which I depend on, with a method using the following syntax: void foo_api (std::vector<type>& ref_to_my_populated_vector); The area of code in question is rather performance intensive, and I want to avoid using the heap to allocate memory. As a result, I created a custom allo...
You have to use the default allocator just as the function expects. You have two different types, and there's no way around that. Just call reserve prior to operating on the vector to get the memory allocations out of the way. Think about the bad things that could happen. That function may take your vector and start ad...
2,114,477
2,114,489
how do I print a binary double array from commandline (unix)
I got binary file, that contains doubles. How do i print that out to a terminal. I've tried octaldump 'od' but cant figure out the syntax I've tried something like head -c80 |od -f But that doesnt work, the man page for od is extremely bad. I've made a c program that does what I want, something like assuming 10double...
Have you tried hexdump utility? hexdump -e ' [iterations]/[byte_count] "[format string]" ' filename Where format string should be "%f", byte count should be 8, and iterations the amount of floats you want to read
2,114,694
2,114,713
HeapAlloc returns 0xC0000017: Not Enough Quota
I'm allocating a small number of data types, total size 2mb. I only use one heap, and it runs fine until I get to a certain number of allocations, I'm pretty sure of this because I've commented one allocation for it to crash on the next. Quota = disk space? the documentation doesn't cover error codes for this specific ...
Try allocating a large chunk of memory (i.e. >2MB) until you get the error to determine if the issue is the # of objects or total heap. Also, are you sure you aren't allocating more than 2mb memory? I've seen that error when the 2gb limit is hit, but never at 2mb unless your pagefile is full. If all else fails, reboo...
2,114,797
2,114,817
Compute Median of Values Stored In Vector - C++?
I'm a programming student, and for a project I'm working on, on of the things I have to do is compute the median value of a vector of int values. I'm to do this using only the sort function from the STL and vector member functions such as .begin(), .end(), and .size(). I'm also supposed to make sure I find the median w...
You are doing an extra division and overall making it a bit more complex than it needs to be. Also, there's no need to create a DIVISOR when 2 is actually more meaningful in context. double CalcMHWScore(vector<int> scores) { size_t size = scores.size(); if (size == 0) { return 0; // Undefined, really. } ...
2,114,941
2,115,068
Simple Qt Embedded Window Question
How are you meant to initialise the program using Qt embedded? At the moment I'm using QMainWindow but this means including a lot extra when configuring Qt and makes the applications a lot bigger when compiling them statically.What are you meant to use in place of QMainWindow? I don't need anything like maximise button...
A QWidget without a parent is a window. If you don't want the things provided by QMainWindow, you don't have to use it - you can use any QWidget subclass.
2,115,185
2,166,256
Prevent memory working set minimize in Console application?
I want to prevent memory working set minimize in Console application. In windows application, I can do by overriding SC_MINIMIZE messages. But, how can I intercept SC_MINIMIZE in console application? Or, can I prevent memory working set minimize by other ways? I use Visual Studio 2005 C++. Somebody has some problem, an...
Working set trimming can only be prevented by locking pages in memory, either by locking them explictly with VirtualLock or by mapping memory into AWE. But both operations are extreamly high priviledged and require the application to run under an account that is granted the 'Lock Pages in Memory' priviledge, see How t...
2,115,253
2,138,037
How to write a bison file to automatically use a token enumeration list define in a C header file?
I am trying to build a parser with Bison/Yacc to be able to parse a flow of token done by another module. The tokens are already listed in a enumeration type as follow: // C++ header file enum token_id { TokenType1 = 0x10000000, TokenType2 = 0x11000000, TokenType3 = 0x11100000, //... and...
Instead of doing : /* Bison/Yacc file */ %token TokenType1 0x10000000 %token TokenType2 0x11000000 %token TokenType3 0x11100000 //... You just need to include the file with the token type in the declaration part #include "mytoken_enum.h" // ... %token TokenType1 %token TokenType2 %token TokenType3 //... EDIT: This c...
2,115,575
2,115,597
Why POSIX is called "Portable Operating System Interface"?
I have searched hard but still confused why POSIX is called "Portable Operating System Interface", what I learned is that it is some threading library for Unix environment, because when you need to use it under windows you have to use cygwin or "Windows Services of Unix", etc. That's why I am confused why it is called ...
Before Posix, the Unix family tree was becoming very diverse and incompatible. A program written for one Unix was not compatible with a different Unix without significant porting effort. Posix was one of the attempts to present a common set of utilities and programming interfaces so that your software would be portab...
2,115,640
2,115,874
STL Multimap Remove/Erase Values
I have STL Multimap, I want to remove entries from the map which has specific value , I do not want to remove entire key, as that key may be mapping to other values which are required. any help please.
If I understand correctly these values can appear under any key. If that is the case you'll have to iterate over your multimap and erase specific values. typedef std::multimap<std::string, int> Multimap; Multimap data; for (Multimap::iterator iter = data.begin(); iter != data.end();) { // you have to do this becau...
2,115,816
2,117,525
OpenCV cvLoadImage() does not load images in visual studio debugger?
I am trying to work out a simple hello world for OpenCV but am running out of ideas as to why it is not working. When I compile and run this code: #include <cv.h> #include <highgui.h> int main(int argc, char* argv[]) { IplImage* img = cvLoadImage( "myjpeg.jpg" ); cvNamedWindow( "MyJPG", CV_WINDOW_AUTOSIZE ); cvShow...
It really seems like there's a problem with the path to myjpeg.jpg since the current directory could be different when you're running under the debugger. By default, the current directory that the Visual Studio debugger uses is the directory containing the .vcproj file, but you can change it in the project properties (...
2,115,931
2,126,566
Registering handlers for .NET COM event in C++
I've been following the 'tutorials' of how to expose a .NET framework through COM ( http://msdn.microsoft.com/en-us/library/zsfww439.aspx and http://msdn.microsoft.com/en-us/library/bd9cdfyx.aspx ). Everything works except for the events part. When I add events to the C# interface the following C++ code is generated: s...
It has been a long time since I used COM and at that time I was using Visual C++ 6.0. I remember that implementing sinks for COM connection points was not a straightforward process. There were multiple ways for implementing them, depending if you used MFC or ATL. Maybe there are easier ways now. Here are couple of link...