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
30,729
30,766
C# Performance For Proxy Server (vs C++)
I want to create a simple http proxy server that does some very basic processing on the http headers (i.e. if header x == y, do z). The server may need to support hundreds of users. I can write the server in C# (pretty easy) or c++ (much harder). However, would a C# version have as good of performance as a C++ versi...
You can use unsafe C# code and pointers in critical bottleneck points to make it run faster. Those behave much like C++ code and I believe it executes as fast. But most of the time, C# is JIT-ted to uber-fast already, I don't believe there will be much differences as with what everyone has said. But one thing you might...
30,998
31,111
Is using too much static bad or good?
I like to use static functions in C++ as a way to categorize them, like C# does. Console::WriteLine("hello") Is this good or bad? If the functions are used often I guess it doesn't matter, but if not do they put pressure on memory? What about static const?
but is it good or bad The first adjective that comes to mind is "unnecessary". C++ has free functions and namespaces, so why would you need to make them static functions in a class? The use of static methods in uninstantiable classes in C# and Java is a workaround because those languages don't have free functions (...
31,867
32,062
Are there any examples where we *need* protected inheritance in C++?
While I've seen rare cases where private inheritance was needed, I've never encountered a case where protected inheritance is needed. Does someone have an example?
People here seem to mistake Protected class inheritance and Protected methods. FWIW, I've never seen anyone use protected class inheritance, and if I remember correctly I think Stroustrup even considered the "protected" level to be a mistake in c++. There's precious little you cannot do if you remove that protection le...
32,168
32,224
C++ cast syntax styles
A question related to Regular cast vs. static_cast vs. dynamic_cast: What cast syntax style do you prefer in C++? C-style cast syntax: (int)foo C++-style cast syntax: static_cast<int>(foo) constructor syntax: int(foo) They may not translate to exactly the same instructions (do they?) but their effect should be the sa...
It's best practice never to use C-style casts for three main reasons: as already mentioned, no checking is performed here. The programmer simply cannot know which of the various casts is used which weakens strong typing the new casts are intentionally visually striking. Since casts often reveal a weakness in the code,...
32,332
37,542
Why don't the std::fstream classes take a std::string?
This isn't a design question, really, though it may seem like it. (Well, okay, it's kind of a design question). What I'm wondering is why the C++ std::fstream classes don't take a std::string in their constructor or open methods. Everyone loves code examples so: #include <iostream> #include <fstream> #include <string> ...
By taking a C string the C++03 std::fstream class reduced dependency on the std::string class. In C++11, however, the std::fstream class does allow passing a std::string for its constructor parameter. Now, you may wonder why isn't there a transparent conversion from a std:string to a C string, so a class that expects a...
33,042
33,071
How can I measure CppUnit test coverage (on win32 and Unix)?
I have a very large code base that contains extensive unit tests (using CppUnit). I need to work out what percentage of the code is exercised by these tests, and (ideally) generate some sort of report that tells me on a per-library or per-file basis, how much of the code was exercised. Here's the kicker: this has to ru...
Which tool should I use? This article describes another developers frustrations searching for C++ code coverage tools. The author's final solution was Bullseye Coverage. Bullseye Coverage features: Cross Platform Support (win32, unix, and embedded), (supports linux gcc compilers and MSVC6) Easy to use (up and running...
33,306
33,313
C++ STL question: allocators
I have a (potentially dumb) question about the C++ STL. When I make a container (vector, set, map, etc), is it allocated on the stack or on the heap? If I make a set and put 5 million strings, will I have to worry about a stack overflow?
STL classes by default allocate their internal buffers from the heap, although these classes also allow custom allocators that allow a user to specify an alternate location to allocate from - e.g. a shared memory pool.
34,065
35,717
How to read a value from the Windows registry
Given the key for some registry value (e.g. HKEY_LOCAL_MACHINE\blah\blah\blah\foo) how can I: Safely determine that such a key exists. Programmatically (i.e. with code) get its value. I have absolutely no intention of writing anything back to the registry (for the duration of my career if I can help it). So we can sk...
Here is some pseudo-code to retrieve the following: If a registry key exists What the default value is for that registry key What a string value is What a DWORD value is Example code: Include the library dependency: Advapi32.lib HKEY hKey; LONG lRes = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Perl", 0, KEY_READ, ...
34,125
34,129
Which, if any, C++ compilers do tail-recursion optimization?
It seems to me that it would work perfectly well to do tail-recursion optimization in both C and C++, yet while debugging I never seem to see a frame stack that indicates this optimization. That is kind of good, because the stack tells me how deep the recursion is. However, the optimization would be kind of nice as wel...
All current mainstream compilers perform tail call optimisation fairly well (and have done for more than a decade), even for mutually recursive calls such as: int bar(int, int); int foo(int n, int acc) { return (n == 0) ? acc : bar(n - 1, acc + 2); } int bar(int n, int acc) { return (n == 0) ? acc : foo(n - 1...
34,325
34,329
Should I use a cross-platform GUI-toolkit or rely on the native ones?
On my side job as programmer, I am to write a program in C++ to convert audio files from/to various formats. Probably, this will involve building a simple GUI. Will it be a great effort to build seperate GUIs for Mac and Windows using Cocoa and WinForms instead of a cross-platform toolkit like Qt or GTK? (I will have t...
If you have the expertise, use native frontends, it'll effectively double the job you have to do for UI but from my experience non-native UI is a little bit clunkier than their native counterparts.
34,506
35,201
Simulating a virtual static member of a class in c++?
Is there anyway to have a sort of virtual static member in C++? For example: class BaseClass { public: BaseClass(const string& name) : _name(name) {} string GetName() const { return _name; } virtual void UseClass() = 0; private: const string _name; }; class DerivedClass : publi...
Here is one solution: struct BaseData { const string my_word; const int my_number; }; class Base { public: Base(const BaseData* apBaseData) { mpBaseData = apBaseData; } const string getMyWord() { return mpBaseData->my_word; } int getMyNumber() { return mpBa...
34,544
63,555
Detect DOM modification in Internet Explorer
I am writing a Browser Helper Object for ie7, and I need to detect DOM modification (i.e. via AJAX). So far I couldn't find any feasible solution.
You want to use IMarkupContainer2::CreateChangeLog.
34,732
34,796
How do I list the symbols in a .so file
How do I list the symbols being exported from a .so file? If possible, I'd also like to know their source (e.g. if they are pulled in from a static library). I'm using gcc 4.0.2, if that makes a difference.
The standard tool for listing symbols is nm, you can use it simply like this: nm -gD yourLib.so If you want to see symbols of a C++ library, add the "-C" option which demangle the symbols (it's far more readable demangled). nm -gDC yourLib.so If your .so file is in elf format, you have two options: Either objdump (-C...
34,955
41,043
Best practices for debugging linking errors
When building projects in C++, I've found debugging linking errors to be tricky, especially when picking up other people's code. What strategies do people use for debugging and fixing linking errors?
Not sure what your level of expertise is, but here are the basics. Below is a linker error from VS 2005 - yes, it's a giant mess if you're not familiar with it. ByteComparator.obj : error LNK2019: unresolved external symbol "int __cdecl does_not_exist(void)" (?does_not_exist@@YAHXZ) referenced in function "void __cdec...
35,485
35,738
Linux: What is the best way to estimate the code & static data size of program?
I want to be able to get an estimate of how much code & static data is used by my C++ program? Is there a way to find this out by looking at the executable or object files? Or perhaps something I can do at runtime? Will objdump & readelf help?
"size" is the traditional tool. "readelf" has a lot of options. $ size /bin/sh text data bss dec hex filename 712739 37524 21832 772095 bc7ff /bin/sh
35,522
35,524
looping and average in c++
Programming Student here...trying to work on a project but I'm stuck. The project is trying to find the miles per gallon per trip then at the end outputting total miles and total gallons used and averaging miles per gallon How do I loop back up to the first question after the first set of questions has been asked. Als...
You will have to tell us the type of data you are given. As per your last question: remember that an average can be calculated in real time by either storing the sum and the number of data points (two numbers), or the current average and the number of data points (again, two numbers). For instance: class Averager { ...
35,762
35,770
Linux GUI development
I have a large GUI project that I'd like to port to Linux. What is the most recommended framework to utilize for GUI programming in Linux? Are Frameworks such as KDE / Gnome usable for this objective Or is better to use something more generic other than X? I feel like if I chose one of Gnome or KDE, I'm closing the ma...
Your best bet may be to port it to a cross-platform widget library such as wxWidgets, which would give you portability to any platform wxWidgets supports. It's also important to make the distinction between Gnome libraries and GTK, and likewise KDE libraries and Qt. If you write the code to use GTK or Qt, it should wor...
35,950
35,965
I don't understand std::tr1::unordered_map
I need an associative container that makes me index a certain object through a string, but that also keeps the order of insertion, so I can look for a specific object by its name or just iterate on it and retrieve objects in the same order I inserted them. I think this hybrid of linked list and hash map should do the j...
Boost documentation of unordered containers The difference is in the method of how you generate the look up. In the map/set containers the operator< is used to generate an ordered tree. In the unordered containers, an operator( key ) => index is used. See hashing for a description of how that works.
36,039
36,080
Templates spread across multiple files
C++ seems to be rather grouchy when declaring templates across multiple files. More specifically, when working with templated classes, the linker expect all method definitions for the class in a single compiler object file. When you take into account headers, other declarations, inheritance, etc., things get really mes...
Are there any general advice or workarounds for organizing or redistributing templated member definitions across multiple files? Yes; don't. The C++ spec permits a compiler to be able to "see" the entire template (declaration and definition) at the point of instantiation, and (due to the complexities of any implement...
36,077
60,140
Finding out the source of an exception in C++ after it is caught?
I'm looking for an answer in MS VC++. When debugging a large C++ application, which unfortunately has a very extensive usage of C++ exceptions. Sometimes I catch an exception a little later than I actually want. Example in pseudo code: FunctionB() { ... throw e; ... } FunctionA() { ... FunctionB() ...
If you are just interested in where the exception came from, you could just write a simple macro like #define throwException(message) \ { \ std::ostringstream oss; \ oss << __FILE __ << " " << __LINE__ << " " \ << __FUNC__ << " " << message; \ throw std:...
36,114
36,246
Variable Holding data in a while statement
I know I must be missing something, but in a while statement how does the variable hold the data, when it finishes the first pass and goes into the second pass? { int num1 = 0 ; int num2 = 0; int num3 = 0; while (num1 < 10) {cout << "enter your first number: "; cin >> num1; cout << "Enter your second number: "...
Is num1 the variable you're having trouble with? This line: cin >> num1; is setting num1 to the value input by the user. So the value calculated for it in the previous run through the loop is being overwritten each time by the new input.
36,347
36,364
What are the differences between "generic" types in C++ and Java?
Java has generics and C++ provides a very strong programming model with templates. So then, what is the difference between C++ and Java generics?
There is a big difference between them. In C++ you don't have to specify a class or an interface for the generic type. That's why you can create truly generic functions and classes, with the caveat of a looser typing. template <typename T> T sum(T a, T b) { return a + b; } The method above adds two objects of the same...
36,832
75,654
Virtual functions in constructors, why do languages differ?
In C++ when a virtual function is called from within a constructor it doesn't behave like a virtual function. I think everyone who encountered this behavior for the first time was surprised but on second thought it made sense: As long as the derived constructor has not been executed the object is not yet a derived inst...
There's a fundamental difference in how the languages define an object's life time. In Java and .Net the object members are zero/null initialized before any constructor is run and is at this point that the object life time begins. So when you enter the constructor you've already got an initialized object. In C++ the ob...
36,890
42,467
Changing a CORBA interface without recompiling
I'd like to add a method to my existing server's CORBA interface. Will that require recompiling all clients? I'm using TAO.
Recompilation of clients is not required (and should not be, regardless of the ORB that you use). As Adam indicated, lookups are done by operation name (a straight text comparison). I've done what you're describing with our ACE/TAO-based system, and encountered no issues (servers were in ACE/TAO C++, clients were ACE/T...
36,991
37,001
Do you have to register a Dialog Box?
So, I am a total beginner in any kind of Windows related programming. I have been playing around with the Windows API and came across a couple of examples on how to initialize create windows and such. One example creates a regular window (I abbreviated some of the code): int WINAPI WinMain( [...] ) { [...] /...
You do not have to register a dialog box. Dialog boxes are predefined so (as you noted) there is no reference to a window class when you create a dialog. If you want more control of a dialog (like you get when you create your own window class) you would subclass the dialog which is a method by which you replace the dia...
37,067
37,314
Task oriented thread pooling
I've created a model for executing worker tasks in a server application using a thread pool associated with an IO completion port such as shown in the posts below: http://weblogs.asp.net/kennykerr/archive/2008/01/03/parallel-programming-with-c-part-4-i-o-completion-ports.aspx http://blogs.msdn.com/larryosterman/archive...
Not really, at least, not last time I looked. I mean, boost::thread_group might make things marginally tidier in places, but not so as would make much of a difference, I don't think. Boost's thread support seems marginally useful when writing something that's cross-platform, but given that what you're writing is going...
37,346
37,348
Why can't a forward declaration be used for a std::vector?
If I create a class like so: // B.h #ifndef _B_H_ #define _B_H_ class B { private: int x; int y; }; #endif // _B_H_ and use it like this: // main.cpp #include <iostream> #include <vector> class B; // Forward declaration. class A { public: A() { std::cout << v.size() << std::endl; } priva...
The compiler needs to know how big "B" is before it can generate the appropriate layout information. If instead, you said std::vector<B*>, then the compiler wouldn't need to know how big B is because it knows how big a pointer is.
37,398
37,402
How do I make a fully statically linked .exe with Visual Studio Express 2005?
My current preferred C++ environment is the free and largely excellent Microsoft Visual Studio 2005 Express edition. From time to time I have sent release .exe files to other people with pleasing results. However recently I made the disturbing discovery that the pleasing results were based on more luck that I would lik...
For the C-runtime go to the project settings, choose C/C++ then 'Code Generation'. Change the 'runtime library' setting to 'multithreaded' instead of 'multithreaded dll'. If you are using any other libraries you may need to tell the linker to ignore the dynamically linked CRT explicitly.
37,428
37,461
Get back to basics. How do I get back into C++?
I haven't used C++ since college. Even though I've wanted to I haven't needed to do any until I started wanting to write plugins for Launchy. Is there a good book to read to get back into it? My experience since college is mainly C# and recently ruby. I bought some book for C# developers and it ended up being on ho...
The best way to get back into C++ is to jump in. You can't learn a real language without spending any serious time in a country where they speak it. I wouldn't try to learn a programming language without spending time coding in it either. I wouldn't recommend learning C first though. That's a good way to pick up som...
37,473
37,474
How can I assert() without using abort()?
If I use assert() and the assertion fails then assert() will call abort(), ending the running program abruptly. I can't afford that in my production code. Is there a way to assert in runtime yet be able to catch failed assertions so I have the chance to handle them gracefully?
Yes, as a matter of fact there is. You will need to write a custom assert function yourself, as C++'s assert() is exactly C's assert(), with the abort() "feature" bundled in. Fortunately, this is surprisingly straightforward. Assert.hh template <typename X, typename A> inline void Assert(A assertion) { if( !asser...
37,799
38,317
GCOV for multi-threaded apps
Is it possible to use gcov for coverage testing of multi-threaded applications? I've set some trivial tests of our code-base up, but it would be nice to have some idea of the coverage we're achieving. If gcov isn't appropriate can anyone recommend an alternative tool (possible oprofile), ideally with some good documen...
We've certainly used gcov to get coverage information on our multi-threaded application. You want to compile with gcc 4.3 which can do coverage on dynamic code. You compile with the -fprofile-arcs -ftest-coverage options, and the code will generate .gcda files which gcov can then process. We do a separate build of our ...
37,956
38,017
C++ : What's the easiest library to open video file
I would like to open a small video file and map every frames in memory (to apply some custom filter). I don't want to handle the video codec, I would rather let the library handle that for me. I've tried to use Direct Show with the SampleGrabber filter (using this sample http://msdn.microsoft.com/en-us/library/ms787867...
Currently these are the most popular video frameworks available on Win32 platforms: Video for Windows: old windows framework coming from the age of Win95 but still widely used because it is very simple to use. Unfortunately it supports only AVI files for which the proper VFW codec has been installed. DirectShow: stand...
38,037
38,413
C++: How to extract a string from RapidXml
In my C++ program I want to parse a small piece of XML, insert some nodes, then extract the new XML (preferably as a std::string). RapidXml has been recommended to me, but I can't see how to retrieve the XML back as a text string. (I could iterate over the nodes and attributes and build it myself, but surely there's a ...
Althoug the documentation is poor on this topic, I managed to get some working code by looking at the source. Although it is missing the xml header which normally contains important information. Here is a small example program that does what you are looking for using rapidxml: #include <iostream> #include <sstream> #in...
38,299
38,568
Tutorial on understanding strings in Symbian
I have Carbide.c++ Developer from Nokia and I want to create applications for my S60 phone. I've looked at the samples that goes with the different SDK's for S60 but I haven't found any simple explanation on how strings, called descriptors, are used in Symbian. One of the problems are that I'm visually impaired and the...
Here are a few sites on blogspot that may help. They have RSS feeds that will hopefully be easier to consume than paging through PDFs. http://descriptor-tips.blogspot.com/ http://descriptors.blogspot.com/
38,447
66,560,184
Asynchronous Mysql connector
Do any asynchronous connectors exist for Mysql that can be used within a C or C++ application? I'm looking for something that can be plugged into a reactor pattern written in Boost.Asio. [Edit:] Running a synchronous connector in threads is not an option.
I know this is an old question, but consider looking at the new Boost.Mysql library: https://anarthal.github.io/mysql/index.html
38,501
40,291
Thread pool for executing arbitrary tasks with different priorities
I'm trying to come up with a design for a thread pool with a lot of design requirements for my job. This is a real problem for working software, and it's a difficult task. I have a working implementation but I'd like to throw this out to SO and see what interesting ideas people can come up with, so that I can compare ...
So what are we going to pick as the basic building block for this. Windows has two building blocks that look promising :- I/O Completion Ports (IOCPs) and Asynchronous Procedure Calls (APCs). Both of these give us FIFO queuing without having to perform explicit locking, and with a certain amount of built-in OS suppor...
38,822
49,780
Best full text search alternative to MS SQL, C++ solution
What is the best full text search alternative to Microsoft SQL? (which works with MS SQL) I'm looking for something similar to Lucene and Lucene.NET but without the .NET and Java requirements. I would also like to find a solution that is usable in commercial applications.
Take a look at CLucene - It's a well maintained C++ port of java Lucene. It's currently licenced under LGPL and we use it in our commercial application. Performance is incredible, however you do have to get your head around some of the strange API conventions.
39,304
39,314
Do C++ logging frameworks sacrifice reusability?
In C++, there isn't a de-facto standard logging tool. In my experience, shops roll their own. This creates a bit of a problem, however, when trying to create reusable software components. If everything in your system depends on the logging component, this makes the software less reusable, basically forcing any downs...
Yes. But dependency injection will help in this case. You can create an abstract logging base-class and create implementations for the logging-frameworks you want to use. Your components are just dependent on the abstract base-class. And you inject the implementations along with al their dependencies as needed.
39,419
39,441
How large is a DWORD with 32- and 64-bit code?
In Visual C++ a DWORD is just an unsigned long that is machine, platform, and SDK dependent. However, since DWORD is a double word (that is 2 * 16), is a DWORD still 32-bit on 64-bit architectures?
Actually, on 32-bit computers a word is 32-bit, but the DWORD type is a leftover from the good old days of 16-bit. In order to make it easier to port programs to the newer system, Microsoft has decided all the old types will not change size. You can find the official list here: http://msdn.microsoft.com/en-us/library/a...
39,468
39,478
Calling DLL functions from VB6
I've got a Windows DLL that I wrote, written in C/C++ (all exported functions are 'C'). The DLL works fine for me in VC++. I've given the DLL to another company who do all their development in VB. They seem to be having a problem linking to the functions. I haven't used VB in ten years and I don't even have it installe...
By using __declspec for export, the function name will get exported mangled, i.e. contain type information to help the C++ compiler resolve overloads. VB6 cannot handle mangled names. As a workaround, you have to de-mangle the names. The easiest solution is to link the DLL file using an export definition file in VC++. ...
39,474
39,590
How to get IntelliSense to reliably work in Visual Studio 2008
Does anyone know how to get IntelliSense to work reliably when working in C/C++ projects? It seems to work for about 1 in 10 files. Visual Studio 2005 seems to be a lot better than 2008. Edit: Whilst not necessarily a solution, the work-around provided here: How to get IntelliSense to reliably work in Visual Studio 20...
I've also realized than Intellisense is sometime 'lost', on some big project. Why? No idea. This is why we have bought Visual Assist (from Tomato software) and disabled Intellisense by deleting the dll feacp.dll in the Visual studio subdirectory (C:\Program Files\Microsoft Visual Studio 8\VC\vcpackages) This is not a s...
39,912
39,944
How do I remove an item from a stl vector with a certain value?
I was looking at the API documentation for stl vector, and noticed there was no method on the vector class that allowed the removal of an element with a certain value. This seems like a common operation, and it seems odd that there's no built in way to do this.
std::remove does not actually erase elements from the container: it moves the elements to be removed to the end of the container, and returns the new end iterator which can be passed to container_type::erase to do the actual removal of the extra elements that are now at the end of the container: std::vector<int> vec; /...
40,423
40,616
How would you implement Erlang-like send and receive in C++?
Actually, this question seems to have two parts: How to implement pattern matching? How to implement send and receive (i.e. the Actor model)? For the pattern matching part, I've been looking into various projects like App and Prop. These look pretty nice, but couldn't get them to work on a recent version (4.x) of g+...
One of the important things about erlang is how the features are used to make robust systems. The send/recieve model is no-sharing, and explicitly copying. The processes themselves are lightweight threads. If you did desire the robust properties of the erlang model, you would be best to use real processes and IPC rathe...
41,045
41,059
Can I have polymorphic containers with value semantics in C++?
As a general rule, I prefer using value rather than pointer semantics in C++ (ie using vector<Class> instead of vector<Class*>). Usually the slight loss in performance is more than made up for by not having to remember to delete dynamically allocated objects. Unfortunately, value collections don't work when you want to...
Since the objects of different classes will have different sizes, you would end up running into the slicing problem if you store them as values. One reasonable solution is to store container safe smart pointers. I normally use boost::shared_ptr which is safe to store in a container. Note that std::auto_ptr is not. vect...
41,400
41,794
How can I wrap a function with variable length arguments?
I am looking to do this in C/C++. I came across Variable Length Arguments, but this suggests a solution with Python and C using libffi. Now, if I want to wrap the printf function with myprintf. I do it like below: void myprintf(char* fmt, ...) { va_list args; va_start(args, fmt); printf(fmt, args); va_e...
The problem is that you cannot use 'printf' with va_args. You must use vprintf if you are using variable argument lists. vprint, vsprintf, vfprintf, etc. (there are also 'safe' versions in Microsoft's C runtime that will prevent buffer overruns, etc.) You sample works as follows: void myprintf(char* fmt, ...) { ...
41,453
34,551,440
How can I add reflection to a C++ application?
I'd like to be able to introspect a C++ class for its name, contents (i.e. members and their types) etc. I'm talking native C++ here, not managed C++, which has reflection. I realise C++ supplies some limited information using RTTI. Which additional libraries (or other techniques) could supply this information?
Ponder is a C++ reflection library, in answer to this question. I considered the options and decided to make my own since I couldn't find one that ticked all my boxes. Although there are great answers to this question, I don't want to use tonnes of macros, or rely on Boost. Boost is a great library, but there are lots...
41,583
41,591
How to do a sample rate conversion in Windows (and OSX)
I am about to write an audio file converter for my side job at the university. As part of this I would need sample rate conversion. However, my professor said that it would be pretty hard to write a sample rate converter that was both of good quality and fast. On my research on the subject, I found some functions in th...
Try Secret Rabbit Code (= SRC = Sample Rate Conversion ) It's GPL, it's fast and it's high quality. http://www.mega-nerd.com/SRC/license.html
41,590
41,598
How do you properly use namespaces in C++?
I come from a Java background, where packages are used, not namespaces. I'm used to putting classes that work together to form a complete object into packages, and then reusing them later from that package. But now I'm working in C++. How do you use namespaces in C++? Do you create a single namespace for the entire app...
Namespaces are packages essentially. They can be used like this: namespace MyNamespace { class MyClass { }; } Then in code: MyNamespace::MyClass* pClass = new MyNamespace::MyClass(); Or, if you want to always use a specific namespace, you can do this: using namespace MyNamespace; MyClass* pClass = new MyClass(...
41,654
41,668
C++ libraries to manipulate images
Do you know any open source/free software C++ libraries to manipulate images in these formats: .jpg .gif .png .bmp ? The more formats it supports, the better. I am implementing a free program in C++ which hides a text file into one or more images, using steganography. I am working under Unix.
ImageMagick can manipulate about anything and has interfaces for a dozen of languages, including the Magick++ API for C++.
41,676
41,710
Is there a way of getting the process id of my C++ application?
Is there a way of getting the process id of my C++ application? I am using the Carbon framework, but not Cocoa…
can you use the getpid() function found in unistd.h ? osx reference
41,832
41,859
Maintain the correct version for a COM dll referenced in a .NET project
I want to reference a COM DLL in a .NET project, but I also want to make sure that the interop DLL created will have the correct version (so that patches will know when the DLL must be changed). If I use TlbImp I can specify the required version with the /asmversion flag but when I add it directly from Visual Studio it...
The Guid refers to the Guid for the TypeLib not the DLL directly. The version numbers refer to the TypeLib's version not the DLLs. The version number will come from your idl file, and I believe it only supports a major and minor version and not a build version. Is this version changing when you modify the typelib? Th...
42,126
42,327
C++ Compiler Error C2371 - Redefinition of WCHAR
I am getting C++ Compiler error C2371 when I include a header file that itself includes odbcss.h. My project is set to MBCS. C:\Program Files\Microsoft SDKs\Windows\v6.0A\include\odbcss.h(430) : error C2371: 'WCHAR' : redefinition; different basic types 1> C:\Program Files\Microsoft SDKs\Windows\v6.0A\include\winn...
This is a known bug - see the Microsoft Connect website: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98699 The error doesn't occur if you compile your app as Unicode instead of MBCS.
42,308
42,513
Tool to track #include dependencies
Any good suggestions? Input will be the name of a header file and output should be a list (preferably a tree) of all files including it directly or indirectly.
If you have access to GCC/G++, then the -M option will output the dependency list. It doesn't do any of the extra stuff that the other tools do, but since it is coming from the compiler, there is no chance that it will pick up files from the "wrong" place.
42,446
42,968
How do I convert an IntPtr to a Stream?
class Foo { static bool Bar(Stream^ stream); }; class FooWrapper { bool Bar(LPCWSTR szUnicodeString) { return Foo::Bar(??); } }; MemoryStream will take a byte[] but I'd like to do this without copying the data if possible.
You can avoid the copy if you use an UnmanagedMemoryStream() instead (class exists in .NET FCL 2.0 and later). Like MemoryStream, it is a subclass of IO.Stream, and has all the usual stream operations. Microsoft's description of the class is: Provides access to unmanaged blocks of memory from managed code. which pret...
42,531
42,544
How do I call ::CreateProcess in c++ to launch a Windows executable?
Looking for an example that: Launches an EXE Waits for the EXE to finish. Properly closes all the handles when the executable finishes.
Something like this: STARTUPINFO info={sizeof(info)}; PROCESS_INFORMATION processInfo; if (CreateProcess(path, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo)) { WaitForSingleObject(processInfo.hProcess, INFINITE); CloseHandle(processInfo.hProcess); CloseHandle(processInfo.hThread); }
42,770
42,806
Writing/Using C++ Libraries
I am looking for basic examples/tutorials on: How to write/compile libraries in C++ (.so files for Linux, .dll files for Windows). How to import and use those libraries in other code.
The code r.cc : #include "t.h" int main() { f(); return 0; } t.h : void f(); t.cc : #include<iostream> #include "t.h" void f() { std::cout << "OH HAI. I'M F." << std::endl; } But how, how, how?! ~$ g++ -fpic -c t.cc # get t.o ~$ g++ -shared -o t.so t.o # get t.so ~$ export LD_LIBRARY_P...
43,194
43,304
Mixing C/C++ Libraries
Is it possible for gcc to link against a library that was created with Visual C++? If so, are there any conflicts/problems that might arise from doing so?
Some of the comments in the answers here are slightly too generalistic. Whilst no, in the specific case mentioned gcc binaries won't link with a VC++ library (AFAIK). The actual means of interlinking code/libraries is a question of the ABI standard being used. An increasingly common standard in the embedded world is t...
43,322
43,325
What's safe for a C++ plug-in system?
Plug-in systems in C++ are hard because the ABI is not properly defined, and each compiler (or version thereof) follows its own rules. However, COM on Windows shows that it's possible to create a minimal plug-in system that allows programmers with different compilers to create plug-ins for a host application using a s...
Dr Dobb's Journal has an article Building Your Own Plugin Framework: Part 1 which is pretty good reading on the subject. It is the start of a series of articles which covers the architecture, development, and deployment of a C/C++ cross-platform plugin framework.
44,693
44,762
Efficient alternatives for exposing a Collection
In C++, what alternatives do I have for exposing a collection, from the point of view of performance and data integrity? My problem is that I want to return an internal list of data to the caller, but I don't want to generate a copy. Thant leaves me with either returning a reference to the list, or a pointer to the lis...
RichQ's answer is a reasonable technique, if you're using an array, vector, etc. If you're using a collection that isn't indexed by ordinal values... or think you might need to at some point in the near future... then you might want to consider exposing your own iterator type(s), and associated begin()/end() methods: ...
44,821
45,170
Default smart device project can't find dependencies
When running the default c++ project in Visual Studios for a Windows CE 5.0 device, I get an error complaining about missing resources. Depends says that my executable needs ayghsell.dll (the Windows Mobile shell), and CoreDll.dll. Does this mean that my executable can only be run on Windows Mobile devices, instead o...
Depends what you mean by a generic Windows CE installation. Windows CE itself is a modularised operating system, so different devices can have different modules included. Therefore each Windows CE device can have a radically different OS installed (headless even). Coredll is the standard "common" library that gets incl...
45,286
45,316
How can I overwrite the same portion of the console in a Windows native C++ console app, without using a 3rd Party library?
I have a console app that needs to display the state of items, but rather than having text scroll by like mad I'd rather see the current status keep showing up on the same lines. For the sake of example: Running... nn% complete Buffer size: bbbb bytes should be the output, where 'nn' is the current percentage compl...
You can use SetConsoleCursorPosition. You'll need to call GetStdHandle to get a handle to the output buffer.
45,528
45,587
Simplest way to change listview and treeview colours
I'm trying to find a simple way to change the colour of the text and background in listview and treeview controls in WTL or plain Win32 code. I really don't want to have to implement full owner drawing for these controls, simply change the colours used. I want to make sure that the images are still drawn with proper tr...
Have a look at the following macros: ListView_SetBkColor ListView_SetTextColor TreeView_SetBkColor TreeView_SetTextColor
45,658
63,430
How do I retrieve IPIEHTMLDocument2 interface on IE Mobile
I wrote an Active X plugin for IE7 which implements IObjectWithSite besides some other necessary interfaces (note no IOleClient). This interface is queried and called by IE7. During the SetSite() call I retrieve a pointer to IE7's site interface which I can use to retrieve the IHTMLDocument2 interface using the followi...
I found the following code in the Google Gears code, here. I copied the functions I think you need to here. The one you need is at the bottom (GetHtmlWindow2), but the other two are needed as well. Hopefully I didn't miss anything, but if I did the stuff you need is probably at the link. #ifdef WINCE // We can't get IW...
45,972
6,383,253
mmap() vs. reading blocks
I'm working on a program that will be processing files that could potentially be 100GB or more in size. The files contain sets of variable length records. I've got a first implementation up and running and am now looking towards improving performance, particularly at doing I/O more efficiently since the input file gets...
I was trying to find the final word on mmap / read performance on Linux and I came across a nice post (link) on the Linux kernel mailing list. It's from 2000, so there have been many improvements to IO and virtual memory in the kernel since then, but it nicely explains the reason why mmap or read might be faster or sl...
47,538
47,554
Where's the Win32 resource for the mouse cursor for dragging splitters?
I am building a custom win32 control/widget and would like to change the cursor to a horizontal "splitter" symbol when hovering over a particular vertical line in the control. IE: I want to drag this vertical line (splitter bar) left and right (WEST and EAST). Of the the system cursors (OCR_*), the only cursor that mak...
There are all sorts of icons, cursors, and images in use throughout the Windows UI which are not publicly available to 3rd-party software. Of course, you could still load up the module in which they reside and use them, but there's really no guarantee your program will keep working after a system update / upgrade. Inc...
47,901
47,921
Can UDP data be delivered corrupted?
Is it possible for UDP data to come to you corrupted? I know it is possible for it to be lost.
UDP packets use a 16 bit checksum. It is not impossible for UDP packets to have corruption, but it's pretty unlikely. In any case it is not more susceptible to corruption than TCP.
47,975
70,695
Is it possible to develop DirectX apps in Linux?
More out of interest than anything else, but can you compile a DirectX app under linux? Obviously there's no official SDK, but I was thinking it might be possible with wine. Presumably wine has an implementation of the DirectX interface in order to run games? Is it possible to link against that? (edit: This is called w...
I've had some luck with this. I've managed to compile this simple Direct3D example. I used winelib for this (wine-dev package on Ubuntu). Thanks to alastair for pointing me to winelib. I modified the source slightly to convert the wchars to chars (1 on line 52, 2 on line 55, by removing the L before the string literals...
47,980
47,983
Deciphering C++ template error messages
I'm really beginning to understand what people mean when they say that C++'s error messages are pretty terrible in regards to templates. I've seen horrendously long errors for things as simple as a function not matching its prototype. Are there any tricks to deciphering these errors? EDIT: I'm using both gcc and MSVC...
You can try the following tool to make things more sane: http://www.bdsoft.com/tools/stlfilt.html
47,981
47,990
How do I set, clear, and toggle a single bit?
How do I set, clear, and toggle a bit?
Setting a bit Use the bitwise OR operator (|) to set a bit. number |= 1UL << n; That will set the nth bit of number. n should be zero, if you want to set the 1st bit and so on upto n-1, if you want to set the nth bit. Use 1ULL if number is wider than unsigned long; promotion of 1UL << n doesn't happen until after eval...
48,017
48,031
What is a jump table?
Can someone explain the mechanics of a jump table and why is would be needed in embedded systems?
A jump table can be either an array of pointers to functions or an array of machine code jump instructions. If you have a relatively static set of functions (such as system calls or virtual functions for a class) then you can create this table once and call the functions using a simple index into the array. This woul...
48,053
48,103
Is there any alternative to using % (modulus) in C/C++?
I read somewhere once that the modulus operator is inefficient on small embedded devices like 8 bit micro-controllers that do not have integer division instruction. Perhaps someone can confirm this but I thought the difference is 5-10 time slower than with an integer division operation. Is there another way to do this ...
Ah, the joys of bitwise arithmetic. A side effect of many division routines is the modulus - so in few cases should division actually be faster than modulus. I'm interested to see the source you got this information from. Processors with multipliers have interesting division routines using the multiplier, but you can...
48,094
48,102
C++ deleting a pointer to a pointer
So I have a pointer to an array of pointers. If I delete it like this: delete [] PointerToPointers; Will that delete all the pointed to pointers as well? If not, do I have to loop over all of the pointers and delete them as well, or is there an easier way to do it? My google-fu doesn't seem to give me any good answ...
Yes you have to loop over the pointers, deleting individually. Reason: What if other code had pointers to the objects in your array? The C++ compiler doesn't know if that's true or not, so you have to be explicit. For an "easier way," two suggestions: (1) Make a subroutine for this purpose so at least you won't have t...
48,338
48,343
Am I allowed to run a javascript runtime (like v8) on the iPhone?
According to this discussion, the iphone agreement says that it doesn't allow "loading of plugins or running interpreted code that has been downloaded". Technically, I would like to download scripts from our server (embedded in a proprietary protocol). Does this mean I wouldn't be allowed to run a runtime like v8 in an...
I think your interpretation is correct - You would not be allowed to download and execute JavaScript code in v8. If there were some way to run the code in an interpreter already on the iPhone (i.e. the javascript engine in MobileSafari) then that would be permitted I think.
48,390
48,587
Eclipse spelling engine does not exist
I'm using Eclipse 3.4 (Ganymede) with CDT 5 on Windows. When the integrated spell checker doesn't know some word, it proposes (among others) the option to add the word to a user dictionary. If the user dictionary doesn't exist yet, the spell checker offers then to help configuring it and shows the "General/Editors/Text...
Are you using the C/C++ Development Tools exclusively?The Spellcheck functionality is dependent upon the Java Development Tools being installed also.The spelling engine is scheduled to be pushed down from JDT to the Platform,so you can get rid of the Java related bloat soon enough. :)
48,426
112,078
How could I graphically display the memory layout from a .map file?
My gcc build toolchain produces a .map file. How do I display the memory map graphically?
Here's the beginnings of a script in Python. It loads the map file into a list of Sections and Symbols (first half). It then renders the map using HTML (or do whatever you want with the sections and symbols lists). You can control the script by modifying these lines: with open('t.map') as f: colors = ['9C9F84', 'A97D5D...
48,496
48,508
How to teach a crash course on C++?
In a few weeks, we'll be teaching a crash course on C++ for Java programmers straight out of college. They have little or no experience yet with C or C++. Previous editions of this course were just 1 or 2 half-day sessions and covered topics including: new language features, e.g. header vs. implementation pointers an...
I can only once again point to Stroustrup and preach: Don't teach the C subset! It's important, but not for beginners! C++ is complex enough as it is and the standard library classes, especially the STL, is much more important and (at least superficially) easier to understand than the C subset of C++. Same goes for poi...
48,647
48,663
Does ScopeGuard use really lead to better code?
I came across this article written by Andrei Alexandrescu and Petru Marginean many years ago, which presents and discusses a utility class called ScopeGuard for writing exception-safe code. I'd like to know if coding with these objects truly leads to better code or if it obfuscates error handling, in that perhaps the g...
It definitely improves your code. Your tentatively formulated claim, that it's obscure and that code would merit from a catch block is simply not true in C++ because RAII is an established idiom. Resource handling in C++ is done by resource acquisition and garbage collection is done by implicit destructor calls. On the...
49,035
49,056
What does the const operator mean when used with a method in C++?
Given a declaration like this: class A { public: void Foo() const; }; What does it mean? Google turns up this: Member functions should be declared with the const keyword after them if they can operate on a const (this) object. If the function is not declared const, in can not be applied to a const object, and the...
Consider a variation of your class A. class A { public: void Foo() const; void Moo(); private: int m_nState; // Could add mutable keyword if desired int GetState() const { return m_nState; } void SetState(int val) { m_nState = val; } }; const A *A1 = new A(); A *A2 = new A(); A1->Foo(); // OK A...
49,046
49,055
Different sizeof results
Why does n not equal to 8 in the following function? void foo(char cvalue[8]) { int n = sizeof (cvalue); } But n does equal to 8 in this version of the function: void bar() { char cvalue[8]; int n = sizeof (cvalue); }
Because you can't pass entire arrays as function parameters in C. You're actually passing a pointer to it; the brackets are syntactic sugar. There are no guarantees the array you're pointing to has size 8, since you could pass this function any character pointer you want. // These all do the same thing void foo(char ...
49,098
49,130
Can cout alter variables somehow?
So I have a function that looks something like this: float function(){ float x = SomeValue; return x / SomeOtherValue; } At some point, this function overflows and returns a really large negative value. To try and track down exactly where this was happening, I added a cout statement so that the function looke...
Welcome to the wonderful world of floating point. The answer you get will likely depend on the floating point model you compiled the code with. This happens because of the difference between the IEEE spec and the hardware the code is running on. Your CPU likely has 80 bit floating point registers that get use to ho...
49,137
49,148
Calling python from a c++ program for distribution
I would like to call python script files from my c++ program. I am not sure that the people I will distribute to will have python installed.
Boost has a python interface library which could help you. Boost.Python
49,168
49,172
How can I embed Perl inside a C++ application?
I would like to call Perl script files from my c++ program. I am not sure that the people I will distribute to will have Perl installed. Basically I'm looking for a .lib file that I can use that has an Apache like distribution license.
You can embed perl into your app. Perl Embedding by John Quillan C++ wrapper around Perl C API
49,211
345,696
How can I use a key blob generated from Win32 CryptoAPI in my .NET application?
I have an existing application that is written in C++ for Windows. This application uses the Win32 CryptoAPI to generate a TripleDES session key for encrypting/decrypting data. We're using the exponent of one trick to export the session key out as a blob, which allows the blob to be stored somewhere in a decrypted form...
Intro I'm Finally getting around to posting the solution. I hope it provides some help to others out there that might be doing similar type things. There really isn't much reference to doing this elsewhere. Prerequisites In order for a lot of this to make sense it's necessary to read the exponent of one trick, which al...
49,258
49,266
What is the cleanest way to direct wxWidgets to always use wxFileConfig?
I am writing my first serious wxWidgets program. I'd like to use the wxConfig facility to make the program's user options persistent. However I don't want wxConfigBase to automatically use the Windows registry. Even though I'm initially targeting Windows, I'd prefer to use a configuration (eg .ini) file. Does anyone kn...
According to the source of wx/config.h file, all you need is to define the wxUSE_CONFIG_NATIVE symbol to 0 in your project and then it will always use wxFileConfig.
50,120
50,168
Database abstraction layers for (Visual) C++
What options exist for accessing different databases from C++? Put differently, what alternatives are there to ADO? What are the pros and cons?
Microsoft ODBC. The MFC ODBC classes such as CDatabase. OleDB (via COM). And you can always go through the per-RDBMS native libraries (for example, the SQL Server native library) DAO (don't). 3rd party ORM providers. I would recommend going through ODBC or OleDB by default. Native libraries really restrict you, DAO i...
50,311
56,899
create and stream large XML document in C++
I have some code that creates a fairly large xml DOM and writes it off to a file (up to 50-100MB) . It basically creates the DOM and then calls a toString on it and writes it out with ofstream. Is there a way to get streaming output of the generated dom so that it doesn't create the whole structure in memory all at onc...
Ok, turns out libxml2 has a streaming API: http://xmlsoft.org/examples/testWriter.c It's a little old style (very C-ish) but you can write your wrapper around it.
51,032
51,080
Is there a difference between foo(void) and foo() in C++ or C?
Consider these two function definitions: void foo() { } void foo(void) { } Is there any difference between these two? If not, why is the void argument there? Aesthetic reasons?
In C: void foo() means "a function foo taking an unspecified number of arguments of unspecified type" void foo(void) means "a function foo taking no arguments" In C++: void foo() means "a function foo taking no arguments" void foo(void) means "a function foo taking no arguments" By writing foo(void), theref...
51,266
51,427
High availability and scalable platform for Java/C++ on Solaris
I have an application that's a mix of Java and C++ on Solaris. The Java aspects of the code run the web UI and establish state on the devices that we're talking to, and the C++ code does the real-time crunching of data coming back from the devices. Shared memory is used to pass device state and context information from...
The first thing I would do is construct a model of the system to map the data flow and try to understand precisely where the bottleneck lies. If you can model your system as a pipeline, then you should be able to use the theory of constraints (most of the literature is about optimising business processes but it applie...
51,436
51,460
How to host licensed .Net controls in unmanaged C++ app?
I need to host and run managed controls inside of a purely unmanaged C++ app. How to do this? To run unlicensed controls is typically simple: if (SUCCEEDED(ClrCreateManagedInstance(type, iid, &obj))) { // do something with obj } When using a licensed control however, we need to somehow embed a .licx file into the ...
The answer depends on the particular component you're using. Contact your component help desk OR read up the documentation on what it takes to deploy their component. Basically component developers are free to implement licensing as they deem fit. With the .licx file the component needs to be able to do whatever the de...
51,592
51,602
Is there a need to destroy char * = "string" or char * = new char[6]?
I assume that char* = "string" is the same to char* = new char[6]. I believe these strings are created on the heap instead of the stack. So do I need to destroy them or free their memory when I'm done using them or do they get destroyed by themselves?
No. You only need to manually free strings when you manually allocate the memory yourself using the malloc function (in C) or the new operator (in C++). If you do not use malloc or new, then the char* or string will be created on the stack or as a compile-time constant.
51,687
54,341
Lightbox style dialogs in MFC App
Has anyone implemented Lightbox style background dimming on a modal dialog box in a MFC/non .net app. I think the procedure would have to be something like: steps: Get dialog parent HWND or CWnd* Get the rect of the parent window and draw an overlay with a translucency over that window allow the dialog to do it...
Here's what I did* based on Brian's links First create a dialog resource with the properties: border FALSE 3D look FALSE client edge FALSE Popup style static edge FALSE Transparent TRUE Title bar FALSE and you should end up with a dialog window with no frame or anything, just a grey box. override the Create function...
51,859
51,920
Using Makefile instead of Solution/Project files under Visual Studio (2005)
Does anyone have experience using makefiles for Visual Studio C++ builds (under VS 2005) as opposed to using the project/solution setup. For us, the way that the project/solutions work is not intuitive and leads to configuruation explosion when you are trying to tweak builds with specific compile time flags. Under Uni...
I've found some benefits to makefiles with large projects, mainly related to unifying the location of the project settings. It's somewhat easier to manage the list of source files, include paths, preprocessor defines and so on, if they're all in a makefile or other build config file. With multiple configurations, add...
51,949
52,009
How to get file extension from string in C++
Given a string "filename.conf", how to I verify the extension part? I need a cross platform solution.
You have to make sure you take care of file names with more then one dot. example: c:\.directoryname\file.name.with.too.many.dots.ext would not be handled correctly by strchr or find. My favorite would be the boost filesystem library that have an extension(path) function
52,357
52,365
What is the point of clog?
I've been wondering, what is the point of clog? As near as I can tell, clog is the same as cerr but with buffering so it is more efficient. Usually stderr is the same as stdout, so clog is the same as cout. This seems pretty lame to me, so I figure I must be misunderstanding it. If I have log messages going out to the ...
Is it possible to redirect clog, cerr, cout, stdin, stdout, and/or stderr? Yes. You want the rdbuf function. ofstream ofs("logfile"); cout.rdbuf(ofs.rdbuf()); cout << "Goes to file." << endl; Is the only difference between clog and cerr the buffering? As far as I know, yes.
52,506
52,617
C++ Template Ambiguity
A friend and I were discussing C++ templates. He asked me what this should do: #include <iostream> template <bool> struct A { A(bool) { std::cout << "bool\n"; } A(void*) { std::cout << "void*\n"; } }; int main() { A<true> *d = 0; const int b = 2; const int c = 1; new A< b > (c) > (d); } The l...
AFAIK it would be compiled as new A<b>(c) > d. This is the only reasonable way to parse it IMHO. If the parser can't assume under normal circumstances a > end a template argument, that would result it much more ambiguity. If you want it the other way, you should have written: new A<(b > c)>(d);
52,557
57,553
profile-guided optimization (C)
Anyone know this compiler feature? It seems GCC support that. How does it work? What is the potential gain? In which case it's good? Inner loops? (this question is specific, not about optimization in general, thanks)
It works by placing extra code to count the number of times each codepath is taken. When you compile a second time the compiler uses the knowledge gained about execution of your program that it could only guess at before. There are a couple things PGO can work toward: Deciding which functions should be inlined or not ...
52,714
52,734
STL vector vs map erase
In the STL almost all containers have an erase function. The question I have is in a vector, the erase function returns an iterator pointing to the next element in the vector. The map container does not do this. Instead it returns a void. Anyone know why there is this inconsistancy?
See http://www.sgi.com/tech/stl/Map.html Map has the important property that inserting a new element into a map does not invalidate iterators that point to existing elements. Erasing an element from a map also does not invalidate any iterators, except, of course, for iterators that actually point to the ...
53,757
53,759
Which compiles to faster code: "n * 3" or "n+(n*2)"?
Which compiles to faster code: "ans = n * 3" or "ans = n+(n*2)"? Assuming that n is either an int or a long, and it is is running on a modern Win32 Intel box. Would this be different if there was some dereferencing involved, that is, which of these would be faster? long a; long *pn; long ans; ... *pn = som...
IMO such micro-optimization is not necessary unless you work with some exotic compiler. I would put readability on the first place.
53,811
53,826
How do you normally set up your compiler's optimization settings?
Do you normally set your compiler to optimize for maximum speed or smallest code size? or do you manually configure individual optimization settings? Why? I notice most of the time people tend to just leave compiler optimization settings to their default state, which with visual c++ means max speed. I've always felt th...
As a Gentoo user I have tried quite a few optimizations on the complete OS and there have been endless discussions on the Gentoo forums about it. Some good flags for GCC can be found in the wiki. In short, optimizing for size worked best on an old Pentium3 laptop with limited ram, but on my main desktop machine with a ...
53,849
53,863
How do I tokenize a string in C++?
Java has a convenient split method: String str = "The quick brown fox"; String[] results = str.split(" "); Is there an easy way to do this in C++?
C++ standard library algorithms are pretty universally based around iterators rather than concrete containers. Unfortunately this makes it hard to provide a Java-like split function in the C++ standard library, even though nobody argues that this would be convenient. But what would its return type be? std::vector<std::...