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
915,646
916,998
Blocking functions using OpenMP
I have a GUI application, which listens to a network port from a second thread. I was looking at OpenMP and I was wondering if there are easy ways to create threads like this. I was searching for documentation, but the OpenMP site is not very convenient to navigate. Could someone help?
As far as I understand OpenMP is a compiler-assisted parallelizing framework/library targeted to heavy computations. You hint the compiler which parts of your code (usually loops) can run in parallel. The compiler does its magic (inserting library calls, sharing/unsharing variables, etc.) and, poof, the program can now...
915,778
915,817
lightweight C++ scripting library
I currently use QtScript for scripting functionality in my C++ application, but it's rather "heavy" on the cpu. When a thread evaluates all the scripts in a loop the cpu usage increases to 90%-100%. Even when i put it to sleep for 1 msec every 5 scripts it stays above 75% cpu usage. Are there any other, easy to impleme...
Have a look at Lua, it's frequently used in games so the performance must be pretty good.
915,914
915,992
is ipv6 backward compatible with ipv4?
I've got a little udp example program written using ipv4. If I alter the code to ipv6 would I still be able to communicate with anyone using the listener with an ipv4 address? I was looking at porting examples at http://ou800doc.caldera.com/en/SDK_netapi/sockC.PortIPv4appIPv6.html I'm not sure if simply altering the c...
Yes and no... IPv6 does contain completely different addressing, so you'll have to recode your app to use the alternative headers and structure sizes. However, the IPv4 address range is available within IPv6, the syntax is to add two colons before the standard address (eg ::10.11.12.13). You can also embed IPv4 address...
916,282
917,710
Instrumentation (diagnostic) library for C++
I'm thinking about adding code to my application that would gather diagnostic information for later examination. Is there any C++ library created for such purpose? What I'm trying to do is similar to profiling, but it's not the same, because gathered data will be used more for debugging than profiling. EDIT: Platform: ...
You might also want to check out libcwd: Libcwd is a thread-safe, full-featured debugging support library for C++ developers. It includes ostream-based debug output with custom debug channels and devices, powerful memory allocation debugging support, as well as run-time support for printing source file:line number in...
916,455
917,079
C++ (Really) Safe Standard String Search?
Buffer overrun problems are well known. Thus we were blessed with standard library functions such as wcscat_s(). And the kind folks at Microsoft have created similar safe string functions such as as StringCbCat(). But I have a problem where I need to search a bit of memory for a string. The Standard library function: ...
Assuming that your pStr is null terminated and that uiSize is the number of wchar_t of readable memory at pMem: wchar_t* pSubStr = std::search( pMem, pMem + uiSize, pStr, pStr + std::wcslen( pStr ) ); // Optionally, change to the 'conventional' strstr return value if( pSubStr == pMem + uiSize) pSubStr = 0;
916,507
917,560
How to convert a user-defined unmanaged type to a managed type?
I have a test that I'm writing in MSTest, which is managed C++, and I'm trying to test an unmanaged class. Specifically, I'm trying to use the PrivateObject class to call a private method. This is the code that I have so far: CUnmanagedType foo; PrivateObject privateFoo = gcnew PrivateObject( foo ); CString strFromFoo...
The PrivateObject constructor wants a typename, not an instance. To do this, you would need to do the following: PrivateObject privateFoo = gcnew PrivateObject( "CUnmanagedType" )
916,546
916,628
Waiting on multiple events C++
Is there a recommended way to wait on multiple inputs. For example I would like my program to be able to receive input from 3 sources: Listen on a thread condition e.g. pthread_cond_wait() Take data from Standard input e.g. getline() Listen on a socket e.g. accept() What is the best way to accomplish this? Do I need a ...
You can listen on multiple file descriptors without using multiple threads using the select(2) system call. You can use pthread_cond_timedwait to wait on a condition variable with a timeout, such that you don't wait more than a particular amount of time. I think it's highly unusual to want to simultaneously wait on ei...
916,600
916,691
Can a C++ compiler re-order elements in a struct
Can a C++ compiler (specifically g++) re-order the internal elements of a struct? I'm seeing some strange behaviour where I have a structure that contains something like the following: Struct SomeStruct{ ... ... long someLong; long someLongArray[25]; unsigned long someUnsignedLong; unsigned long someU...
It normally can't reorder elements, no. An exception is if there's an access specifier separating them: struct Foo { A a; B b; C c; private: D d; E e; F f; }; a, b and c are guaranteed to be stored in this order, and d, e and f are guaranteed to be stored in order. But there is no guarantees about whe...
916,790
916,813
How do I convert a CString to a double in C++?
How do I convert a CString to a double in C++? Unicode support would be nice also. Thanks!
A CString can convert to an LPCTSTR, which is basically a const char* (const wchar_t* in Unicode builds). Knowing this, you can use atof(): CString thestring("13.37"); double d = atof(thestring). ...or for Unicode builds, _wtof(): CString thestring(L"13.37"); double d = _wtof(thestring). ...or to support both Unicode...
916,877
917,938
Map plugin for an MFC application
I want to display a map in a MFC application (Visual Studo 2008 with MFC Feature Pack). Off the top of my head I have the following requirements: I have to be able to add my own markers (plain lat/lon positions), preferrably with different colors/icons so one can distinguish between different types of markers. If the ...
I have written an open-source Geocaching app ( it's in c++ ) that renders maps, the source is at: http://code.google.com/p/gpsturbo/ It uses my own custom rendering but you could rip out the map parsing if you want. It renders map using google tiles ( and caches the tiles for offline use), as well as Garmin format GPS...
916,973
916,986
Recursive file search using C++ MFC?
What is the cleanest way to recursively search for files using C++ and MFC? EDIT: Do any of these solutions offer the ability to use multiple filters through one pass? I guess with CFileFind I could filter on *.* and then write custom code to further filter into different file types. Does anything offer built-in mult...
Using CFileFind. Take a look at this example from MSDN: void Recurse(LPCTSTR pstr) { CFileFind finder; // build a string with wildcards CString strWildcard(pstr); strWildcard += _T("\\*.*"); // start working for files BOOL bWorking = finder.FindFile(strWildcard); while (bWorking) { bWor...
917,120
917,184
combining similar functions into one common function involving passing function pointers as parameters
I am trying to combine the following two functions into one portable function: void NeedleUSsim::FindIdxRho() { searchTmp = &ninfo->rho; double *p = std::find_if(tplRho_deg, tplRho_deg+sampleDim[2], &NeedleUSsim::GreaterThanOrEqualTo); while(p != tplRho_deg+sampleDim[2]) { idxRho = p - tplRho_de...
The simplest way to make your code a bit more generic is the following : template<typename ComparisonType> double* NeedleUSsim::FindIdx(double* containerBegin, double* containerEnd, ComparisonType comparison) { double* p = std::find_if(containerBegin, containerEnd, comparison); double* idx = 0; while(p != c...
917,134
922,167
Delete a node from the middle of a C++ queue
I have a linked list with a c-style ctor and dtor. I just got too frustrated when this if statement decided not to test true, putting me in an infinite loop. I dont understand why it will never test true. I am trying to delete a node (the address of a class object) from my LinkedList. Maybe someone could help me out? N...
Keep your loops small, it easier to figure out what went wrong. Assuming your data compare makes sense, look at this the following: curr = first_; while( curr && (curr->data_ != node->data_) ) { curr = curr->next_; } if (!curr) return // didnt find it, nothing to remove if ( curr == first_ ) first_ = curr->n...
917,391
917,548
QPainter colored text (syntax coloring)
I have a custom Qt widget which I used to display disassembly and I am looking to add syntax coloring to it. Currently, I simply set the QPen to a solid color, construct the text I want to display, and render it to the QPainter at the appropriate coordinates. The question is, what is the best approach to adding syntax ...
Qt provides a QSyntaxHighlighter that is probably exactly what you want. QSyntaxHighlighter uses a QTextDocument to mark each block of code with a specific state which can be associated with a specific presentation format. The documentation on QSyntaxHighlighter provides a sample demonstrating how this may be accompli...
917,643
917,667
Using floats in Windows DLL function parameters
I am writing an unmanaged DLL in C++. Is using float as a function parameter in a Windows DLL a good idea? I'd like my DLL to be usable from as many languages as possible (VB6, .NET, etc). To this end, I've used STDCALL and avoided C++ types. Will most languages handle float correctly? If not, what should I use?
The float type used in most compilers is even standardized in some IEEE format, so go ahead.
917,963
922,267
IMovieControl::Run fails on Windows XP?
Actually, it only fails the second time it's called. I'm using a windowless control to play video content, where the video being played could change while the control is still on screen. Once the graph is built the first time, we switch media by stopping playback, replacing the SOURCE filter, and running the graph agai...
Never got a resolution on this. The production solution was to just call IGraphBuilder::Release and rebuild the entire graph from scratch. There's a CPU spike and a slight redraw delay when switching videos, but it's less pronounced than we'd feared.
918,236
918,288
Interesting Scope Problem, Explanation?
I just discovered a bug where the code looked something like this: char *foo = malloc(SOME_NUM * sizeof(char)); if (!processReturnsTrueOrFalse(foo)) { free(foo); char *foo = malloc(SOME_NUM * sizeof(char)); // More stuff, whatever } This compiles, but it's weird that I am allowed to define two variables wi...
C++ defines a new scope for variables every time you use { }. Take a look at this example here. const char *foo = "global"; int main(int argc, char* argv[]) { const char *foo = "hello"; { cout << foo << endl; const char *foo = "world"; cout << foo << endl; cout << ::foo << end...
918,405
918,564
QDBusAbstractAdaptor vs. QDBusAbstractInterface
When exposing some code to D-Bus using Qt D-Bus bindings, when should one use a Qt Adaptor over a Qt Interface? I'm having a difficult time understanding how exactly they differ since it seems like they provide the same functionality.
Per http://doc.trolltech.com/4.3/qdbusabstractinterface.html, "QDBusAbstractInterface class is the base class for all D-Bus interfaces in the QtDBus binding", while, per http://doc.trolltech.com/4.3/qdbusabstractadaptor.html, "QDBusAbstractAdaptor class is the starting point for all objects intending to provide interfa...
918,567
918,574
'size_t' vs 'container::size_type'
Is there is a difference between size_t and container::size_type? What I understand is size_t is more generic and can be used for any size_types. But is container::size_type optimized for specific kinds of containers?
The standard containers define size_type as a typedef to Allocator::size_type (Allocator is a template parameter), which for std::allocator<T>::size_type is typically defined to be size_t (or a compatible type). So for the standard case, they are the same. However, if you use a custom allocator a different underlying t...
918,668
920,128
How can I redefine a built in keyboard shortcut's behavior?
I am attempting to re-implement the Copy behavior for a QTextEdit object. The custom context menu I create works as expected when the 'Copy' button is clicked, but Ctrl + C isn't being handled correctly. Since the context menu doesn't have any issues, I'll omit that portion of the code. // Create a text edit box for te...
Copy is not virtual so this might be problematic. Copying is handled via the private text control API, and is not easily accessible. The best approach is probably to install an event handler for the text edit and intercept the copy key event before it's delivered to the text control processEvent handler - which should ...
918,702
918,712
Linkedlist Node in C+
I am learning a book on data structures, and complied their node in linked list example, and I receive this error: and Everything.cpp|7|error: expected unqualified-id before "int"| and Everything.cpp|7|error: expected `)' before "int"| ||=== Build finished: 2 errors, 0 warnings ===| The code for the node is: typedef...
The code sample is wrong. There should not be the keyword struct in front of the constructor declaration. It should be: typedef struct Node { Node(int data) // No 'struct' here { this-> data = data; previous = NULL; next = NULL; } int data; struct Node* previous; struc...
918,736
918,827
Random number generator that produces a power-law distribution?
I'm writing some tests for a C++ command line Linux app. I'd like to generate a bunch of integers with a power-law/long-tail distribution. Meaning, I get a some numbers very frequently but most of them relatively infrequently. Ideally there would just be some magic equations I could use with rand() or one of the st...
This page at Wolfram MathWorld discusses how to get a power-law distribution from a uniform distribution (which is what most random number generators provide). The short answer (derivation at the above link): x = [(x1^(n+1) - x0^(n+1))*y + x0^(n+1)]^(1/(n+1)) where y is a uniform variate, n is the distribution power, ...
918,841
918,848
Error installing Windows SDK v6.1 with windowssdkver command: Input string was not in a correct format
When installing Windows SDK v6.1, following the chromium instructions (http://dev.chromium.org/developers/how-tos/build-instructions-windows) I run the following command: windowssdkver -version:v6.1 -legacy I get the following error: Input string was not in a correct format. at System.Number.StringToNumber(String s...
The solution i find is to do this: Reboot first (just to be safe) Go into Regedit -> HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v6.0A Rename the key 'ProductVersion' to '-ProductVersion' Run the windowssdkver command, it seems to work then Go back into regedit, and rename the key back to its original...
919,406
919,509
What is the difference between accessing vector elements using an iterator vs an index?
What advantages are there in accessing vector elements using an iterator vs an index?
Why are iterators better than indexes? In the cases where index is not available (like with std::list, for example). In the case where a generic function accepting an iterator is called. When writing a function template that is supposed to work with more than one container type. They exist to create uniformity among a...
919,695
919,797
Moving heavily templatized C++ code to Java
I have an application written in C++ (makes heavy use of templates) that I need to take to the Java ME platform. I have two questions: Are there any good tools to convert C++ code to Java - do some basic stuff so I have a platform to start with. I found this - http://tangiblesoftwaresolutions.com/Product_Details/CPlus...
For all of Sun's marketing, Java is not simply a better C++, and in fact does not support many of the idioms and paradigms C++ supports. This makes automated translation difficult. How should you automatically turn a multi-inheritance hierarchy into Java's single inheritance hierarchy? (Note, I am not saying that a ...
919,701
920,118
Why is the copy ctor used in this code?
class A { public: A(const int n_); A(const A& that_); A& operator=(const A& that_); }; A::A(const int n_) { cout << "A::A(int), n_=" << n_ << endl; } A::A(const A& that_) // This is line 21 { cout << "A::A(const A&)" << endl; } A& A::operator=(const A& that_) { cout << "A::operator=(const A&)" << endl; } ...
Core defect 391 explains the issue. Basically, the current C++ standard requires a copy constructor to be available when passing a temporary of class type to a const reference. This requirement will be removed in C++0x. The logic behind requiring a copy constructor comes from this case: C f(); const C& r = f(); // a co...
920,033
920,050
How can I check if a combobox is a dropdown or a drop list?
Is there a way to retrieve the type of a CComboBox? I need to know if it is a "Dropdown" or a "Drop List". I've tried the following: if (m_MyComboBox.GetStyle() & CBS_DROPDOWN) // do some stuff and if (m_MyComboBox.GetStyle() & CBS_DROPDOWNLIST) // do some stuff But both expressions seem to evaluate to TRUE reg...
From winuser.h: #define CBS_DROPDOWN 0x0002L #define CBS_DROPDOWNLIST 0x0003L You need: switch(m_MyComboBox.GetStyle() & CBS_DROPDOWNLIST) { case CBS_SIMPLE: // do stuff break; case CBS_DROPDOWN: // do stuff break; case CBS_DROPDOWNLIST: // do stuff break; }
920,312
920,369
std::multimap compile errors
I am trying to use multimap for the first time but my app will not compile. TIA Paul.. // file dept.h typedef std::multimap <CString, std::map< CString, CString> > _DeparmentRecord; // also tryied replacing CString with LPCWSTR _DeparmentRecord DeparmentRecord; // file dept.cpp DWORD CIni::AddNameValue(LPCWSTR Se...
Change the function as follows. DWORD AddNameValue(LPCWSTR Section, LPCWSTR Name, LPCWSTR Value) { std::map<CString, CString> aTemp; aTemp.insert(std::make_pair (Name, Value)); DeparmentRecord.insert(std::make_pair (Section, aTemp)) ; }
920,500
920,524
What is the purpose of __cxa_pure_virtual?
Whilst compiling with avr-gcc I have encountered linker errors such as the following: undefined reference to `__cxa_pure_virtual' I've found this document which states: The __cxa_pure_virtual function is an error handler that is invoked when a pure virtual function is called. If you are writing a C++ application that...
If anywhere in the runtime of your program an object is created with a virtual function pointer not filled in, and when the corresponding function is called, you will be calling a 'pure virtual function'. The handler you describe should be defined in the default libraries that come with your development environment. ...
920,511
920,534
How to visualize bytes with C/C++
I'm working my way through some C++ training. So far so good, but I need some help reinforcing some of the concepts I am learning. My question is how do I go about visualizing the byte patterns for objects I create. For example, how would I print out the byte pattern for structs, longs, ints etc? I understand it in my ...
You can use a function such as this, to print the bytes: static void print_bytes(const void *object, size_t size) { #ifdef __cplusplus const unsigned char * const bytes = static_cast<const unsigned char *>(object); #else // __cplusplus const unsigned char * const bytes = object; #endif // __cplusplus size_t i; ...
920,615
920,637
Why do some const variables referring to some exported const variables get the value 0?
Consider the following. I have two exported constants as follows: // somefile.h extern const double cMyConstDouble; extern const double cMyConstDouble2; and // somefile.cpp const double cMyConstDouble = 3.14; const double cMyConstDouble2 = 2.5*cMyConstDouble; These constants are now referenced some place else to defi...
Because cMyConstDouble is declared as extern, compiler is not able to assume its value and does not generate a compile time initialization for cMyConstDouble2. As the cMyConstDouble2 is not compile time initialized, its order of initialization relative to cAnotherDouble2 is random (undefined). See static initialization...
920,731
920,915
C++, removing #include<vector> or #include<string> in class header
I want to remove, if possible, the includes of both <vector> and <string> from my class header file. Both string and vector are return types of functions declared in the header file. I was hoping I could do something like: namespace std { template <class T> class vector; } And, declare the vector in the header...
You cannot safely forward declare STL templates, at least if you want to do it portably and safely. The standard is clear about the minimum requirements for each of the STL element, but leaves room for implemtation extensions that might add extra template parameters as long as those have default values. That is: the st...
920,740
920,962
App Verifier reporting "Thread cannot own a critical section."
So App Verifier is throwing this exception. From what I gather, the text of this message is a little misleading. The problem appears to be that the the critical section was created by a thread that is being destroyed before the critical section is destroyed. It's a relatively simple fix but does anyone know what th...
I believe you are correct on the interpretation of the message. The only reference I can find is as follows. The stack trace is a good clue as the author suggests http://jpassing.wordpress.com/2008/02/18/application-verifier-thread-cannot-own-a-critical-section/ I dug around for a bit and cannot find any specific r...
920,829
921,074
Asynchronous screen update to gameplay logic, C++
I am programming a game using Visual C++ 2008 Express and the Ogre3D sdk. My core gameplay logic is designed to run at 100 times/second. For simplicity, I'll say it's a method called 'gamelogic()'. It is not time-based, which means if I want to "advance" game time by 1 second, I have to call 'gamelogic()' 100 times. 'g...
If this is your first game application, using multi-threading to achieve your results might be more work than you should really tackle on your first game. Sychronizing a game loop and render loop in different threads is not an easy problem to solve. As you correctly point out, rendering time can greatly affect the "sp...
921,693
921,772
How to speed up c++ linking time
Is there any way, to optimalize linking time in MS Visual studio C++ (2005) ? We're using Xoreax Incredibuild for compilation speed up, but nothing for link. Currently every linking takes about 30seconds. When I turn on incremental linking, takes abou 35-40 seconds. ( No matter if i compile project with or without inc...
I'm not aware of any parallel linking tools; I do know that Incredibuild does not allow it. The biggest tool in your toolbox for avoiding link times is the appropriate level of abstraction. If your link times are long, it may be because objects know too much about other objects. Decoupling them is then the key -- throu...
921,806
922,419
What's the point of this pattern: using a struct to contain a single method
In our code we have quite a few cases of this pattern: class outerClass { struct innerStruct { wstring operator()( wstring value ) { //do something return value; } }; void doThing() { wstring initialValue; wstring finalValue = innerStr...
It's an optimization step for templated predicates. It's not a matter of a functor being easier to use than a function. Both work pretty much the same way in boost and STL contexts. How they differ is in template instantiation. Imagine a trivial template function that requires a predicate template< typename Predicate ...
921,847
923,125
how to check if a directory is writeable in win32 C/winapi?
I know of two methods which are not reliable: _access() - doesn't work on directories (only checks existence) CreateFile() - gives false positives in the presence of virtual store (AFAIK) Most useful would be a code sample, because the win32 ACL access functions are extremely complicated. Please don't post links to m...
you can disable location virtualization for your application in a manifest file (http://www.codeguru.com/csharp/csharp/cs_misc/designtechniques/article.php/c15455/) - this should make CreateFile reliable enough for your purposes.
922,068
922,113
Image Arithmetic functions in C++
I'm trying to find/write a function that would perform the same operation as imlincomb(). However, I am having trouble finding such functions in C++ without using any Matlab API functions other than Intel Performance Primitiives library, and I don't really want to purchase a license for it unless my application really ...
There's definitely nothing of the sort in any standard C++ package. You might be able to use something in LAPACK, but I think you'd be better off writing your own. It's a fairly simple function: each output pixel is independent and depends only on the input pixels at the same coordinates. In pseudocode: for each row...
922,204
1,035,095
GetOpenFileName() does not refresh when changing filter
I use GetOpenFilename() to let the user select a file. Here is the code: wchar_t buffer[MAX_PATH] = { 0 }; OPENFILENAMEW open_filename = { sizeof (OPENFILENAMEW) }; open_filename.hwndOwner = handle_; open_filename.lpstrFilter = L"Video Files\0*.avi;*.mpg;*.wmv;*.asf\0" L"All Fi...
Okay, I have figured out the problem, or at least, I have a solution that is working for me. Earlier in the code, I had the following call to initialize COM... ::CoInitializeEx(NULL, COINIT_MULTITHREADED); Well, changing this to... ::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); ...solves the problem for me! Now th...
922,358
922,385
Consistent pseudo-random numbers across platforms
I am looking for a way to generate pseudo random number sequences that will yield identical sequence results for a given seed across any platform. I am assuming that rand() / srand() is not going to be consistent (I could easily be wrong about this assumption).
Something like a Mersenne Twister (from Boost.Random) is deterministic.
922,368
922,388
Removing map element by value
I'll keep this brief. I am trying to keep a map between strings and object pointers, and as such, I use std::map. I have a manager that's a global class that keeps track of the map, and whenever an object's destructor is called, it tells the manager that it has been deleted. The only way I can think of is to search thr...
No there is not an efficient way of doing this with std::map other than iterating through comparing the values. However most of the time the key for a value is computable from the value itself. For example using the Name property of a Person object as the key. Is it possible for the manager to store a list of key /...
922,442
927,603
Unique class type Id that is safe and holds across library boundaries
I would appreciate any help as C++ is not my primary language. I have a template class that is derived in multiple libraries. I am trying to figure out a way to uniquely assign an id int to each derived class. I need to be able to do it from a static method though, ie. template < class DERIVED > class Foo { public: ...
Here's what I ended up doing. If you have any feedback (pros, cons) please let me know. template < class DERIVED > class Foo { public: static const char* name(); // Derived classes will implement, simply // returning their class name static int s_id() { static const i...
922,829
923,212
C++ :: Boost :: posix_time (elapsed seconds. elapsed fractional seconds)
I'm trying to come up with an answer to two questions that didn't seem hard at first. Q1 : How do I obtain the number of elapsed seconds between UTC.Now() and a given date? A1 : Just like in the code below! Q2 : How do I determine how many fractional seconds have elapsed since the last "full" second ? I'd like to print...
You are using the second_clock to get the current time. As the name implies, it is accurate only to the nearest second. Since your reference time has no fractional seconds the duration fractional seconds always ends up being 0. Use the microsec_clock instead: ptime Now = microsec_clock::universal_time(); Also, in such...
923,288
923,309
Guides to help learn C++ specifically from a C# background
Is there a guide/reference anyone would recommend to pick up C++ specifically if you have strong experience of C#? There are C++ guides, but a lot start with the absolute basics and I feel I've covered a lot with my C# learnings. But the absolute basics may be a good thing and I may be barking up the wrong tree - I ima...
Useful info on a C# to C++ (Win32) project port. Might be a good starting point. http://blogs.cozi.com/tech/2008/03/index.html
923,458
923,496
Running a separate process or thread in Qt
I'm writing my first proper useful piece of software. Part of it will involve the user viewing an image, and choosing to accept or reject it. Doing this will cause the image to be saved to an accepted or rejected folder, and possibly rotated and/or resized. At the moment, my rotate/resize/save operation is pausing exec...
Qt has thread support. You might find this example application interesting since it's somewhat similar to what you describe. Also, here is the full Qt thread documentation.
923,649
923,667
Copying an integer to a Buffer memcpy C++
Basically I would like to store the address of a pointer in a buffer. Don't ask me why char * buff = "myBuff"; char * myData = (char*)malloc(sizeof(char*)); int addressOfArgTwo = (unsigned int)buff; memcpy(myData, &addressOfArgTwo, sizeof(char*)); cout << "Int Val: " << addressOfArgTwo << endl; cout << "Address in buf...
You dereference a char *, resulting in a char, and then cast that 1-byte char to an int, not the entire 4 bytes of address (if this is a 32-bit machine, 8 bytes on 64-bit). 4472832 is 444000 in hexadecimal. On a little-endian machine, you grab that last 00. *((unsigned int*)myData) should result in the correct numbe...
923,688
923,692
Some questions about special operators i've never seen in C++ code
I have downloaded the Phoenix SDK June 2008 (Tools for compilers) and when I'm reading the code of the Hello sample, I really feel lost. public ref class Hello { //-------------------------------------------------------------------------- // // Description: // // Class Variables. // // Remarks: // // A normal com...
It's not standard C++, it's C++/CLI.
923,922
923,964
Event / Task Queue Multithreading C++
I would like to create a class whose methods can be called from multiple threads. but instead of executing the method in the thread from which it was called, it should perform them all in it's own thread. No result needs to be returned and It shouldn't block the calling thread. A first attempt Implementation I have in...
There's Futures library making its way into Boost and the C++ standard library. There's also something of the same sort in ACE, but I would hate to recommend it to anyone (as @lothar already pointed out, it's Active Object.)
924,257
924,259
C++ Programming Book Example on Stack
In this book, I am learning how the book writes a stack, but when I compile it, it reaches a compile error: #define DEFAULT_SIZE = 10 class Stack { private: int size; int top; int *value; public: Stack( int size = DEFAULT_SIZE ); virtual ~Stack(); bool isFull();...
Do this: #define DEFAULT_SIZE 10 The = sign is not needed in the preprocessor definition.
924,354
925,008
URL escaping MFC strings
How do you URL escape an MFC CString?
InternetCanonicalizeUrl()
924,360
924,431
Difference between C++ reference type argument passing and C#'s ref?
I always thought they were about the same thing but someone pointed me out in one of my answers that such ain't quite true. Edit: Here is what I said and the comment I got. Edit2: What's the difference between C++'s: public: void foo(int& bar); and C#'s public void foo(ref int bar){ }
In C#, you have primitive types (ints, structs, etc.) and reference types (objects). These are built in to the language. In C++, you have to be explicit. Here is a set of equivalent ways of referring to objects in C# and C++, based on whether they are reference types or primitives, and whether or not you're using ref: ...
924,485
924,495
What's the difference between a header file and a library?
One of the things I'm having a hard time understanding is how the compiler works. I'm having a lot of difficulties with it, but in particular I keep getting headers and libraries mixed up. If somebody could clear things up a bit, that'd be great.
Think of both like this (Disclaimer: this is a really high-level analogy ;) .. The header is a phone number you can call, while... ...the library is the actual person you can reach there! It's the fundamental difference between "interface" and "implementation"; the interface (header) tells you how to call some functi...
924,642
924,672
boost spirit headers deprecated
I am following the quickstart guide for boost::spirit, and I get this compiler warning when I include : "This header is deprecated. Please use: boost/spirit/include/classic_core.hpp" Should I be worried about this? (quick start guide: http://spirit.sourceforge.net/distrib/spirit_1_8_5/libs/spirit/doc/quick_start.html ...
[EDIT:] The original answer is badly out of date; in particular the link is broken. The current version of Boost (since 2012-02-24) is 1.49.0. The warning mentioned is a result of #include <boost/spirit.hpp> which is a deprecated header; however old examples on the web use this form. To get started, try the boost tuto...
924,830
924,854
what is difference btw /MD and /MDD in VisualStudio C++?
What is difference betwwen /MD and /MDD( multi threaded debug dll ) in c/c++->code generation propertis of visual studio ....
They specify which runtime to use. Both use mmulti-threaded dynamic (DLL) runtimes, but the /MDD version uses the debug version and also defines the _DEBUG symbol for you. See this MSDN page for details.
925,084
925,153
POD low dimensional vector in boost
I'm looking for POD low dimension vectors (2,3 and 4D let say) with all the necessary arithmetic niceties (operator +, - and so on). POD low dimension matrices would be great as well. boost::ublas vectors are not POD, there's a pointer indirection somewhere (vector are resizeable). Can I find that anywhere in boost? Us...
There is a nice Vector library for 3d graphics in the prophecy SDK: Check out http://www.twilight3d.com/downloads.html
925,487
925,863
Is there a way to detect an alphanumeric Unicode symbol?
I have a Unicode string consisting of letters, digits and punctuation marks. Ho can I detect characters that are digits and letters (not necessarily ASCII) with a C++ standard library or Win32 API?
iswdigit(), iswalpha() and iswalnum() are the functions you are looking for. Cheers !
925,513
925,569
C++ empty String constructor
I am a C++ beginner, so sorry if the question is too basic. I have tried to collect the string constrcturs and try all them out (to remember them). string strA(); // string(); empty string // incorrect string strB("Hello"); // string( const char* str) string strC("Hello",3); // string( const char* str, size_...
This is a very popular gotcha. C++ grammar is ambiguous. One of the rules to resolve ambiguities is "if something looks like declaration it is a declaration". In this case instead of defining a variable you declared a function prototype. string strA(); is equivalent to string strA(void); a prototype of a no-arg func...
926,010
926,031
Helper library for distributed algorithms programming?
When you code a distributed algorithm, do you use any library to model abstract things like processor, register, message, link, etc.? Is there any library that does that? I'm thinking about e.g. self-stabilizing algorithms, like self-stabilizing minimum spanning-tree algorithms.
There's a DVM system that can be used for implementing different distributed algorithms. It works on top of MPI. However it is more for matrix-oriented scientific algorithms where distribution is done in terms of data blocks. I had a brief experience using it - it's much more convenient than direct usage of MPI and all...
926,097
926,186
Replace strings in native .exe using c#
how can I catch all strings from a native windows .exe file and replace them later with others using c# ? Background: I want to create a c# tool to extract and replace strings from a simple .exe file. Is this possible somehow?
What you need to start is a PE/COFF parser. If your strings are stored in a resource section in the PE, then it's pretty easy. For instance, you can load an exe into Visual Studio as a resource file and use its resource editor to change icons and strings and such in the exe. If on the other hand the strings are stored ...
926,172
926,192
How to hide strings in a exe or a dll?
I discovered that it is possible to extract the hard-coded strings from a binary. For example the properties view of Process Explorer displays all the string with more than 3 characters. Here is the code of a simple executable that I wrote to simply test it: #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0501 #endif #incl...
Welcome to the wider world of defensive programming. There are a couple of options, but I believe all of them depend on some form of obfuscation; which, although not perfect, is at least something. Instead of a straight string value you can store the text in some other binary form (hex?). You can encrypt the strings t...
926,187
926,339
Difference between two DLL declarations
I have a simple but subtle question. Below you see two different declaration variants of the same class from a DLL header file. Can anybody tell me the difference of this class declaration; class __declspec(dllexport) Car { public: Car(); void drive(void); typedef enum { None, Indented } Formatting; } fro...
A brief test using depends showed that the first example exports one additional symbol compared to the second (btw you don't export an enum, it's not legal). If I'm not wrong I believe it was the default assignment operator. The first approach exports the entire class, the second one just the methods that are prefixed ...
926,551
926,578
Where to install SDK DLLs on a system so that they can be found by apps that need them
I've got an SDK I'm working on and the previous developer just dropped the DLLs in System32 (Apparently a serious offense: see here) So assuming I move them out into \Program Files\\SDK (or whatever), how do I make sure that all the apps that needs those DLLs can access them? And to clarify, all apps that access these...
An SDK is by definition a development kit. It's not a deployment patch... What this means is that the applications that depend on those assemblies should ship with them and install them into their local \program files.. directories. The reason for this is let's say you decide to do a breaking change by eliminating an ...
926,728
928,659
Will my iPhone app take a performance hit if I use Objective-C for low level code?
When programming a CPU intensive or GPU intensive application on the iPhone or other portable hardware, you have to make wise algorithmic decisions to make your code fast. But even great algorithm choices can be slow if the language you're using performs more poorly than another. Is there any hard data comparing Object...
Mike Ash has some hard numbers for performance of various Objective-C method calls versus C and C++ in his post "Performance Comparisons of Common Operations". Also, this post by Savoy Software is an interesting read when it comes to tuning the performance of an iPhone application by using Objective-C++. I tend to p...
926,752
926,795
Why should I prefer to use member initialization lists?
I'm partial to using member initialization lists with my constructors... but I've long since forgotten the reasons behind this... Do you use member initialization lists in your constructors? If so, why? If not, why not?
For POD class members, it makes no difference, it's just a matter of style. For class members which are classes, then it avoids an unnecessary call to a default constructor. Consider: class A { public: A() { x = 0; } A(int x_) { x = x_; } int x; }; class B { public: B() { a.x = 3; } p...
926,915
927,041
How do text differencing applications work?
How do applications like DiffMerge detect differences in text files, and how do they determine when a line is new, and not just on a different line than the file being checked against? Is this something that is fairly easy to implement? Are there already libraries to do this?
Here's the paper that served as the basis for the UNIX command-line tool diff.
927,043
927,104
Is there a way to determine if a top level Qt window has been moved?
I am trying to determine when the main window of my application has been moved. The main window is a standard QMainWindow and we've installed an eventFilter on the QApplication to look for moveEvents for the QMainWindow, but none are being triggered. For a variety of reasons, subclassing the QMainWindow isn't really an...
I guess it's better to install the event filter at the top-level window, instead of the application. However, if you still do not get QMoveEvents and you're working on Windows, you probably can override winEventFilter() and wait for WM_MOVE. Similar functionality might be available for Linux and Mac. I usually do not r...
927,063
927,287
Building C++ source code as a library - where to start?
Over the months I've written some nice generic enough functionality that I want to build as a library and link dynamically against rather than importing 50-odd header/source files. The project is maintained in Xcode and Dev-C++ (I do understand that I might have to go command line to do what I want) and have to link ag...
I'd recommend building as a statc library rather than a DLL. A lot of the issues of exporting C++ functions and classes go away if you do this, provided you only intend to link with code produced by the same compiler you built the library with. Building a static library is very easy as it is just an collection of .o/.o...
927,574
927,591
Compiling C++ Program Causes "Fatal Error LNK1104"
I am trying to compile a c++ application using the following command in command prompt: cl -I"c:\Program files\Java\jdk1.5.0_07\include" -I"c:\program files\java\jdk1.5.0_07\include\win32" -MD -LD HelloWorld.cpp -FeHelloWorld.dll However, this produces the following error: LINK : fatal error LNK1104: cannot open file...
LINK : fatal error LNK1104: cannot open file 'MSVCRT.lib' Any ideas of what is causing this and how to fix it? The linker needs to be pointed to the location of MSVCRT.lib, as it doesn't seem to be in your LIBPATH. It should be here: C:\Program Files\Microsoft Visual Studio 7\VC\lib Add -link -LIBPATH:"C:\Program Fil...
927,631
9,523,724
Is there a heap class in C++ that supports changing the priority of elements other than the head?
I have a priority queue of events, but sometimes the event priorities change, so I'd like to maintain iterators from the event requesters into the heap. If the priority changes, I'd like the heap to be adjusted in log(n) time. I will always have exactly one iterator pointing to each element in the heap.
I'm happy to report that Boost has now added a Boost.Heap library with some stellar data structures. The advantage of this is that Fibonacci heaps support changing priority in constant amortized time. Unfortunately, all of the mutable heaps are node-based (in other words, they have extra indirection as suggested by @wi...
927,901
927,934
Weird way to write "hello world"
Possible Duplicates: Changing c++ output without changing the main() function How to assign a method's output to a textbox value without code behind How to write hello world without modifying main function? Thanks int main(){return 0;}
#include<iostream> int hello() { cout<<"Hello World"<<endl; } static int foo = hello(); int main(){return 0;}
927,945
927,950
Deleting a heap then dereferencing a pointer to that memory
This is code from an exercise: #include <iostream> using namespace std; int main() { int n = 13; int* ip = new int(n + 3); int* ip2 = ip; cout << *ip << endl; delete ip; cout << *ip2 << endl; cout << ip << tab << ip2 << endl; } When the space allocated to the int on the heap is deleted, I ...
Dereferencing an invalid pointer leads to undefined results per spec. It's not guaranteed to fail. Usually (CPU/OS/compiler/... dependent), the compiler doesn't really care about it at all. It just gives what's currently at that memory address. For example, in x86 architecture, you just see an error only when the addr...
928,568
928,732
Creating multiple instances of global statics in C++?
One of the libraries we are using for our product uses a singleton for access to it. I'm pretty sure it's implemented as a static instance (it isn't open source). This works well for a single document application, but our app may have more than one document loaded. I'm assuming access to the instance is written somethi...
The only thing that I can think of is to sub-class it if you are lucky enough to have the singleton class defined like: class Document { public: static Document* getInstance() { static Document inst; return &inst; } virtual ~Document(); protected: Document(); private: struct Impl; ...
928,613
928,620
Is this the correct way to overload the left-stream operator? (C++)
This function declaration gives me errors: ostream& operator<<(ostream& os, hand& obj); The errors are: error C2143: syntax error : missing ';' before '&' error C4430: missing type specifier error C2065: 'os' : undeclared identifier error C2065: 'obj' : undeclared identifier error C2275: 'hand' : illegal use of this t...
The declaration looks right. But the error message suggests that ostream is not known as a type. Try including the iostream header and say std::ostream instead. Another thing you should consider is making the parameter 'hand' a const reference. So you could also accept temporaries and print them out.
928,662
928,679
What does "cannot convert 'this' pointer from 'const hand' to 'hand &' mean? (C++)
The error occurs when I try to do this friend std::ostream& operator<<(std::ostream& os, const hand& obj) { return obj.show(os, obj); } where hand is a class I've created, and show is std::ostream& hand::show(std::ostream& os, const hand& obj) { return os<<obj.display[0]<<obj.display[1]<<obj.display[2]<<obj.di...
You need to make hand::show(...) a const method; and it doesn't make sense to pass it obj reference -- it already receives that as the 'this' pointer. This should work: class hand { public: std::ostream& show(std::ostream &os) const; ... }; friend std::ostream& operator<<(std::ostream& os, const hand& obj) { ret...
928,694
928,701
What does "warning: not all control paths return a value" mean? (C++)
The exact warning I get is warning C4715: 'hand::show' : not all control paths return a value and hand::show is std::ostream& hand::show(std::ostream& os) const { if(side == left) { return os<<display[0]<<display[1]<<display[2]<<display[3]<<display[4]; } if(side == right) { return o...
Your compiler isn't smart enough to take into account that the only two options for side are left and right, so it thinks it's possible for neither return statement to be executed. When side is neither left nor right, your function doesn't say which value to return.
928,751
928,761
declare a array of const ints in C++
I have a class and I want to have some bit masks with values 0,1,3,7,15,... So essentially i want to declare an array of constant int's such as: class A{ const int masks[] = {0,1,3,5,7,....} } but the compiler will always complain. I tried: static const int masks[] = {0,1...} static const int masks[9]; // then init...
class A { static const int masks[]; }; const int A::masks[] = { 1, 2, 3, 4, ... }; You may want to fixate the array within the class definition already, but you don't have to. The array will have a complete type at the point of definition (which is to keep within the .cpp file, not in the header) where it can ded...
928,758
928,765
How can I fix an int-to-bool warning in C++?
I get a warning in MSVC++ when I try to read an integer from a file and make a bool variable equal it. accessLV[i] = FileRead(file1, i + 1); (accessLV is an array of bools, FileRead is a function I made to decrease the syntax involved in reading from a file, i is because the statement is within a for loop) I've tried ...
How about accessLV[i] = FileRead(file1, i + 1) != 0;
928,777
929,369
C++ code to get line of file and read the second word of the line?
#include <iostream> #include <string> #include <fstream> using namespace std ; string strWord( int index , string line) { int count = 0; string word; for ( int i = 0 ; i < line.length(); i++) { if ( line[i] == ' ' ) { if ( line [i+1] != ' ') ...
You wanted a comment of each line // function that returns a word from 'line' with position 'index' // note that this is not a zero based index, first word is 1, // second is 2 etc .. string strWord(int index, string line) { int count = 0; // number of read words string word; // the resulting word for (int ...
928,992
929,015
Nested functions are not allowed but why nested function prototypes are allowed? [C++]
I was reading the linked question which leads me to ask this question. Consider the following code int main() { string SomeString(); } All says, compiler takes this as a function prototype and not as a string object. Now consider the following code. int main() { string Some() { return ""; } } ...
Your prototype is just 'Forward Declaration'. Please check out the Wikipedia article. Basically, it tells the compiler "don't be alarmed if the label 'SomeFun' is used in this way". But your linker is what's responsible for finding the correct function body. You can actually declare a bogus prototype, e.g. 'char Some...
929,016
936,439
msvc9, iostream and 2g/4g plus files
Doing cross platform development with 64bit. Using gcc/linux and msvc9/server 2008. Just recently deployed a customer on windows and during some testing of upgrades I found out that although std::streamoff is 8 bytes, the program crashes when seeking past 4G. I immediately switched to stlport which fixes the problem, ...
I ended up using STLport. The biggest difference with STLport being that some unit tests which crashed during multiplies of double precision numbers now work and those unit tests pass. There are some other differences with relative precision popping up but those seem to be minor.
929,976
929,986
C++: Assigning values to non-continuous indexes in vectors?
If I want to declare a vector of unknown size, then assign values to index 5, index 10, index 1, index 100, in that order. Is it easily doable in a vector? It seems there's no easy way. Cause if I initialize a vector without a size, then I can't access index 5 without first allocating memory for it by doing resize() or...
Resize doesn't clear the vector. You can easily do something like: if (v.size() <= n) v.resize(n+1); v[n] = 42; This will preserve all values in the vector and add just enough default initialized values so that index n becomes accessible. That said, if you don't need all indexes or contigous memory, you migh...
930,138
930,141
Is clrscr(); a function in C++?
I've looked everywhere for this function and cannot find the header files to make this work. It says clrscr() undeclared which brings me to the question. Is clrscr(); a function in C++?
It used to be a function in <conio.h>, in old Borland C compilers. It's not a C++ standard function.
930,323
930,344
«F(5)» and «int x; F(x)» to call different functions?
I'd like to write two distinct functions to handle a constant value and a variable of a given type (viz., int). Here is the example test case: int main(void) { int x=12; F(5); // this should print "constant" F(x); // this should print "variable" } I thought it would be enough to define: void F...
If what you want is to differentiate between a compile time constant and a non-compile time constant - then you have no chance. That's not possible. But if you want to differentiate between a non-constant variable and between a constant variable (and everything else included - like literals), then you can overload a f...
930,334
931,004
Processing Escapes using the Spirit Parser Framework
I'm trying to parse a string similar to the following using a spirit parser: <junk> -somearg#this is a string with a literal ## in it# <junk> What I'm looking for is a grammar which can extract the portion inside the # marks, but is smart to skip over the double ## in the middle, which is an escape meaning a literal #....
I solved this by adding a kleene star to the confix parser. Thanks anyway! *confix_p(L'#', *anychar_p, L'#' >> ~ch_p(L'#')) works as expected.
930,622
930,866
Does there exist a "wiki" for editing doxygen comments?
I'm working on a fairly big open source RTS game engine (Spring). I recently added a bunch of new C++ functions callable by Lua, and am wondering how to best document them, and at the same time also stimulate people to write/update documentation for a lot of existing Lua call-outs. So I figured it may be nice if I coul...
This is a very cool idea indeed, and a couple of years ago I also had a very strong need for something like that. Unfortunately, at least back then, I wasn't able to find something like that. Doing a quick search on sourceforge and freshmeat also doesn't bring up anything related today. But I agree that such a wiki fro...
930,897
930,970
C++ atomic operations for lock-free structures
I'm implementing a lock-free mechanism using atomic (double) compare and swap instructions e.g. cmpxchg16b I'm currently writing this in assembly and then linking it in. However, I wondered if there was a way of getting the compiler to do this for me automatically? e.g. surround code block with 'atomically' and have i...
Already kindof answered here. The C++0x standard will provide some atomic datatypes, mainly integer and void types using std::atomic<> template. That article mentions Boehm's atomic_ops project which you can download and use today. If not, can't you implement your assembler inline in the compiler? I know MSVC has the _...
930,932
930,940
Returning different data type depending on the data (C++)
Is there anyway to do something like this? (correct pointer datatype) returnPointer(void* ptr, int depth) { if(depth == 8) return (uint8*)ptr; else if (depth == 16) return (uint16*)ptr; else return (uint32*)ptr; } Thanks
No. The return type of a C++ function can only vary based on explicit template parameters or the types of its arguments. It cannot vary based on the value of its arguments. However, you can use various techniques to create a type that is the union of several other types. Unfortunately this won't necessarily help you he...
931,093
931,165
How do I make my program watch for file modification in C++?
There are a lot of programs, Visual Studio for instance, that can detect when an outside program modifies a file and then reload the file if the user wants chooses. Is there a relatively easy way to do this sort of thing in C++ (doesn't necessarily have to be platform independent)?
There are several ways to do this depending on the platform. I would choose from the following choices: Cross Platform Trolltech's Qt has an object called QFileSystemWatcher which allows you to monitor files and directories. I'm sure there are other cross platform frameworks that give you this sort of capability too,...
931,195
931,205
How do you make a prototype of a function with parameters that have default values?
A have a function with a prototype of: void arryprnt(int[], string, int, string, string); And a definition of: void arryprnt(int[] a, string intro, int len, string sep=", ", string end=".") { // stuff } And I'm calling it like this: arryprnt(jimmy, "PSEUDOJIMMY: ", 15); ...When I make that call to arryprnt, I get a ...
You should put the default arguments in the prototype, not the definition like this: void arryprnt(int[] a, string intro, int len, string sep=", ", string end="."); and the make the definition without them: void arryprnt(int[] a, string intro, int len, string sep, string end) { // ... } BTW: on another note. It i...
931,293
931,364
linking c++ sources in iPhone project
I have a single cpp file added to my iPhone project with a .cpp extension, but I'm seeing errors when linking like: operator new[](unsigned long)", referenced from: ___gxx_personality_sj0", referenced from: I thought as long as I named the cpp files with .cpp or .mm it would do the right thing, do I need to add some ...
Select the file in the project browser, and press cmd-i to bring up the info window for the file in question. Set File Type to sourcecode.cpp.cpp should do it. Alternatively right click on your project, add new file, select C++ source, then copy and paste the content. In light of the build log, try adding the following...
931,301
931,318
Which is more readable (C++ = )
int valueToWrite = 0xFFFFFFFF; static char buffer2[256]; int* writePosition = (int* ) &buffer2[5]; *writePosition = valueToWrite; //OR * ((int*) &buffer2[10] ) = valueToWrite; Now, I ask you guys which one do you find more readable. The 2 step technique involving a temporary variable or the one step technique? Do not...
int* writePosition = (int* ) &buffer2[5] Or *((int*) &buffer2[10] ) = valueToWrite; Are both incorrect because on some platforms access to unaligned values (+5 +10) may cost hundreds of CPU cycles and on some (like older ARM) it would cause an illegal operation. The correct way is: memcpy( buffer+5, &valueToWrite, si...
931,476
931,490
finding a function name and counting its LOC
So you know off the bat, this is a project I've been assigned. I'm not looking for an answer in code, but more a direction. What I've been told to do is go through a file and count the actual lines of code while at the same time recording the function names and individual lines of code for the functions. The problem I...
Three approaches come to mind. Use regular expressions. This is fairly similar to what you're thinking of. Look for lines that look like function definitions. This is fairly quick to do, but can go wrong in many ways. char *s = "int main() {" is not a function definition, but sure looks like one. char * /* eh? */ s (...
931,502
931,516
gaming with c++ or c#?
What is the best language for programming a game project and why? Why is the game programing world dominated by c++?
This is kind of a difficult question to answer. For the most part, C++ is a "better" language for programming games in that it gives you so much direct control over memory management that you have more options to fine tune your performance. That, along with the fact that C++ has been around ages longer than C#, have le...
931,713
931,781
Reading from a socket 1 byte a time vs reading in large chunk
What's the difference - performance-wise - between reading from a socket 1 byte a time vs reading in large chunk? I have a C++ application that needs to pull pages from a web server and parse the received page line by line. Currently, I'm reading 1 byte at a time until I encounter a CRLF or the max of 1024 bytes is rea...
If you are reading directly from the socket, and not from an intermediate higher-level representation that can be buffered, then without any possible doubt, it is just better to read completely the 1024 bytes, put them in RAM in a buffer, and then parse the data from the RAM. Why? Reading on a socket is a system call, ...
931,827
931,873
std::string comparison (check whether string begins with another string)
I need to check whether an std:string begins with "xyz". How do I do it without searching through the whole string or creating temporary strings with substr().
I would use compare method: std::string s("xyzblahblah"); std::string t("xyz") if (s.compare(0, t.length(), t) == 0) { // ok }
931,890
931,915
What is more efficient a switch case or an std::map
I'm thinking about the tokenizer here. Each token calls a different function inside the parser. What is more efficient: A map of std::functions/boost::functions A switch case
STL Map that comes with visual studio 2008 will give you O(log(n)) for each function call since it hides a tree structure beneath. With modern compiler (depending on implementation) , A switch statement will give you O(1) , the compiler translates it to some kind of lookup table. So in general , switch is faster. Howev...
932,092
1,304,488
Default HTML style for controls in the Qt library
This is a question about Qt library, not about Web design. For QLabel and other controls I can set HTML text, for example "<h3>Some Text</h3>". The question is: where is the default HTML style is defined? How can I find out what a font would be used for <h3> tag? The next question: can I change the default HTML style? ...
What you want cannot be done with a QLabel. The QLabel is designed to hold primative text labels - it's HTML support is rather... ropey. However, You can achieve this using a QTextEdit & QTextDocument. Try something like this (I'm writing this from memory, so it may not compile or be 100% correct): QTextDocument *doc =...
932,114
933,925
Total beginner looking for tutorials programming outlook add ins in c++
I'm an absolute beginner in Outlook programming and Windows GUI programming in general. But I have lots of years experience in C++ programming in general (not GUI) I need to develop a Outlook plug-in and my question is where to start? What do I need to know to let me start? Can you please give me some useful links to l...
OutlookCode.com and it's forums are always my first point of call with Outlook related programming. Also see the Office Developer Centre. For your specific scenario the COM Add-ins page links to the following ATL/C++ sample.
932,237
932,362
How to run a dictionary search against a large text file?
We're in the final stages of shipping our console game. On the Wii we're having the most problems with memory of course, so we're busy hunting down sloppy coding, packing bits, and so on. I've done a dump of memory and used strings.exe (from sysinternals) to analyze it, but it's coming up with a lot of gunk like this: ...
First, I'd get a good word list. This NPL page has a good list of word lists of varying sizes and sources. What I would do is build a hash table of all the words in the word list, and then test each word that is output by strings against the word list. This is pretty easy to do in Python: import sys dictfile = open...
932,384
932,404
gdb says "cannot open shared object file"
I have one binary and one shared library. The shared library is compiled with: all: g++ -g -shared -fpic $(SOURCES) -o libmisc.so the binary is compiled with: LIBS=-L../../misc/src LDFLAGS=-lmisc all: g++ -g -o mainx $(INCLUDE) $(SOURCE) $(LIBS) $(LDFLAGS) I set in ~/.bashrc export LD_LIBRARY_PATH=/mnt/sda5/Program...
Emacs probably does not read your .bashrc before it invokes gdb. Try to put 'set solib-search-path' and 'set solib-absolute-path in your .gdbinit file instead