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
763,608
763,628
How to make a .com file using C/C++?
How can we make a .com file using C/C++? Is it possible? Edit: I was able to successfully make a com file using darin's suggestions. But somehow the exe file of the following program cannot be converted to com file. I get the "File cannot be converted" message by exe2bin. I'm using Borland Turbo C++ 3.0. Any suggestion...
In C, you must compile your program with the TINY memory model. Then you can use use EXE2BIN or a similar program to convert an EXE file to a COM file.
763,656
763,841
Should we still be optimizing "in the small"?
I was changing my for loop to increment using ++i instead of i++ and got to thinking, is this really necessary anymore? Surely today's compilers do this optimization on their own. In this article, http://leto.net/docs/C-optimization.php, from 1997 Michael Lee goes into other optimizations such as inlining, loop unro...
If there is no cost to the optimization, do it. When writing the code, ++i is just as easy to write as i++, so prefer the former. There is no cost to it. On the other hand, going back and making this change afterwards takes time, and it most likely won't make a noticeable difference, so you probably shouldn't bother wi...
763,837
774,914
Eclipse has two C/C++ indexers (fast & full): what's the difference?
Eclipse CDT provides two indexers for C/C++ code (Preferences > C/C++ > Indexer). Does anybody know what the exact difference is between these two? The help file isn't exactly enlightening: "CDT supports the contribution of additional indexers, with 2 indexers being provided with the default CDT release: Fast ...
Here is an excerpt from the CDT page describing their parsing and indexing(CDT/designs/Overview of Parsing). It gives a pretty good description of what the differences are and where the fast indexer can fail: Parsing and binding resolution is a slow process, this is a problem because the user expects code editing...
764,540
764,552
HTML Sanitization in C++
Is there any available C++ (or maybe C) function/class/library with only purpose to sanitize a string that might contain HTML? I find a lot of source code for sanitizing in C# or other languages more used in web application but nothing in C++. I'll try to implement my own function if I don't find any available but I t...
HTML Tidy is written in c, but there are bindings for practically every language/platform, including c++.
764,555
764,561
Determing exit point of application. C++/Linux
I'm working on a big app (ns2) and somewhere someone put an exit(1) in there without any debug or print statements and it is being executed. I don't want to have to manually check every file that calls exit to figure out why the program is exiting. Is is possible to determine where the program exited? This is running o...
Sure. Put a breakpoint at the start of exit(3). When it breaks, look at the stack. Second choice, run it under truss(1) (I'm pretty sure there's a Linux version of truss.) Or strace(1). Update In fact, I ran across another method in another question: here's a link.
764,824
764,872
Best way to organize entities in a game?
Let's say I'm creating an OpenGL game in C++ that will have many objects created (enemies, player characters, items, etc.). I'm wondering the best way to organize these since they will be created and destroyed real-time based on time, player position/actions etc. Here's what I've thought of so far: I can have a global...
I'm not sure I fully understand the question but I think you are wanting to create a collection of polymorphic objects. When accessing a polymorphic object, you must always refer to it by a pointer or a reference. Here is an example. First you need to set up a base class to derive your objects from: class BaseObject { ...
764,833
764,840
Programming a Steganography application in C/C++
I have been reading up on on steno for a while. I have seen tools that help aid in embedding messages in .mp3's and png's etc. I am familiar that they do this by replacing the least important bit. In images, these LIB are colors that the human eye can't see; thus not needed. In audio files frequencies not audible to th...
Your application needs to be aware of the file formats. You can't just go changing the LSB of random words in a PNG, nor in an mp3. Once you can read and write back those format, analyze the data, figure out where the LIBs (where importance is the perception of the user, not the least significant bit of the architect...
765,148
10,669,041
How to remove constness of const_iterator?
As an extension to this question Are const_iterators faster?, I have another question on const_iterators. How to remove constness of a const_iterator? Though iterators are generalised form of pointers but still const_iterator and iterators are two different things. Hence, I believe, I also cannot use const_cast<> to ...
There is a solution with constant time complexity in C++11: for any sequence, associative, or unordered associative container (including all of the Standard Library containers), you can call the range-erase member function with an empty range: template <typename Container, typename ConstIterator> typename Container::i...
765,228
765,230
32bit int * 32bit int = 64 bit int?
In other words does this work as expected? int32 i = INT_MAX-1; int64 j = i * i; or do I need to cast the i to 64 bit first?
You need to cast at least one of the operands to the multiply. At the point the multiply is being done, the system doesn't know you're planning to assign to an int64. (Unless int64 is actually the native int type for your particular system, which seems unlikely)
765,257
765,266
Should I prefer iterators over const_iterators?
Someone here recently brought up the article from Scott Meyers that says: Prefer iterators over const_iterators (pdf link). Someone else was commenting that the article is probably outdated. I'm wondering what your opinions are? Here is mine: One of the main points of the article is that you cannot erase or insert o...
I totally agree with you. I think the answer is simple: Use const_iterators where const values are the right thing to use, and vice versa. Seems to me that those who are against const_iterators must be against const in general...
765,301
765,395
Should I reject C++ because it's becoming a juggernaut?
I have tried to keep up with C++ since they introduced 1998 ANSI/ISO C++. I absorbed the new concepts and tried to understand them. I learned about exception handling, templates, and namespaces. I've read about the new cast mechanisms and worked with the STL library. All of these concepts required a lot of energy. But ...
Hear what Bruce Eckel { author of the two of the so-called best C++ books } commented on C++ a few weeks ago: That said, I hardly ever use C++ anymore. When I do, it's either examining legacy code, or to write performance-critical sections, typically as small as possible to be called from other code (my pref...
765,408
765,474
Free easy way to draw graphs and charts in C++?
I am doing a little exploring simulation and I want to show the graphs to compare the performance among the algorithms during run-time. What library comes to your mind? I highly prefer those that come small as I'd love if it's easy for my instructor to compile my code. I've checked gdchart but it seems to be too heavy....
My favourite has always been gnuplot. It's very extensive, so it might be a bit too complex for your needs though. It is cross-platform and there is a C++ API.
765,459
765,494
How can you do C++ when your embedded compiler doesn't have operator new or STL support?
I am working on a group senior project for my university and I have run into a major hurdle in trying to get my code to work. The compiler that we have for our 8 bit Atmel microcontroller does not support the new or delete operators, and it does not support the C++ STL. I could program it in C, but I have to implement...
Just for the record, zeroing the bits in an object won't affect whether the destructor gets called (unless the compiler has a special quirk that enables this behaviour). Just write some logging statements in your destructor to test this out. Structuring your program not to allocate anything is probably the way the syst...
765,629
765,644
Learning OpenGL through Java
I'm interested in learning OpenGL and my favorite language at the time is Java. Can I reap its full (or most) benefits using things like JOGL or should I instead focus on getting stronger C++ skills? Btw, which is your Java OpenGL wrapper library of choice and why?
JOGL is a wrapper library that allows OpenGL to be used in the Java programming language. It is currently the reference implementation for JSR-231 (Java Bindings for OpenGL) so it should be your first choice
765,709
765,722
Why compiler is not giving error when signed value is assigned to unsigned integer? - C++
I know unsigned int can't hold negative values. But the following code compiles without any errors/warnings. unsigned int a = -10; When I print the variable a, I get a wrong value printed. If unsigned variables can't hold signed values, why do compilers allow them to compile without giving any error/warning? Any thoug...
Microsoft Visual C++: warning C4245: 'initializing' : conversion from 'int' to 'unsigned int', signed/unsigned mismatch On warning level 4. G++ Gives me the warning: warning: converting of negative value -0x00000000a' to unsigned int' Without any -W directives. GCC You must use: gcc main.c -Wconversion Which will...
765,778
765,780
Why does tm_sec range from 0-60 instead of 0-59 in time.h?
My time.h has the following definition of tm: struct tm { int tm_sec; /* seconds after the minute [0-60] */ int tm_min; /* minutes after the hour [0-59] */ int tm_hour; /* hours since midnight [0-23] */ ... } I just noticed that they document tm_sec as ranging between 0-60 inclusive. I've al...
Leap seconds are the reason for this: A leap second is a plus or minus one-second adjustment to the Coordinated Universal Time (UTC) time scale that keeps it close to mean solar time. When a positive leap second is added at 23:59:60 UTC, it delays the start of the following UTC day (at 00:00:00 UTC) by one second, eff...
765,913
765,918
Should I worry about "Conditional jump or move depends on uninitialised value(s)"?
If you've used Memcheck (from Valgrind) you'll probably be familiar with this message... Conditional jump or move depends on uninitialized value(s) I've read about this and it simply occurs when you use an uninitialized value. MyClass s; s.DoStuff(); This will work because s is automatically initialized... So if thi...
Can you post a more complete sample? It's hard to see how there would be that particular error with out some form of goto or flow changing statement. I most commonly see this error in code like the following MyClass s1; ... if ( someCondition ) { goto Foo: } MyClass s2; Foo: cout << s2.GetName(); This code is fu...
765,971
766,002
Is memory allocated with new ever automatically freed?
I'm 99% certain the answer to this is a blinding no. Please validate my proposition that the following code will produce a memory leak. Data &getData() { Data *i = new Data(); return *i; } void exampleFunc() { Data d1 = getData(); Data d2; /* d1 is not deallocated because it is on the heap, and d2...
Actually both d1 and d2 will be deallocated, because they are both on the stack. What is not deallocated is the Data object you allocated in your getData() function. You can see this a little more clearly if you flesh out your Data class with instrumentation in the constructors and destructor. For example: class Dat...
766,080
766,100
Why is Valgrind stating that my implementation of std::map<T, T> produces a memory leak?
Valgrind is outputting the following: ==14446== 2,976 (176 direct, 2,800 indirect) bytes in 2 blocks are definitely lost in loss record 23 of 33 ==14446== at 0x4C2506C: operator new(unsigned long) (in /usr/lib64/valgrind/amd64-linux/vgpreload_memcheck.so) ==14446== by 0x41C487: __gnu_cxx::new_allocator<std::_Rb_t...
It's probably because of a pool allocator. From Valgrind FAQ: My program uses the C++ STL and string classes. Valgrind reports 'still reachable' memory leaks involving these classes at the exit of the program, but there should be none. First of all: relax, it's probably not a bug, but a feature. Many imp...
766,126
766,131
Representation of wchar_t and char in WinDbg
Note: /* * Trivial code */ wchar_t *greeting = L"Hello World!"; char *greeting_ = "Hello World!"; WinDbg: 0:000> ?? greeting wchar_t * 0x00415810 "Hello World!" 0:000> ?? greeting_ char * 0x00415800 "Hello World!" 0:000> db 0x00415800 00415800 48 65 6c 6c 6f 20 57 6f-72 6c 64 21 00 00 00 00 Hello World!.... 0041581...
wchar_t is a wide-character string, so each character takes 2 bytes of storage. 'H' as a wchar_t is 0x0048. Since x86 is little-endian, you see the bytes in memory in order 48 00. db in windbg will dump the bytes and provide how its viewed as an ASCII string, hence the H.E.L. ... output you see. You can use 'du' to ...
766,127
766,139
Obtaining current ModelView matrix
In OpenGL, how do I read the current x/y translation in the modelview matrix? I know that you have to load the current matrix into an array and read the floats from there, but I don't know precisely how to do it.
In order to retrieve the current modelview matrix you have to call the glGetFloatv function with GL_MODELVIEW_MATRIX parameter. GLfloat matrix[16]; glGetFloatv (GL_MODELVIEW_MATRIX, matrix); From the documentation: GL_MODELVIEW_MATRIX params returns sixteen values: the modelview matrix on the top of the modelvi...
766,167
766,176
What happens to pixels after passing them into glTexImage2D()?
If for example I create an array of pixels, like so: int *getPixels() { int *pixels = new int[10]; pixels[0] = 1; pixels[1] = 0; pixels[1] = 1; // etc... } glTexImage2D(..., getPixels()); Does glTexImage2D use that reference or copy the pixels into it's own memory? If the answer is the former, the...
From this quote in the man page, it sounds like glTexImage2D allocates its own memory. This would make sense, ideally the OpenGL API would send data to be stored on the graphics card itself (if drivers/implementation/etc permitted). In GL version 1.1 or greater, pixels may be a null pointer. In t...
766,172
766,608
How to make this Matrix class easier to use in the debugger
I've written a C++ matrix template class. It's parameterized by its dimensions and by its datatype: template<int NRows, int NCols, typename T> struct Mat { typedef Mat<NRows, NCols, T> MyType; typedef T value_type; typedef const T *const_iterator; typedef T *iterator; enum { NumRows = NRows }; ...
XCode allows you to create custom data formatters to format the data in the debugger in any way you'd want.
766,303
766,717
Why does Valgrind not like my usage of glutCreateWindow?
I'm using the following code... 169: const char *title = Title.c_str(); 170: glutCreateWindow(title); ... Valgrind gives me the following ... ==28841== Conditional jump or move depends on uninitialised value(s) ==28841== at 0x6FF7A4C: (within /usr/lib64/libGLcore.so.180.44) ==28841== by 0x6FF81F7: (within /usr/l...
Valgrind comes with some default error suppression, but that probably does not cover libCLcore. The error-checking tools detect numerous problems in the base libraries, such as the GNU C library, and the X11 client libraries, which come pre-installed on your GNU/Linux system. You can't easily fix these, but you don't ...
766,477
766,526
Are there equivalents to pread on different platforms?
I am writing a concurrent, persistent message queue in C++, which requires concurrent read access to a file without using memory mapped io. Short story is that several threads will need to read from different offsets of the file. Originally I had a file object that had typical read/write methods, and threads would acqu...
On Windows, the ReadFile() function can do it, see the lpOverlapped parameter and this info on async IO.
766,605
766,633
Can you embed for loops (in each other) in C++
I am working on a merge sort function. I got the sort down - I am trying to get my merge part finished. Assume that I am learning C++, have cursory knowledge of pointers, and don't understand all the rules of std::vector::iterator's (or std::vector's, for that matter). Assume that num is the size of the original std::...
It's valid... but a for loop probably isn't what you want. When you use two for loops, your inner loop keeps going back to the start every time the outer loop loops. So if your vectors contain: farray: 10 9 8 4 3 sarray: 7 6 4 3 1 Then your final array will contain something like: 10 10 10 10 10 9 9 9 9 9 8 8 8 8 8 7 ...
766,816
766,819
Why does this compile in C but not C++ (sigaction)?
I get the following errors when trying to compile the below code using g++. When I compile it using gcc it works fine (other than a few warnings). Any help appreciated. g++ ush7.cpp ush7.cpp: In function ‘int signalsetup(sigaction*, sigset_t*, void (*)(int))’: ush7.cpp:93: error: expected unqualified-id before ‘catch...
catch is a keyword in C++ but not in C. Please see my related answer C is not a proper subset of C++ here, or even better here.
767,009
767,060
Wrapping up a C++ API in Java or .NET
Has anyone successfully "wrapped up" a C++ API in Java or .NET? I have an application that provides a C++ API for writing plug-ins. What I'd like to do is access that API from .NET or Java. Would I need to use COM, or are there simpler/better alternatives?
If you have a very straight forward method signatures (i.e. methods that takes and returns primitive types such as int, char[], void* ... etc), it is reasonably easy to do so in .NET and still possible but a bit harder in Java with JNI. However, if your class methods uses modern C++ programming techniques such as boost...
767,099
767,174
Is it good form to compare against changing values in a loop in C++?
No doubt some of you have seen my recent posting, all regarding the same program. I keep running into problems with it. To reiterate: still learning, not very advanced, don't understand pointers very well, not taking a class, don't understand OOP concepts at all, etc. This code just merges two sorted vectors, farray an...
1 . It's fine to compare iterators which are from the same container as a for loop condition, but this only makes sense if you are moving one or other iterators in either the increment part if the for loop statement or in the body of the for loop itself. In this for loop you compare iter against sarray.end() but the fo...
767,477
767,630
template specialization for static member functions; howto?
I am trying to implement a template function with handles void differently using template specialization. The following code gives me an "Explicit specialization in non-namespace scope" in gcc: template <typename T> static T safeGuiCall(boost::function<T ()> _f) { if (_f.empty()) throw GuiException("Functio...
When you specialize a templated method, you must do so outside of the class brackets: template <typename X> struct Test {}; // to simulate type dependency struct X // class declaration: only generic { template <typename T> static void f( Test<T> ); }; // template definition: template <typename T> void X::f( Tes...
767,579
767,709
Exporting classes containing `std::` objects (vector, map etc.) from a DLL
I'm trying to export classes from a DLL that contain objects such as std::vectors and std::strings - the whole class is declared as DLL export through: class DLL_EXPORT FontManager { The problem is that for members of the complex types I get this warning: warning C4251: 'FontManager::m__fonts' : class 'std::map<_Kty,...
When you touch a member in your class from the client, you need to provide a DLL-interface. A DLL-interface means, that the compiler creates the function in the DLL itself and makes it importable. Because the compiler doesn't know which methods are used by the clients of a DLL_EXPORTED class it must enforce that all me...
767,644
767,688
How would I write a Photoshop plugin for an image format?
I have an image format and Photoshop doesn't support it. I've been tasked with writing a plugin to import or open the format, but there seems to be little information out there and what information I can find is all about writing filters. However, I want to import/export/open, not filter it.
My experience with photoshop import filters is roughly six years old, so take this comment with a grain of (old) salt. I just took the import filter example code from the official SDK as a boilerplate and added my own decoding function. It was a straight forward job and took a week from start to finish. If I remember ...
767,770
768,199
Explorer thumbnails (winXP)
I have a file format I need to be able to show in explorer thumbnails. Since the target system is windows XP, the Vista PreviewHandler API will not be suitable. Ill be using c++. How would I do it?
You'll need to register a shell extension for your file type. The extension contains code that extracts/generates the thumbnail by implementing the IExtractImage interface. See: IExtractImage Interface on MSDN
767,995
768,012
using std::find_if with std::string
I'm being stupid here but I can't get the function signature for the predicate going to find_if when iterating over a string: bool func( char ); std::string str; std::find_if( str.begin(), str.end(), func ) ) In this instance google has not been my friend :( Is anyone here?
#include <iostream> #include <string> #include <algorithm> bool func( char c ) { return c == 'x'; } int main() { std::string str ="abcxyz";; std::string::iterator it = std::find_if( str.begin(), str.end(), func ); if ( it != str.end() ) { std::cout << "found\n"; } else { std::c...
768,182
768,195
C/C++: How to convert 6bit ASCII to 7bit ASCII
I have a set of 6 bits that represent a 7bit ASCII character. How can I get the correct 7bit ASCII code out of the 6 bits I have? Just append a zero and do an bitwise OR? Thanks for your help. Lennart
ASCII is inherently a 7-bit character set, so what you have is not "6-bit ASCII". What characters make up your character set? The simplest decoding approach is probably something like: char From6Bit( char c6 ) { // array of all 64 characters that appear in your 6-bit set static SixBitSet[] = { 'A', 'B', ... }; ...
768,351
770,662
Complete example using Boost::Signals for C++ Eventing
I’m aware of the tutorial at boost.org addressing this: Boost.org Signals Tutorial, but the examples are not complete and somewhat over simplified. The examples there don’t show the include files and some sections of the code are a little vague. Here is what I need: ClassA raises multiple events/signals ClassB subscr...
The code below is a minimal working example of what you requested. ClassA emits two signals; SigA sends (and accepts) no parameters, SigB sends an int. ClassB has two functions which will output to cout when each function is called. In the example there is one instance of ClassA (a) and two of ClassB (b and b2). ma...
768,585
768,605
Why does my Visual Studio Win32 project require .NET 3.5 SP1 to install?
Using Visual Studio 2008, I created a C++ Win32 project. To release the program, I made a Visual Studio setup project within the same solution. The setup.exe prompts my users to install .NET 3.5 SP1, which is often a 15+ minute install and only allowed to administrator level accounts. If they do not there is an error a...
In VS 2008 the default target framework is .NET 3.5. For C++ on the Common Properties page there's a "Targeted Framework" drop down, but on the test project I created it's greyed out, so it looks like this can't be changed after the project has been created. I created a second C++ project and selected the 2.0 Template ...
768,588
768,620
Is the const value parameter in definition but not declaration really C++?
This is similar to (but different from) this question. Here is some simple test code to illustrate some weirdness I have discovered with Sun CC: //---------------main.cpp #include "wtc.hpp" int main(int, char**) { testy t; t.lame(99); return 0; } //--------------wtc.hpp #ifndef WTC_HPP_INCLUDED #define WTC_HPP_I...
This looks like a compiler problem in CC. The C++ standard says (in 13.1 Overloadable declarations): Parameter declarations that differ only in the presence or absence of const and/or volatile are equivalent. That is, the const and volatile type-specifiers for each parameter type are ignored when d...
768,844
899,624
non-unicode WM_CHAR in unicode windows
I have written a DLL which exports a function that creates a window using RegisterClassExW and CreateWindowExW. Every message is retrieved via GetMessageW(&msg, wnd_handle, 0, 0); TranslateMessage(&msg); DispatchMessageW(&msg); Also there is a program which loads the DLL and calls the function. Despite the Unicode w...
the problem was in the message retrieval process. I used GetMessage() with the handle of my window instead of just 0, GetMessageW(&msg, wnd_handle, 0, 0) instead of GetMessageW(&msg, 0, 0, 0). In this way, the WM_INPUTLANGCHANGEREQUEST messages were swallowed and the locale remained English.
768,853
768,869
TinyXML: how to parse a file pointer
I'm trying to connect the output of popen, a file pointer, to the input of TinyXML. According to the main page, the best way to do it is using the parse method: C style input: * based on FILE* * the Parse() and LoadFile() methods I believe I need to use the TIXML_USE_STL to get to this. How do I go about find...
I'm not hugely familiar with TinyXML, but does LoadFile() not work in its overloaded version which takes a FILE *? http://www.grinninglizard.com/tinyxmldocs/classTiXmlDocument.html#a12 EDIT: Ah, the problem is that TinyXML doesn't support reading from a stream (see the link above). Your only choice then is to read the ...
768,982
769,087
How to properly use structs inside a class?
Using: VS2008, Win32, C/C++ I'm trying to encapsulate my entire dialog window into a class for reusability. Sort of like a custom control. In doing this, I am moving my seperate functions into a class. The following struct design though is giving me problems, with Visual Studio outputting: error C2334 '{'. It's a si...
You cannot specify initialisers for non-static members that way -- you would normally need to declare the array and then populate it inside the constructor... Except that, in fact there is no way to initialise const member arrays in C++ (see this thread). If you are prepared to share MainMessages amongst all instances...
769,026
769,056
stl algorithm in class
Is there a way to use stl algorithms like find() and find_if() in a container of objects? Ex.:With find() find the element whit name "abc" in a vector of class Alfhabetic.
You can define a comparing predicate (functor). Here is a generic implementation: struct AlphabeticNameComp { AlphabeticNameComp( const std::string& toCompare) : toCompare_( toCompare) { } bool operator()( const Alphabetic& obj) const { return toCompare_ == obj.name(); } private: const std...
769,097
769,161
Choosing a STL container with uniqueness and which keeps insertion ordering
I am unable to decide which STL container to use in the following case: I want to preserve the order of insertion of the elements The elements in the container have to be unique. Is there any readymade container available for this? I don't want to use a vector and then perform a std::find before doing a push_back ev...
Boost MultiIndex should be able to do exactly what you want - you can just use one sequenced index to get the "ordered by insertion order" requirement, and either a hashed_unique or ordered_unique index to get the uniqueness requirement.
769,537
770,837
Hook LoadLibrary call from managed code
We would like to hook calls to LoadLibrary in order to download assemblies that are not found. We have a handler for ResolveAssembly that handles the managed assemblies, but we also need to handle unmanaged assemblies. We have attempted to hook LoadLibrary calls by re-writing the imports table via techniques specifie...
I have successfully hooked from Managed code. However, I did it by injecting an unmanaged DLL into the remote process and have it rewrite the import table in DllMain. You may want to consider this method. Here is my hooking function: //structure of a function to hook struct HookedFunction { public: LPTSTR moduleNam...
769,867
769,921
How to use BOOST_FOREACH with two std::maps?
I have code that looks essentially like this: std::map<int, int> map1, map2; BOOST_FOREACH(int i, map1) { // do steps 1-5 here... } BOOST_FOREACH(int i, map2) { // do steps 1-5 (identical to above) here... } Is there any way to concatenate the maps to eliminate the duplicate code in the second loop? Or a way t...
You could define a function: typedef std::map<int, int> IntMap; void doStuffWithInt(IntMap::value_type &i) { // steps 1 to 5 } BOOST_FOREACH(IntMap::value_type &i, map1) doStuffWithInt(i); BOOST_FOREACH(IntMap::value_type &i, map2) doStuffWithInt(i); Although in that case it might be even simpler to use std::f...
770,344
770,374
Visual C++ - Linking plugin DLL against EXE?
I'm in the process of porting a large C++ application from Linux (gcc) to Windows (Visual C++ 2008) and am having linker issues with plugins. On Linux this wasn't an issue, as .so supports runtime symbol lookup, but dll does not seem to support this. Some background information: The application (the host), which hosts ...
What do you mean by "runtime symbol lookup"? Do you mean dynamically loading libraries using dlopen and dlsym and so on? The equivalents in Windows are called LoadLibrary and GetProcAddress. In windows, you don't export symbols from a executable. You should only export them from a dll. The right way to solve your probl...
770,577
771,391
Is the ANTLR parser generator best for a C++ app with constrained memory?
I'm looking for a good parser generator that I can use to read a custom text-file format in our large commercial app. Currently this particular file format is read with a handmade recursive parser but the format has grown and complexified to the point where that approach has become unmanageable. It seems like the ultim...
ANTLR 3 doesn't support C++; it claims to generate straight C but the docs on getting it to actually work are sort of confusing. It does generate C, and furthermore, it works with Visual Studio and C++. I know this because I've done it before and submitted a patch to get it to work with stdcall. Memory is at a...
770,728
770,855
mouse over transparency in Qt
I am trying to create an app in Qt/C++ with Qt4.5 and want the any active windows to change opacity on a mouseover event... As i understand it, there is no explicit mouseover event in Qt. However, I got rudimentary functioning by reimplementing QWidget's mousemoveevent() in the class that declares my mainwindow. But th...
Installing event filters for each of your child widgets might do the trick. This will allow your main window to receive child events such as the ones from you group boxes. You can find example code here.
770,994
771,544
Is there a way to call the STL Libraries of C++ from Java using JNI?
Is there a way to call STL libraries from JNI, I believe JNI provides a C like interface for native calls, how do we achieve this for the C++ template libraries?
I agree that if you're looking for just the plain STL, you could probably use a Java library instead. However, if you insist on wrapping STL, SWIG provides some STL wrapping in JNI out of the box (see this for the basic mechanism), which should produce relatively stable, tested code.
771,008
771,018
'for' loop vs Qt's 'foreach' in C++
Which is better (or faster), a C++ for loop or the foreach operator provided by Qt? For example, the following condition QList<QString> listofstrings; Which is better? foreach(QString str, listofstrings) { //code } or int count = listofstrings.count(); QString str = QString(); for(int i=0;i<count;i++) { str =...
It really doesn't matter in most cases. The large number of questions on StackOverflow regarding whether this method or that method is faster, belie the fact that, in the vast majority of cases, code spends most of its time sitting around waiting for users to do something. If you are really concerned, profile it for yo...
771,012
771,065
Baffling Inline Behaviour from Random Number Generator Wrapper (C++)
I have a simple wrapper for an Mersenne twister random number generator. The purpose is to scale the number returned by the generator (between 0 and 1) to between argument defined limits (begin and end). So my function is inline float xlRandomFloat(float begin, float end) {return (begin+((end-begin)*genrand_real2()))...
Okay, several things at work here. First, on the debugging, you describe what I'd think of as the more or less expected behavior, because when you inline a function, there's no generated code to go with the fromt matter of the function. So, the first statement there is ret=(((end-begin)*genrand_real2())); and the fir...
771,453
771,463
Copy map values to vector in STL
Working my way through Effective STL at the moment. Item 5 suggests that it's usually preferable to use range member functions to their single element counterparts. I currently wish to copy all the values in a map (i.e. - I don't need the keys) to a vector. What is the cleanest way to do this?
You can't easily use a range here because the iterator you get from a map refers to a std::pair, where the iterators you would use to insert into a vector refers to an object of the type stored in the vector, which is (if you are discarding the key) not a pair. I really don't think it gets much cleaner than the obvious...
771,458
771,554
Improvements for this C++ stack allocator?
Any suggestions for my stack based allocator? (Except for suggestions to use a class with private/public members) struct Heap { void* heap_start; void* heap_end; size_t max_end; Heap(size_t size) { heap_start = malloc(size); heap_end = heap_start; max_end = size + (size_t) h...
You've implemented a stack based allocator. You can't free up without leaving gaps. Usually a pool refers to a block of contiguous memory with fixed sized slots, which are doubly linked to allow constant time add and delete. Here's one you can use as a guide. It's along the same lines as yours but includes basic iterat...
771,492
771,508
C++ Style Convention: Parameter Names within Class Declaration
I'm a fairly new C++ programmer and I would like to hear the arguments for and against naming parameters within the class declaration. Here's an example: Student.h #ifndef STUDENT_H_ #define STUDENT_H_ #include <string> using namespace std; class Student { private: string name; unsigned int age;...
It is much better to use the parameter names in the declaration, and use good parameter names. This way, they serve as function documentation. Otherwise, you will have to write additional comments in your header, and it is always better to use good parameter/variable names than to use comments. Exception: when a func...
771,867
772,005
How to make a cross-platform c++ inline assembly language?
I hacked a following code: unsigned long long get_cc_time () volatile { uint64 ret; __asm__ __volatile__("rdtsc" : "=A" (ret) : :); return ret; } It works on g++ but not on Visual Studio. How can I port it ? What are the right macros to detect VS / g++ ?
#if defined(_MSC_VER) // visual c #elif defined(__GCCE__) // gcce #else // unknown #endif My inline assembler skills are rusty, but it works like: __asm { // some assembler code } But to just use rdtsc you can just use intrinsics: unsigned __int64 counter; counter = __rdtsc(); http://msdn.microsoft.com/en-us/librar...
771,868
771,888
Problem compiling Platform SDK program
I'm trying to compile the example from here; http://msdn.microsoft.com/en-us/library/ms682619(VS.85).aspx I've installed the Platform SDK, but I'm getting these errors; Error 1 error LNK2019: unresolved external symbol _GetDeviceDriverBaseNameW@12 referenced in function _main DriverChecker.obj DriverChecker Error...
You just need to add psapi.lib as an additional library in your linker options. Edit properties for your project, navigate to Linker->Input, and type "psapi.lib" where it says Additional Dependencies.
771,944
771,955
How to measure user time used by process on windows?
On linux we can use "time" command. Or from C++: #include <sys/time.h> #include <sys/resource.h> int getrusage(int who, struct rusage *usage); How to do a closest thing to that on windows ?
GetProcessTimes This gives lpUserTime [out] : A pointer to a FILETIME structure that receives the amount of time that the process has executed in user mode. The time that each of the threads of the process has executed in user mode is determined, and then all of those times are summed together to obtain this value.
772,089
1,083,465
One executable that starts as a GUI application or console application based on command line in Visual Studio 2005
I have a Qt application in Visual Studio 2005 which is linked using \subsystem:windows such that when I run the compiled executable it does not create a command line terminal, as well. I would like to create a command-line mode: when I start it with the --nogui command line argument, then the GUI is not presented, but ...
I think the preferred technique for the situation here is the ".com" and ".exe" method. In Windows from the command line, if you run a program and don't specify an extension, the order of precedence in locating the executable will .com preferred over a .exe file. Then you can use tricks to have that ".com" be a proxy f...
772,146
772,224
c++ delete object referenced by two pointers
I am just curious if there is an elegant way to solve following problem in c++: I have a simulator app which contains several components connected by channels. The channels may be either network channels (two instances of the app are needed) or dummy local channel. There are two interfaces: IChannelIn and IChannelOut a...
How does your class know that this is a freestore pointer? E.g. what speaks against the following code? DummyChannel d; in = &d; out = &d; This is an entirely sensible piece of code but your destructor will crash when trying to delete either of the pointers. Long story short: reclaiming resources is the job of whoever...
772,192
3,670,232
tr1::hash for boost::thread::id?
I started to use the unordered_set class from the tr1 namespace to speed-up access against the plain (tree-based) STL map. However, I wanted to store references to threads ID in boost (boost::thread::id), and realized that the API of those identifiers is so opaque that you cannot clearly obtain a hash of it. Surprising...
The overhead of stringifying thread::id (only to compute the string hash afterward) is, as you almost said yourself, astronomical compared to any performance benefits a tr1::unordered_map might confer vis-a-vis std::map. So the short answer would be: stick with std::map< thread::id, ... > If you absolutely must use un...
772,655
772,697
Counting instances of individual derived classes
I'd like to be able to count instances of classes that belong in the same class hierarchy. For example, let's say I have this: class A; class B: public A; class C: public B; and then I have this code A* tempA = new A; B* tempB = new B; C* tempC = new C; C* tempC2 = new C; printf(tempA->GetInstancesCount()); printf(te...
There is a problem with proposed solutions: when you create B you A constructor will be called automatically and thus increment count of A. class A { public: A(bool doCount = true) { if (doCount) ++instanceCount_; } static std::size_t GetInstanceCount() { return instanc...
772,709
772,719
What's the proper "C++ way" to do global variables?
I have a main application class, which contains a logger, plus some general app configurations, etc. Now I will display a lot of GUI windows and so on (that will use the logger and configs), and I don't want to pass the logger and configurations to every single constructor. I have seen some variants, like declaring t...
Use the singleton design pattern. Basically you return a static instance of an object and use that for all of your work. Please see this link about how to use a singleton and also this stackoverflow link about when you should not use it Warning: The singleton pattern involves promoting global state. Global state is b...
773,414
773,424
Structure to hold value by ranged key
I need a structure to hold a value based on a key that has a range. My implementation is C++, so any STL or Boost would be excellent. I have as range-key, which are doubles, and value [0,2) -> value1 [2,5) -> value2 [5,10) -> value3 etc Such that a search of 1.23 should return value1, and so on. Right now I am using ...
If your ranges are contiguous and non-overlapping, you should use std::map and the upper_bound member function. Or, you could use a sorted vector with the upper_bound algorithm. Either way, you only need to record the lowest value of the range, with the upper part of the range being defined by the next higher value. Ed...
773,486
773,550
C hard coding an array of typedef struct
This is such a dumb question it's frustrating even asking it. Please, bear with me, I'm feeling particularly dumb over this one today.... I've got a library with a certain typedef struct. basically: typedef struct {int x; int y;} coords; What I really wanted to do was declare in my header a variable array of this: ...
Well, what you created is not a variable array. It's an array whose size is not known. That array has an incomplete type, and can thus not be defined in C++. What you can do is to make it just a declaration by putting extern before it. extern coords MyCoords[]; Then, in the .cpp file that initializes it, you can then...
773,525
773,549
std::map iterator not iterating in MFC app
I have a std::map declared thusly in a legacy MFC application: typedef std::map<long, CNutrientInfo> NUTRIENT_INFO_MAP; typedef NUTRIENT_INFO_MAP::const_iterator NUTRIENT_INFO_ITER; typedef NUTRIENT_INFO_MAP::value_type NUTRIENT_INFO_PAIR; static NUTRIENT_INFO_MAP m_NutrientInfoMap; m_NutrientInfoMap is populated when...
Is your example actually pasted from the source? Maybe it looks more like: while (iter != m_NutrientInfoMap.end()); // <== note the semi-colon { m = (*iter).second; if (_stricmp(m.GetFullName().c_str(), name.c_str()) == 0) { return m; } iter++; }
773,599
773,604
Return class pointer from a function
I am not sure what is wrong with this (keep in mind I'm kinda sorta new to C++) I have this class: Foo { string name; public: SetName(string); } string Foo::SetName(string name) { this->name = name; return this->name; }; ////////////////////////////////////////////// //This is where I am trying to return ...
You need to use the new keyword instead to create new Foo on the heap. The object on the stack will be freed when the function ends, so you are returning a pointer to an invalid place in memory. Here is the correct code. Foo * ReturnFooPointer() { Foo * foo_ptr = new Foo(); return foo_ptr; } Remember later to del...
773,667
871,802
element-wise operations with boost c++ ublas matrix and vector types
i'd like to perform element-wise functions on boost matrix and vector types, e.g. take the logarithm of each element, exponentiate each element, apply special functions, such as gamma and digamma, etc. (similar to matlab's treatment of these functions applied to matrices and vectors.) i suppose writing a helper functio...
WARNING The following answer is incorrect. See Edit at the bottom. I've left the original answer as is to give context and credit to those who pointed out the error. I'm not particularly familiar with the boost libraries, so there may be a more standard way to do this, but I think you can do what you want with iterato...
773,935
774,010
Handle Tab key in GLUT
I use OpenGL+GLUT for simple application, but I can't handle a "Tab" key press. Does anybody knows how to handle pressing of Tab key ? thanx P.S.:Mac OS 10.5.6, GCC 4.0 Solution void processNormalKeys(unsigned char key, int x, int y){ if ((int)key == 9) { //tab pressed .... } .... } .... int m...
I believe hitting tab triggers the normal keyboard callback with a key value of 9 (ASCII for tab).
774,047
774,256
How can I change Windows shell (cmd.exe) environment variables from C++?
I would like to write a program that sets an environment variable in an instance of the shell (cmd.exe) it was called from. The idea is that I could store some state in this variable and then use it again on a subsequent call. I know there are commands like SetEnvironmentVariable, but my understanding is that those ...
A common techniques is the write an env file, that is then "call"ed from the script. del env.var foo.exe ## writes to env.var call env.var
774,233
774,320
MS Extensions To STL
If this is a "Google Is Your Friend" question, I apologize in advance. I've searched but perhaps I've been using the wrong terms for searching. Can anyone point me to any sort of introductory document on the STL extensions which MS provided with Visual Studio 2003? I believe the libraries were licensed from Dinkumwar...
One thing Microsoft has done starting with VS 2003 it to put non-standard C++ extensions in the stdext namespace: http://msdn.microsoft.com/en-us/library/ek139e86(VS.71).aspx So doing a search on stdext (either on the headers or on MSDN) will help you. Note that while the above link talks only about <hash_set> and <h...
774,293
774,317
How to create an iterator over elements that match a derived type in C++?
I'd like an iterator in C++ that can only iterate over elements of a specific type. In the following example, I want to iterate only on elements that are SubType instances. vector<Type*> the_vector; the_vector.push_back(new Type(1)); the_vector.push_back(new SubType(2)); //SubType derives from Type the_vector.push_ba...
You must use a dynamic cast. the_iterator = the_vector.begin(); while( the_iterator != the_vector.end() ) { SubType* item = dynamic_cast<SubType*>(*the_iterator); if( item != 0 ) ... //only SubType(2) and SubType(4) should be in this loop. ++the_iterator; }
774,464
774,484
Undefined reference? Is there something I'm not seeing? (c++, singleton class)
I can't seem to make this undefined reference go away. I have this code under the private section of Scene.h: static Scene * scene_; There is a #include "Scene.h" at the very first part of the header of Scene.cpp This is the only error I'm receiving at the moment, any ideas? I'll supply any other info you want.
When you declare a static member you must also define it in one compilation unit (and only one): // a.h class A { static int x; }; // a.cpp int A::x = 0; The declaration of the variable in the class will not reserve memory, just tell the compiler (from other compilation units) that there will be a variable accessi...
774,474
774,530
How to hide MFC splash screen in auto start?
I have a MFC app without main window. When users start it, it displays the splash screen for 1~2 seconds, then splash screen fades out to system tray. Users start to access the menu by clicking the icon in the tray. The app can also auto start when users login to Windows (adding entry in Start Up folder). The same pro...
A simple way would be to set a shortcut to the application in the Startup folder that specifies a parameter on the command line, e.g. if your application is called myapp.exe in the shortcut properties you could type <path to myapp>\myapp.exe -nosplash. Then modify your application code to check the command line parame...
774,717
774,755
C++ Object Graph to C#
Is there a tool that will take a series of C++ headers and generate a XSD and a class that will serialize the C++ to XML? Or really what we are looking for is the simplest way to migrate data from C++ to C#? We have a library in C++ that we would like to write a GUI for in C#. Using Managed wrapper classes it seems l...
This would be a good starting point for serializing the C++ stuff. http://www.boost.org/doc/libs/1_38_0/libs/serialization/doc/index.html
774,802
794,763
Is there a gcc 4.2 warning similar to Visual Studio's regarding possible loss of data?
Is there a flag for gcc such that conversions from a long to a short will generate a warning about a possible loss of data? I'm working on a C++ application that is compiled for both Visual Studio (2005) and GCC 4.2 (for Mac OS X). The warnings that Visual Studio prints out follow this pattern: : warning C4244: 'argume...
This feature is not supported in GCC 4.2, but it has been added in GCC 4.3. Wiki page explaining it. Thanks to schnaader and Evan Teran for providing the links that led me there.
775,082
775,098
Best commercial C++ IDE?
I have tried C++ Builder 2009 and Visual Studio 2008. VCL seems much more friendlier than MFC. Are there alternates which are superior than these two? PS: Please do not suggest freebies or open source IDEs. I really am interested in commercial IDE's only.
I suppose mentioning VCL and MFC means you are referring to Windows IDEs only. With that said, I think VS2008 pretty much has the crown no contest. Its debugger is one of the best you can get and it's perfectly integrated into the IDE. Don't get me wrong, C++ builder is still a great piece of software, but I feel Borla...
775,144
775,179
C++ Segregated Free Lists
I need to use segregated free lists for a homework assignment and I was wondering if the STL or some other library had these already written so I don't have to reinvent the wheel?
I don't think STL has anything, but it looks like the Boost library might have it, http://www.boost.org/doc/libs/1_38_0/libs/pool/doc/interfaces/simple_segregated_storage.html
775,217
775,227
What is a good way to load textures dynamically in OpenGL?
Currently I am loading an image in to memory on a 2nd thread, and then during the display loop (if there is a texture load required), load the texture. I discovered that I could not load the texture on the 2nd thread because OpenGL didn't like that; perhaps this is possible but I did something wrong - so please correct...
You can load a texture from disk to memory on any thread you like, using any tool you wish for reading the files. However, when you bind it to OpenGL, it's going to need to be handled on the same thread as the rendering for that OpenGL context. That being said, this discussion suggests that using a PBO in a second thr...
775,325
775,343
Function for manipulating container of Base/Derived objects
consider the following algorithm with arrays: class MyType; { // some stuff } class MySubType:MyType { // some stuff } void foo(MyType** arr, int len) { for (int i = 0;i<len;i++) // do something on arr[i]-> } void bar() { MySubType* arr[10]; // initialize all MySubType*'s in arr foo(&...
This might fix your problem template <typename T> void foo(std::vector<T>& s) { typename std::vector<T>::iterator i; for (i = s.begin(); i != s.end(); i++) // do stuff on *i }
775,349
787,671
Webcam driver settings?
I'm working on a C++ application that uses OpenCV/ffmpeg to capture video frames from my built-in webcam (Studio XPS 13). This application is really sensitive to those auto light adjustments that the webcam driver does.... is there any way I can change this behavior? Either via some webcam driver settings app, or in co...
Well, I'm not sure what the most general way to do this is, but I know that the module for my webcam (ov511) has options to tweak all these settings... try running modinfo for the kernel module.
775,357
775,379
MPI Genetic Monte Carlo Algorithm Resources?
I have been working with some friends to convert a Matlab Genetic Algorithm to C++ and it works in a sequential order currently. Matlab is no longer a portion of our current code. We are looking to use it on a cluster, but have been a little dry on resources. We have a cluster available at the University and it is eq...
If you're doing matrix computations, then whether there's even a good way to partition the calculations is highly dependent upon the calculation itself. I'd highly recommend the Golub and van Loan book, "Matrix Computations, 3rd Ed.". In it there is an entire chapter devoted to parallel computations (Ch. 6). OpenMPI i...
775,367
775,371
Will this be out of scope and not function properly?
I'm declaring a struct inside my code and then trying to insert it into a data structure that I have written. However, I'm concerned that since I declare the struct inside the function, once the function ends, the data structure will be pointing to garbage. Can anyone help with this? Here's the code: void Class::funct...
It will be out of scope after function returns, yes. That is not valid. You want to allocate it on the heap. Edit: Unless you copy the memory you point to in insert, of course.
775,481
775,500
Keeping address in C++ hacking game code?
I have this code that edits addresses in a game to get unlimited ammo and what not, and I found out that the addresses are different for every computer, sometimes every time you restart the game, so how would I manage making this work still even though they change.
If you get the address you're looking for, and then search for that address in memory to find the address of the pointer to that data, and then search for that address in memory so you can find the address of the pointer to it, and so on, you may eventually find an address that does not change. Then, at runtime, you ca...
775,700
779,424
Why aren't Shell_NotifyIcon balloon tips working?
According to everything I've seen, the following C++ program should be displaying a balloon tool tip from the tray icon when I left-click in the application window, yet it's not working. Can anyone tell me what I'm missing? This is on XP with version 6.0 of Shell32.dll (verified with DllGetVersion). Thanks! #inclu...
Bah, I figured it out. For some reason with the headers I have... sizeof(NOTIFYICONDATA) == 508 whereas... NOTIFYICONDATA_V3_SIZE == 504 NOTIFYICONDATA_V2_SIZE == 488 NOTIFYICONDATA_V1_SIZE == 88 If I specify either V2 or V3 instead of sizeof(NOTIFYICONDATA) the balloon tips show up just fine.
775,774
776,008
Conditionally disable warnings with qmake/gcc?
I am involved with a software project written in Qt and built with qmake and gcc on Linux. We have to link to a third-party library that is of fairly low quality and spews tons of warnings. I would like to use -W -Wall on our source code, but pass -w to the nasty third-party library to keep the console free of noise ...
Jonathan, I think the problem is where your source files are including header files from 3rd party libraries, and you want to switch off the warnings for the latter. Kevin, i think you can use pragmas to control warnings : gcc diagnostic pragmas You could add these before and after any #includes for 3rd party libs.
775,790
775,804
From Visual Studio C++ 6.0 to VS 2008?
I work in a company doing C++ development on VC6, and we're considering a move to VS 2008. What are the benefits of upgrading? What are the cons? Any guides/steps on migrating project files, or gotchas I should be aware of? Are people ok with moving to the different development interface?
For me, the biggest reason to upgrade to 2008 is the level of standards compliance in the C++ compiler. It is vastly improved from VC6 and is capable of using most libraries that you are familiar with or want to use. Including STL, BOOST and TR1. The downsides are the normal issues with upgrading. For example, impro...
775,902
776,148
Zeroing out a struct in the constructor
A wide range of structures is used in Win32 programming. Many times only some of their fields are used and all the other fields are set to zero. For example: STARTUPINFO startupInfo; // has more than 10 member variables ZeroMemory( &startupInfo, sizeof( startupInfo ) ); //zero out startupInfo.cb = sizeof( startupInfo )...
I think this is a fine way to make such structures more bulletproof. I'm not sure why others seem to not like the technique. I use it occasionally, but not as often as I otherwise might because it doesn't seem to be very well liked by coworkers for some reason. I don't see it used in published material very often - the...
776,004
776,086
Manipulating with pointers to derived class objects through pointers to base class objects
I have this code to represent bank: class Bank { friend class InvestmentMethod; std::vector<BaseBankAccount*> accounts; public: //... BaseBankAccount is an abstract class for all accounts in a bank: class BaseBankAccount { public: BaseBankAccount() {} virtual int getInterest() const = 0; ...
A solution to accessing more derived class features from a base class is the visitor pattern. class BaseBankAccount { public: ... virtual void AcceptVisitor(IVisitor& v) = 0; }; class AccountTypeA : public BaseBankAccount { public: void TypeAFeature() {...} void AcceptVisitor(IVisitor& v) { v...
776,042
776,092
How to detect cycles when using shared_ptr
shared_ptr is a reference counting smart pointer in the Boost library. The problem with reference counting is that it cannot dispose of cycles. I am wondering how one would go about solving this in C++. Please no suggestions like: "don't make cycles", or "use weak_ptr". Edit I don't like suggestions that say to just us...
I haven't found a much better method than drawing large UML graphs and looking out for cycles. To debug, I use an instance counter going to the registry, like this: template <DWORD id> class CDbgInstCount { public: #ifdef _DEBUG CDbgInstCount() { reghelper.Add(id, 1); } CDbgInstCount(CDbgInstCount const &) { ...
776,182
776,226
C++ : variable template parameters (for genetic algorithm)
I'm writing a parallel evolutionary algorithm library using C++, MPI and CUDA. I need to extract the raw data from my object oriented design and stick it into a flat array (or std::vector using stl-mpi) for it to be sent across to nodes or the cuda device. The complete design is quite complex with a lot of inheritance...
As far as dynamic typing is concerned, boost::variant is a pretty powerful tool. But your problem seems to be fairly simple, so i'd recommend doing something like this : template<typename DataPiece> class Genome { typedef std::vector<DataPiece> Data; Data data; } template <class T_Genome> class Population { ...
776,303
776,320
In C++ how can I use a template function as the 3rd parameter in std::for_each?
I am trying to use std::for_each to output the contents of vectors, which may contain different types. So I wrote a generic output function like so: template<typename T> void output(const T& val) { cout << val << endl; } which I would like to use with: std::for_each(vec_out.begin(), vec_out.end(), output); but th...
Try: std::for_each(vec_out.begin(), vec_out.end(), output<T>); where vec_out is a container (vector) of type T. Note: The for_each algorithm expects an unary functor for its last argument. See the link for an example using functors.
776,304
1,133,119
TAB control background in ATL App, XP styles
I have an ATL application with a dialog containing a TAB control. The App uses a common controls manifest. Under XP with visual styles, the tab control background is a different color than the dialog and the controls (mostly checkboxes), so it looks quite ugly. Screenshot How can I fix that?
Here you could find answer to your question.
776,354
776,369
Test if a font is installed (Win32)
How can I test if a font is installed? Ultimately, I want to implement a HTML-like font selection, i.e. when specifying e.g. "Verdana,Arial", it should pick the first font that is installed. This Question provides an answer for .NET - it seems the recommended way is to create the font, and then cmpare the font face act...
You can use EnumFontFamiliesEx to enumerate the list of Fonts on the system, or if you pass a font name you can enumerate the fonts for that family.
776,510
776,890
Soundex Algorithm implementation using C++
Put simply a Soundex Algorithm changes a series of characters into a code. Characters that produce the same Soundex code are said to sound the same. The code is 4 characters wide The first character of the code is always the first character of the word Each character in the alphabet belongs in a particular group (at ...
Instead of scode[codeCount] = 1; you should write scode[codeCount] = '1'; as you are forming a char array, the former is actually the first ascii character while the latter is the character '1'.
776,624
776,677
What's faster, iterating an STL vector with vector::iterator or with at()?
In terms of performance, what would work faster? Is there a difference? Is it platform dependent? //1. Using vector<string>::iterator: vector<string> vs = GetVector(); for(vector<string>::iterator it = vs.begin(); it != vs.end(); ++it) { *it = "Am I faster?"; } //2. Using size_t index: for(size_t i = 0; i < vs.si...
Why not write a test and find out? Edit: My bad - I thought I was timing the optimised version but wasn't. On my machine, compiled with g++ -O2, the iterator version is slightly slower than the operator[] version, but probably not significantly so. #include <vector> #include <iostream> #include <ctime> using namespac...
776,960
777,049
What's the best way to implement a operator overload?
Among all things I've learned in C++ (which isn't so much), operator overloading seems the most difficult. In general terms, when is it best to write an operator overload as a friend function? When do I have to explicilty use *this? Is always bad to use a temporary object?
Neil's answer is correct. In addition, this link provides a lot of good information about when, where, why, and how to use the various types of operator overloading in C++. In general, I'd try to stick with overloads that are intuitive -- use of the '+' operator should reflect something analogous to addition, etc. If...
776,976
777,052
Getting different instances to communicate
Suppose I have two instances of the same class. The class has a pointer to some data, and I want the instances to exchange the pointers as part of some private function's algorithm, but without compromising the data to everybody else by giving a direct access to it through a public function. My first idea was to add a...
Objects of the same class can access each others' private data directly. You often see this in copy constructors, for example.
777,261
777,359
Avoiding unused variables warnings when using assert() in a Release build
Sometimes a local variable is used for the sole purpose of checking it in an assert(), like so - int Result = Func(); assert( Result == 1 ); When compiling code in a Release build, assert()s are usually disabled, so this code may produce a warning about Result being set but never read. A possible workaround is - int R...
We use a macro to specifically indicate when something is unused: #define _unused(x) ((void)(x)) Then in your example, you'd have: int Result = Func(); assert( Result == 1 ); _unused( Result ); // make production build happy That way (a) the production build succeeds, and (b) it is obvious in the code that the variab...
777,485
777,520
What is double(C++) in C#?
What is the double type(C++) in C#? double experience; At first,I thought its UInt32,but its not. How to declare it in C#?
This is a question that is dependent upon the particular C++ compiler implementation you are using. The double type can be either 4 or 8 bytes according to the C++ standard. Most compilers do use 8 bytes though. Here are the closest representations 4 bytes: float 8 bytes: double Reference: http://msdn.microsoft.co...
777,764
782,146
What modern C++ libraries should be in my toolbox?
I've been out of the C++ game for about 10 years and I want to get back in and start on a commercial app. What libraries are in use these days? User interface (e.g, wxWidgets, Qt) Database General purpose (e.g. Boost, Loki, STL) Threading Testing Network/sockets I looking to be cross-platform compatible (as much as ...
Cross-platform libraries that are free for commercial (or non-commercial) applications Feel free to expand this list General Purpose Boost Loki MiLi POCO STL (of course) STXXL (STL re-implementation for extra large data sets) Qt ASL JUCE Audio FMOD Synthesis ToolKit Database SOCI OTL LMDB++ Design IoC Fr...