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
191,814
191,836
Can pipes be used across LAN computers?
Can pipes be used across LAN computers? In particular I'm looking for Windows, but if you have more info on other platforms, that will also help others who find this thread later.
Yes they can. Named pipes can be used to provide communication between processes on the same computer or between processes on different computers across a network. If the server service is running, all named pipes are accessible remotely http://msdn.microsoft.com/en-us/library/aa365590.aspx
191,980
191,992
In an MFC application, what's the easiest way to copy a file from one directory to another?
Should I create two CFile objects and copy one into the other character by character? Or is there something in the library that will do this for me?
I would just use the CopyFile Win32 API function, but the example code in the CFile::Open documentation shows how to copy files with CFile (using pretty much the method you suggest).
192,021
192,046
Why are pipes considered dangerous to use in Windows/unix/linux?
Why are pipes considered dangerous to use? What can be done to avoid these security issues? I'm mostly interested in Windows, but if you have other OS information, please provide.
(assuming you're talking about Unix named pipes from the mention of 'c' and 'IPC'. Windows named pipes work somewhat differently) Anyone with permissions can write to a named pipe, so you have to be careful with permissions and locking (see flock()). If an application trusts the input it's getting from the named pipe...
192,124
192,568
How do I load and save an image from an SQL Server database using GDI+ and C++?
I need specifically to load a JPG image that was saved as a blob. GDI+ makes it very easy to retrieve images from files but not from databases...
Take a look at Image::Image(IStream *, BOOL). This takes a pointer to a COM object implementing the IStream interface. You can get one of these by allocating some global memory with GlobalAlloc and then calling CreateStreamOnHGlobal on the returned handle. It'll look something like this: shared_ptr<Image> CreateImag...
192,940
192,979
Storing PCRE compiled regexes in C/C++
Is there an efficient way to store the compiled regexes (compiled via regcomp(), PCRE) in a binary file, so that later I can just read from the file and call regexec()? Or is it just a matter of dumping the compiled regex_t structs to the file and reading them back when needed?
Unless you have a super-complex regex, I hardly see an advantage of serializing the compiled regex, the compilation time shouldn't be that big. Unless you are on a super-tight embed system? In any case, indeed dumping the structure might be a solution, at least you can try... [EDIT] I just looked at the source I have (...
193,469
193,770
How do I make Visual Studio pause after executing a console application in debug mode?
I have a collection of Boost unit tests I want to run as a console application. When I'm working on the project and I run the tests I would like to be able to debug the tests, and I would like to have the console stay open after the tests run. I see that if I run in release mode the console window stays up after the pr...
Boost test offers the following usage recommendations for Visual Studio that would enable you to run the unit tests automatically at the end of compilation and capture the output into the build window. The nice side effect of this trick is it enable you to treat test failures as compilation errors. "...you could jump ...
193,471
687,302
Which is better BOOST_MPL_ASSERT or BOOST_STATIC_ASSERT?
As I recall BOOST_MPL_ASSERT was once preferred. Is this still true? Anyone know why?
[Answering my own question] It depends. This is an apples to oranges comparison. Although similar, these macros are NOT interchangeable. Here's a summary of how each works: BOOST_STATIC_ASSERT( P ) generates a compilation error if P != true. BOOST_MPL_ASSERT(( P )) generates a compilation error if P::type::value != ...
193,703
193,752
How is tr1::reference_wrapper useful?
recently I've been reading through Scott Meyers's excellent Effective C++ book. In one of the last tips he covered some of the features from TR1 - I knew many of them via Boost. However, there was one that I definitely did NOT recognize: tr1::reference_wrapper. How and when would I use tr1::reference_wrapper?
It's like boost::ref, as far as I know. Basically, a reference which can be copied. Very useful when binding to functions where you need to pass parameters by reference. For example (using boost syntax): void Increment( int& iValue ) { iValue++; } int iVariable = 0; boost::function< void () > fIncrementMyVariable ...
193,708
193,742
What is a good use case for tr1::result_of?
I hear that tr1::result_of gets used frequently inside of Boost... I'm wondering if there are any good (simple) use cases for tr1::result_of I can use at home.
A description of result_of is given at open_std.org. Microsoft has a quick example of a unit test wrapper that uses result_of.
193,965
194,042
Are there any good open source BDD tools for C/C++?
I love the Ruby RSpec BDD development style. Are there any good tools for doing this with C/C++?
cspec is for C. Presumably it will work with C++. There is a list of tools for various languages on the Behavior Driven Development Wikipedia page.
194,465
11,354,496
How to parse a string to an int in C++?
What's the C++ way of parsing a string (given as char *) into an int? Robust and clear error handling is a plus (instead of returning zero).
In the new C++11 there are functions for that: stoi, stol, stoll, stoul and so on. int myNr = std::stoi(myString); It will throw an exception on conversion error. Even these new functions still have the same issue as noted by Dan: they will happily convert the string "11x" to integer "11". See more: http://en.cpprefer...
194,492
194,640
Accessing protected members from subclasses: gcc vs msvc
In visual C++, I can do things like this: template <class T> class A{ protected: T i; }; template <class T> class B : public A<T>{ T geti() {return i;} }; If I try to compile this in g++, I get an error. I have to do this: template <class T> class B : public A<T>{ T geti() {return A<T>::i;} }; Am I not ...
This used to be allowed, but changed in gcc 3.4. In a template definition, unqualified names will no longer find members of a dependent base (as specified by [temp.dep]/3 in the C++ standard). For example, template <typename T> struct B { int m; int n; int f (); int g (); }; int n; ...
194,499
194,509
How to paralleize search for a string in a file with a help of fork? (GNU Linux/g++)
I got a text file with a couple of lines and I am looking for a string in this file. I need to pass following command line parameters to the program: - file path - the string I am looking for - maximum number of processes the program is allowed to "fork" in order to complete this task. How to such a program should b...
A couple of thoughts. You will have to open the file separately from each process, otherwise they will share a single file descriptor and thus have a shared position in the file (or not, see the comments, as this may be system specific...). You may not see the speed increase you are hoping for due to disk access and/o...
194,676
194,741
What language/platform would you recommend for CPU-bound application?
I'm developing non-interactive cpu-bound application which does only computations, almost no IO. Currently it works too long and while I'm working on improving the algorithm, I also think if it can give any benefit to change language or platform. Currently it is C++ (no OOP so it is almost C) on windows compiled with I...
Just to be thorough: the first thing to do is to gather profile data and the second thing to do is consider your algorithms. I'm sure you know that, but they've got to be #included into any performance-programming discussion. To be direct about your question "Can switching to ASM help?" the answer is "If you don't know...
194,912
194,971
Any C++ libraries available to convert between floating point representations?
I recently had a need to interpret a DEC 32-bit floating point representation. It differs from the IEEE floating point representations in the number of bits allocated to the exponent and mantissa. Here's a description of a bunch of floating point formats: http://www.quadibloc.com/comp/cp0201.htm I managed to roll my o...
You mean like libvaxdata? I've never used it - I just found it by googling. But it looks like what you're looking for. It's a C library rather than C++, but converting floating point data should work fine from extern "C" calls.
195,207
195,209
Unresolved external symbol on static class members
Very simply put: I have a class that consists mostly of static public members, so I can group similar functions together that still have to be called from other classes/functions. Anyway, I have defined two static unsigned char variables in my class public scope, when I try to modify these values in the same class' con...
If you are using C++ 17 you can just use the inline specifier (see https://stackoverflow.com/a/11711082/55721) If using older versions of the C++ standard, you must add the definitions to match your declarations of X and Y unsigned char test::X; unsigned char test::Y; somewhere. You might want to also initialize a s...
195,323
195,350
What is the most elegant way to read a text file with c++?
I'd like to read whole content of a text file to a std::string object with c++. With Python, I can write: text = open("text.txt", "rt").read() It is very simple and elegant. I hate ugly stuff, so I'd like to know - what is the most elegant way to read a text file with C++? Thanks.
There are many ways, you pick which is the most elegant for you. Reading into char*: ifstream file ("file.txt", ios::in|ios::binary|ios::ate); if (file.is_open()) { file.seekg(0, ios::end); size = file.tellg(); char *contents = new char [size]; file.seekg (0, ios::beg); file.read (contents, size); ...
195,682
195,747
How do you mock classes that use RAII in c++
Here's my issue, I'd like to mock a class that creates a thread at initialization and closes it at destruction. There's no reason for my mock class to actually create and close threads. But, to mock a class, I have inherit from it. When I create a new instance of my mock class, the base classes constructor is called...
You instead make an interface that describes the type, and have both the real class and the mock class inherit from that. So if you had: class RAIIClass { public: RAIIClass(Foo* f); ~RAIIClass(); bool DoOperation(); private: ... }; You would make an interface like: class MockableInterface { public: Mocka...
195,714
196,248
Design: Large archive file editor, file mapping
I'm writing an editor for large archive files (see below) of 4GB+, in native&managed C++. For accessing the files, I'm using file mapping (see below) like any sane person. This is absolutely great for reading data, but a problem arises in actually editing the archive. File mapping does not allow resizing a file while i...
What I do is to close view handle(s) and FileMapping handle, set the file size then reopen mapping / view handles. // Open memory mapped file HANDLE FileHandle = ::CreateFileW(file_name, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); size_t Size = ::GetFileSize(FileHandle, 0); HANDLE MappingHandle ...
195,842
809,259
Capture which step of an animated system cursor is being shown on Windows
I want to capture as a bitmap the system cursor on Windows OSes as accurately as possible. The provided API for this is to my knowledge GetCursorInfo, DrawIconEx. The simple chain of actions is: Get cursor by using GetCursorInfo Paint the cursor in a memory DC by using DrawIconEx. Here is how the code looks roughly. ...
Unfortunately, I don't think there's a Windows API that discloses the current frame of the cursor animation. I assume that's what you're after: the look of the cursor at the instant you make the snapshot.
196,088
196,151
Coercing template class with operator T* when passing as T* argument of a function template
Assume I have a function template like this: template<class T> inline void doStuff(T* arr) { // stuff that needs to use sizeof(T) } Then in another .h filee I have a template class Foo that has: public: operator T*() const; Now, I realize that those are different Ts. But If I have a variable Foo<Bar> f on the stack...
GCC is correct. In template arguments only exact matches are considered, type conversions are not. This is because otherwise an infinite (or at least exponential) amount of conversions could have to be considered. If Foo<T> is the only other template that you're going to run in to, the best solution would be to add: te...
196,390
196,397
Can you write a block of c++ code inside C#?
I heard somewhere that you can drop down to C++ directly inside C# code. How is this done? Or did I hear wrong? Note: I do not mean C++ / CLI.
You might be thinking of unsafe blocks where you can write code that looks a lot like C++, since you can use pointers.
196,522
196,545
In C++ what are the benefits of using exceptions and try / catch instead of just returning an error code?
I've programmed C and C++ for a long time and so far I've never used exceptions and try / catch. What are the benefits of using that instead of just having functions return error codes?
Possibly an obvious point - a developer can ignore (or not be aware of) your return status and go on blissfully unaware that something failed. An exception needs to be acknowledged in some way - it can't be silently ignored without actively putting something in place to do so.
196,733
197,157
How can I use covariant return types with smart pointers?
I have code like this: class RetInterface {...} class Ret1: public RetInterface {...} class AInterface { public: virtual boost::shared_ptr<RetInterface> get_r() const = 0; ... }; class A1: public AInterface { public: boost::shared_ptr<Ret1> get_r() const {...} ... }; This code does not compi...
Firstly, this is indeed how it works in C++: the return type of a virtual function in a derived class must be the same as in the base class. There is the special exception that a function that returns a reference/pointer to some class X can be overridden by a function that returns a reference/pointer to a class that de...
197,048
198,063
Idiomatic use of std::auto_ptr or only use shared_ptr?
Now that shared_ptr is in tr1, what do you think should happen to the use of std::auto_ptr? They both have different use cases, but all use cases of auto_ptr can be solved with shared_ptr, too. Will you abandon auto_ptr or continue to use it in cases where you want to express explicitly that only one class has ownershi...
To provide a little more ammunition to the 'avoid std::auto_ptr' camp: auto_ptr is being deprecated in the next standard (C++0x). I think this alone is good enough ammunition for any argument to use something else. However, as Konrad Rudolph mentioned, the default replacement for auto_ptr should probably be boost::sc...
197,121
198,542
How do I write a for loop that iterates over a CAtlMap selectively deleting elements as it goes?
I'm trying to do the following without too much special case code to deal with invalidated POSITIONs etc: What's the best way to fill in the blanks? void DeleteUnreferencedRecords(CAtlMap<Record>& records) { for(____;____;____) { if( NotReferencedElsewhere(record) ) { // Delete record ...
According to this: http://msdn.microsoft.com/en-us/library/0h4c3zkw(VS.80).aspx RemoveAtPos has these semantics Removes the key/value pair stored at the specified position. The memory used to store the element is freed. The POSITION referenced by pos becomes invalid, and while the POSITION of any other elements in the...
197,135
207,796
Getting notifications when the user tries sending an SMS
My application is implemented as a service (running under services.exe). I am adding a new feature which requires being notified when the user sends an SMS. I have tried using IMAPIAdviseSink, registering with both IMAPISession and IMsgStore, but I do not get any notifications. The other options I can see are to create...
You can't use IMAPIAdviseSink from a service. You need to use it from separate process and notify the service of the events you're interested in.
197,140
197,251
What is the best implementation of STL for VS2005?
I'm currently using default implementation of STL for VS2005 and I'm not really satisfied with it. Perhaps there is something better?
The Dinkumware STL implementation (supplied with VS2005) is actually quite good. The STL is a general purpose library and so it is almost always possible to write something better for very specific use cases. I'm aware of the following alternative implementations, but I've never used them with VS2005: SGI Standard Temp...
197,211
197,478
Class design with vector as a private/public member?
what is the best way to put a container class or a some other class inside a class as private or a public member? Requirements: 1.Vector< someclass> inside my class 2.Add and count of vector is needed interface
If the container's state is part of the class's invariant, then it should, if possible, be private. For example, if the container represents a three dimensional vector then part of the invariant might be that it always contains exactly 3 numbers. Exposing it as a public member would allow code external to the class to...
197,258
197,273
Calling a static member function of a C++ STL container's value_type
I'm trying to get my head around why the following doesn't work. I have a std::vector and I want to call a static member function of it's contained value_type like so: std::vector<Vector> v; unsigned u = v.value_type::Dim(); where Vector is in fact a typedef for a templated type: template <typename T, unsigned U> clas...
You are accessing the value_type trough the variable instance and not the variable type. Method 1 - this works: typedef std::vector<Vector> MyVector; MyVector v; unsigned u = MyVector::value_type::Dim(); Method 2 - or this: std::vector<Vector> v; unsigned u = std::vector<Vector>::value_type::Dim(); If you typedef lik...
197,375
197,382
Visual c++ "for each" portability
I only just recently discovered that Visual C++ 2008 (and perhaps earlier versions as well?) supports for each syntax on stl lists et al to facilitate iteration. For example: list<Object> myList; for each (Object o in myList) { o.foo(); } I was very happy to discover it, but I'm concerned about portability for the ...
For each is not standard C or C++ syntax. If you want to be able to compile this code in gcc or g++, you will need to create an iterator and use a standard for loop. QuantumPete [edit] This seems to be a new feature introduced into MS Visual C++, so this is definitely not portable. Ref: http://msdn.microsoft.com/en-us/...
197,379
197,440
How do I create a symlink in Windows Vista?
I am looking to create symlinks (soft links) from Java on a Windows Vista/ 2008 machine. I'm happy with the idea that I need to call out to the JNI to do this. I am after help on the actual C code though. What is the appropriate system call to create the link? Pointers to some good documentation on this subject would b...
Symbolic links in Windows are created using the CreateSymbolicLink API Function, which takes parameters very similar to the command line arguments accepted by the Mklink command line utility. Assuming you're correctly referencing the JNI and Win32 SDK headers, your code could thus be as simple as: JNIEXPORT jboolean JN...
197,461
197,464
What is the difference between "VC++" and "C++"?
Someone asked me how familiar I am with VC++ and how familiar I am with C++. What is the difference?
C++ is the actual language, VC++ is Microsoft's Visual C++, an IDE for C++ development. From stason.org: C++ is the programming language, Visual C++ is Microsoft's implementation of it. When people talk about learning Visual C++, it usually has more to do with learning how to use the programming environment, and how t...
197,468
253,883
Does ATL/WTL still require the use of a global _Module variable?
I'm just starting up a new ATL/WTL project and I was wondering if the global _Module variable is still required? Back a few years when I started working with WTL it was required (at least for ATL 3.0) that you define a global variable such as: CAppModule _Module; To get ATL to work correctly. But recently I've read s...
Technically you do not need a global _Module instance since ATL/WTL version 7. Earlier ATL/WTL code referenced _Module by this specific name and expected you to declare a single instance of this object. This has since been replaced by a single instance object named _AtlBaseModule that is automatically declared for you ...
197,675
197,699
How does delete[] "know" the size of the operand array?
Foo* set = new Foo[100]; // ... delete [] set; You don't pass the array's boundaries to delete[]. But where is that information stored? Is it standardised?
When you allocate memory on the heap, your allocator will keep track of how much memory you have allocated. This is usually stored in a "head" segment just before the memory that you get allocated. That way when it's time to free the memory, the de-allocator knows exactly how much memory to free.
197,839
197,900
Determine the size of a C++ array programmatically?
This question was inspired by a similar question: How does delete[] “know” the size of the operand array? My question is a little different: Is there any way to determine the size of a C++ array programmatically? And if not, why? Every function I've seen that takes an array also requires an integer parameter to give...
delete [] does know the size that was allocated. However, that knowledge resides in the runtime or in the operating system's memory manager, meaning that it is not available to the compiler during compilation. And sizeof() is not a real function, it is actually evaluated to a constant by the compiler, which is someth...
197,983
197,989
What is a basic example of "low-level" multi-threading in C++?
I'm a kinda newbie developer with a few years under my belt. Recently I interviewed at a game company and was asked "have you done any multi-threading?" I told them about having a C# app with a few Threads... and then I said a bit about transactions and locking etc in Sql. The interviewer politely told me that this ...
The canonical implementation of "low level threads" is pthreads. The most basic examples of threading problems that are usually taught along with pthreads are some form of readers and writers problem. That page also links to more classical threading problems like producers/consumers and dining philosophers.
197,987
198,308
Multiple Interchangeable Views (MFC/C++)
I have a main frame with a splitter. On the left I have my (imaginatively named) CAppView_Leftand on the right I have CAppView_Right_1and CAppView_Right_2. Through the following code I initialise the two primary views correctly: if (!m_wndSplitter.CreateStatic(this, 1, 2)) { TRACE0("Failed to CreateStaticSplitter\n...
There is a CodeProject article that should help you achieve what you want: http://www.codeproject.com/KB/splitter/usefulsplitter.aspx I have replaced views in a splitter before, so if the above doesn't help I'll post some of my own code.
197,999
198,025
Need Advice on Implementing a Time-limited Trial
I'm developing a shareware desktop application. I'm to the point where I need to implement the trial-use/activation code. How do you approach something like this? I have my own ideas, but I want to see what the stackoverflow community thinks. I'm developing with C++/Qt. The intended platform is Windows/Mac/Linux. Thank...
What to protect against and what not to protect against: Keep in mind that people will always find a way to get around your trial period. So you want to make it annoying for the person to have to get around your trial period, but it doesn't matter if it's impossible to get around you trial period. Most people will t...
198,051
198,065
Why "delete [][]... multiDimensionalArray;" operator in C++ does not exist
I was always wondering if there is operator for deleting multi dimensional arrays in the standard C++ language. If we have created a pointer to a single dimensional array int *array = new int[size]; the delete looks like: delete [] array; That's great. But if we have two dimension array, we can not do delete [][] two...
Technically, there aren't two dimensional arrays in C++. What you're using as a two dimensional array is a one dimensional array with each element being a one dimensional array. Since it doesn't technically exist, C++ can't delete it.
198,071
198,162
Code for checking write-permissions for directories in Win2K/XP
Greetings! I am trying to check directory write-permissions from within a Windows MFC/ATL program using C++. My first guess is to use the C-standard _access function, e.g.: if (_access("C:\mydir", 2) == -1) // Directory is not writable. But apparently on Windows 2000 and XP, _access can't determine directory permis...
You can call CreateFile with GENERIC_WRITE access to check this. http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx It's not a C++ library but it still counts as elegant because it directly does what you want...
198,124
199,834
How can I get the path of a Windows "special folder" for a specific user?
Inside a service, what is the best way to determine a special folder path (e.g., "My Documents") for a specific user? SHGetFolderPath allows you to pass in a token, so I am assuming there is some way to impersonate the user whose folder you are interested in. Is there a way to do this based just on a username? If not, ...
I would mount the user's registry hive and look for the path value. Yes, it's a sub-optimal solution, for all the reasons mentioned (poor forwards compatibility, etc.). However, like many other things in Windows, MS didn't provide an API way to do what you want to do, so it's the best option available. You can get the ...
198,199
198,264
How do you reverse a string in place in C or C++?
How do you reverse a string in C or C++ without requiring a separate buffer to hold the reversed string?
The standard algorithm is to use pointers to the start / end, and walk them inward until they meet or cross in the middle. Swap as you go. Reverse ASCII string, i.e. a 0-terminated array where every character fits in 1 char. (Or other non-multibyte character sets). void strrev(char *head) { if (!head) return; ch...
198,625
200,260
Determine if IP is blocked
Does anyone know if it is possible to reliably determine (programattically C/C++...) whether or not a firewall or IP filtering software is installed on a Windows PC? I need to detect whether a certain server IP is being blocked in my client software by the host OS. I don't need to worry about external hardware firewal...
After reading some of your comments in reply to other answers, I think this might actually be closer to what you're looking for. It might not catch every type of firewall but any major firewall vendor should be registered with the Security Center and therefore detected with this method. You could also combine this with...
199,403
199,419
C++: What's the simplest way to read and write BMP files using C++ on Windows?
I would like to load a BMP file, do some operations on it in memory, and output a new BMP file using C++ on Windows (Win32 native). I am aware of ImageMagick and it's C++ binding Magick++, but I think it's an overkill for this project since I am currently not interested in other file formats or platforms. What would be...
When developing just for Windows I usually just use the ATL CImage class
199,418
199,422
Using C++ library in C code
I have a C++ library that provides various classes for managing data. I have the source code for the library. I want to extend the C++ API to support C function calls so that the library can be used with C code and C++ code at the same time. I'm using GNU tool chain (gcc, glibc, etc), so language and architecture supp...
Yes, this is certainly possible. You will need to write an interface layer in C++ that declares functions with extern "C": extern "C" int foo(char *bar) { return realFoo(std::string(bar)); } Then, you will call foo() from your C module, which will pass the call on to the realFoo() function which is implemented in ...
199,555
201,229
How would you go about implementing the game reversi? (othello)
I have been thinking about starting a side project at home to exercise my brain a bit. Reversi looks like a simply game, where mobility has a profound effect on game play. It is at least a step up from tic tac toe. This would be a single player against an AI of some sort. I am thinking to try this in C++ on a PC. W...
In overall, issues you will end up running onto will depend on you and your approaches. Friend tends to say that complex is simple from different perspective. Choice of graphics library depends about what kind of game you are going to write? OpenGL is common choice in this kind of projects, but you could also use some ...
199,606
199,618
How should C bitflag enumerations be translated into C++?
C++ is mostly a superset of C, but not always. In particular, while enumeration values in both C and C++ implicitly convert into int, the reverse isn't true: only in C do ints convert back into enumeration values. Thus, bitflags defined via enumeration declarations don't work correctly. Hence, this is OK in C, but not ...
Why not just cast the result back to a Foo? Foo x = Foo(Foo_First | Foo_Second); EDIT: I didn't understand the scope of your problem when I first answered this question. The above will work for doing a few spot fixes. For what you want to do, you will need to define a | operator that takes 2 Foo arguments and returns ...
199,627
199,911
Converting C source to C++
How would you go about converting a reasonably large (>300K), fairly mature C codebase to C++? The kind of C I have in mind is split into files roughly corresponding to modules (i.e. less granular than a typical OO class-based decomposition), using internal linkage in lieu private functions and data, and external linka...
Having just started on pretty much the same thing a few months ago (on a ten-year-old commercial project, originally written with the "C++ is nothing but C with smart structs" philosophy), I would suggest using the same strategy you'd use to eat an elephant: take it one bite at a time. :-) As much as possible, split it...
199,629
199,767
IDL declaration (in C++) for a function that will take a C-style array from C#
I am working with an existing code base made up of some COM interfaces written in C++ with a C# front end. There is some new functionality that needs to be added, so I'm having to modify the COM portions. In one particular case, I need to pass an array (allocated from C#) to the component to be filled. What I would lik...
Hmmm... I've found some information that gets me closer... Marshaling Changes - Conformant C-Style Arrays This IDL declaration (C++) HRESULT GetFoo([in] int bufferSize, [in, size_is(bufferSize)] int buffer[]); Is imported as (MSIL) method public hidebysig newslot virtual instance void GetFoo([in] int32 bufferSize, [in...
199,876
200,121
Setting Background Color CMDIFrameWnd
Is there a way to change the color of the background for a MDIParent windows in MFC (2005)? I have tried intercepting ON_WM_CTLCOLOR AND ON_WM_ERASEBKGND but neither work. OnEraseBkgnd does work, but then it gets overwritten by the standard WM_CTL color. Cheers
The CMDIFrameWnd is actually covered up by another window called the MDIClient window. Here is a Microsoft article on how to subclass this MDIClient window and change the background colour. I just tried it myself and it works great. http://support.microsoft.com/kb/129471
199,959
200,034
What is the equivalent of Thread.SetApartmentState in C++?
In C# there is a method SetApartmentState in the class Thread. How do I do the same thing in C++?
For unmanaged processes, you control the apartment model used for a thread by passing appropriate parameters to CoInitializeEx(). Larry Osterman wrote up a great little guide to these: ... When a thread calls CoInitializeEx (or CoInitialize), the thread tells COM which of the two apartment types it’s prepared ...
199,999
200,025
With scons, how do you link to prebuilt libraries?
I recently started using scons to build several small cross-platform projects. One of these projects needs to link against pre-built static libraries... how is this done? In make, I'd just append "link /LIBPATH:wherever libstxxl.lib" on windows, and "stxxl.a" on unix.
Just to document the answer, as I already located it myself. Program( 'foo', ['foo.cpp'], LIBS=['foo'], LIBPATH='.' ) Adding the LIBS & LIBPATH parameters add the correct arguments to the build command line. More information here.
200,032
200,054
Are C++ meta-templates required knowledge for programmers?
In my experience Meta-templates are really fun (when your compilers are compliant), and can give good performance boosts, and luckily I'm surrounded by seasoned C++ programmers that also grok meta-templates, however occasionally a new developer arrives and can't make heads or tails of some of the meta-template tricks w...
If you can you find enough candidates who really know template meta-programing then by all means, require it. You will be showing a lot of qualified and potentially productive people the door (there are plenty of legitimate reasons not to know how to do this, namely that if you do it on a lot of platforms, you will cr...
200,093
200,160
UTF usage in C++ code
What is the difference between UTF and UCS. What are the best ways to represent not European character sets (using UTF) in C++ strings. I would like to know your recommendations for: Internal representation inside the code For string manipulation at run-time For using the string for display purposes. Best storage r...
What is the difference between UTF and UCS. UCS encodings are fixed width, and are marked by how many bytes are used for each character. For example, UCS-2 requires 2 bytes per character. Characters with code points outside the available range can't be encoded in a UCS encoding. UTF encodings are variable width, and ...
200,237
200,425
Where can I learn more about C++0x?
I would like to learn more about C++0x. What are some good references and resources? Has anyone written a good book on the subject yet?
Articles on Lambda Expressions, The Type Traits Library, The rvalue Reference, Concepts, Variadic Templates, shared_ptr Regular Expressions Tuples Multi Threading General Discussion The C/C++ Users Journal, The New C++, Article Videos Google tech talk overview of various features overview at wikipedia Library Boost
200,550
200,645
Trapping messages in MFC - Whats the difference?
I was just wondering what (if any) the difference was between the following two message traps in MFC for the function, OnSize(..). 1 - Via Message map: BEGIN_MESSAGE_MAP(CClassWnd, CBaseClassWnd) ... ON_WM_SIZE() .. END_MESSAGE_MAP() 2 - Via afx_message: afx_msg type OnSize(...); They seem to be used interchangea...
Both parts are necessary to add a message handler to a class. The message map should be declared inside your class, together with declarations for any message handler functions (e.g, OnSize). class CClassWnd : public CBaseClassWnd { ... afx_msg void OnSize(UINT nType, int cx, int cy); DECLARE_MESSAGE_MAP };...
201,141
203,250
How to create a JNIEnv mock in C/C++
I am writing some JNI code in C that I wish to test using cunit. In order to call the JNI functions, I need to create a valid JNIEnv struct. Does anyone know if there is a mocking framework for such a purpose, or who can give me some pointers on how to create a mock JNIEnv struct myself?
jni.h contains the complete structure for JNIEnv_, including the "jump table" JNINativeInterface_. You could create your own JNINativeInterface_ (pointing to mock implementations) and instantiate a JNIEnv_ from it. Edit in response to comments: (I didn't look at the other SO question you referenced) #include "jni.h" #...
201,593
201,795
Is there a simple way to convert C++ enum to string?
Suppose we have some named enums: enum MyEnum { FOO, BAR = 0x50 }; What I googled for is a script (any language) that scans all the headers in my project and generates a header with one function per enum. char* enum_to_string(MyEnum t); And a implementation with something like this: char* enum_to_string(M...
You may want to check out GCCXML. Running GCCXML on your sample code produces: <GCC_XML> <Namespace id="_1" name="::" members="_3 " mangled="_Z2::"/> <Namespace id="_2" name="std" context="_1" members="" mangled="_Z3std"/> <Enumeration id="_3" name="MyEnum" context="_1" location="f0:1" file="f0" line="1"> <En...
201,940
201,998
can realloc Array, then Why use pointers?
This was an job placement interview I faced. They asked whether we can realloc Array, I told yes. Then They asked - then why we need pointers as most of the people give reason that it wastes memory space. I could not able to give satisfactory answer. If any body can give any satisfactory answer, I'll be obliged. Please...
You can only reallocate an array that was allocated dynamically. If it was allocated statically, it cannot be reallocated [safely].* Pointers hold addresses of data in memory. They can be allocated, deallocated, and reallocated dynamically using the new/delete operators in C++ and malloc/free in C. I would strongly sug...
202,007
581,579
Creating Docking Panes in CView instead of CMainFrame
When creating an MDI Application with "Visual Studio" style using the AppWizard of VS2008 (plus Feature Pack), the CMainFrame class gets a method CreateDockingWindows(). Since I don't want all panes to be always visible but display them depending on the type of the active document, I made those windows to members of my...
The following solution turned out to work pretty well for me. The MainFrame still owns all the panes thus keeping all the existing framework-functionality. I derive the panes from a class which implements the "CView-like" behavior I need: /** * \brief Mimics some of the behavior of a CView * * CDockablePane derived ...
202,549
202,943
Parsing iCal/vCal/Google calendar files in C++
Can anyone recommend a ready-to-use class/library compatible with C/C++/MFC/ATL that would parse iCal/vCal/Google calendar files (with recurrences)? It can be free or commercial.
there is a parser in PHP for iCal, you can downloaded and check the code to suit your language. for vCal/vCard parsing there's a C Library. for Google Calendar I couldn't find any exact answer, so, try to Google it.
202,718
202,738
Can the result of a function call be used as a default parameter value?
Is there a good method for writing C / C++ function headers with default parameters that are function calls? I have some header with the function: int foo(int x, int y = 0); I am working in a large code base where many functions call this function and depend on this default value. This default value now needs to chan...
Go figure! It does work. Default arguments in C++ functions
203,126
203,136
How does the C++ compiler know which implementation of a virtual function to call?
Here is an example of polymorphism from http://www.cplusplus.com/doc/tutorial/polymorphism.html (edited for readability): // abstract base class #include <iostream> using namespace std; class Polygon { protected: int width; int height; public: void set_values(int a, int b) { width = a; ...
Each object (that belongs to a class with at least one virtual function) has a pointer, called a vptr. It points to the vtbl of its actual class (which each class with virtual functions has at least one of; possibly more than one for some multiple-inheritance scenarios). The vtbl contains a bunch of pointers, one for e...
203,548
203,550
Undefined Symbol ___gxx_personality_v0 on link
I've been getting this undefined symbol building with this command line: $ gcc test.cpp Undefined symbols: "___gxx_personality_v0", referenced from: etc... test.cpp is simple and should build fine. What is the deal?
Use g++ test.cpp instead, since this is c++ code. Or, if you really want to use gcc, add -lstdc++ to the command line, like so: gcc test.cpp -lstdc++ Running md5 against the a.out produced under each scenario shows that it's the same output. But, yeah, g++ probably makes your world a simpler place.
203,616
203,655
Why does C# not provide the C++ style 'friend' keyword?
The C++ friend keyword allows a class A to designate class B as its friend. This allows Class B to access the private/protected members of class A. I've never read anything as to why this was left out of C# (and VB.NET). Most answers to this earlier StackOverflow question seem to be saying it is a useful part of C++ a...
Having friends in programming is more-or-less considered "dirty" and easy to abuse. It breaks the relationships between classes and undermines some fundamental attributes of an OO language. That being said, it is a nice feature and I've used it plenty of times myself in C++; and would like to use it in C# too. But I be...
203,667
203,703
C++ "Named Parameter Idiom" vs. Boost::Parameter library
I've looked at both the Named Parameter Idiom and the Boost::Parameter library. What advantages does each one have over the other? Is there a good reason to always choose one over the other, or might each of them be better than the other in some situations (and if so, what situations)?
Implementing the Named Parameter Idiom is really easy, almost about as easy as using Boost::Parameter, so it kind of boils down to one main point. -Do you already have boost dependencies? If you don't, Boost::parameter isn't special enough to merit adding the dependency. Personally I've never seen Boost::parameter in p...
203,823
203,830
C++ headers - separation between interface and implementation details
One of classes in my program uses some third-party library. Library object is a private member of my class: // My.h #include <3pheader.h> class My { ... private: 3pObject m_object; } The problem with this - any other unit in my program that uses My class should be configured to include...
Use the "pimpl" idiom: // header class My { class impl; std::auto_ptr<impl> _impl; }; // cpp #include <3pheader.h> class My::impl { 3pObject _object; };
203,847
204,374
Fast library to replace CDC vector graphics
I have a mature MFC C++ application that displays on screen and prints using CDC wrappings on the Win32 GDI. While it has been optimized over the years, I would like to replace it with something a bit faster. The graphics included rendered triangular surface models, complex polylines and polygons, and lots of text. ...
I have once evaluated FastGraph (http://www.fastgraph.com) for a project. I liked it in the small test programs I wrote, it was very fast. We ended up not using it for external reasons (nothing to do with the libraries that I evaluated) so I don't have more practical experience.
203,899
204,342
Use Compiler/Linker for C++ Code Clean-up
I'm using VS2008 for a C++ project. The code is quite old and has passed through many hands. There are several classes hierarchies, functions, enums and so on which are no longer being used. Is there a way to get the compiler/linker to list out identifiers which have been declared or defined but are not being referred ...
PC-Lint "whole project" analysis (which analyses multiple files together) can do this. Please feel free to contact me if you need help setting it up.
203,990
205,417
How to manage a simple PHP session using C++ cURL (libcurl)
I'm writing a C++ client which is using libcurl for communicating with a PHP script. The communication should be session based, and thus the first task is to login and make the PHP script set up a session. I'm not used to working with sessions either from C++ or PHP. I basically know that it has to do with cookies and ...
As far as I understand it, CURL will handle session cookies automatically for you if you enable cookies, as long as you reuse your CURL handle for each request in the session: CURL *Handle = curl_easy_init(); // Read cookies from a previous session, as stored in MyCookieFileName. curl_easy_setopt( Handle, CURLOPT_COOK...
204,167
215,834
How to get folder sharing on Windows Mobile emulator to work
I am developing an application using Windows Mobile 5.0, under embedded VC++ 4.0, and using the emulator for debugging. I need to copy some files onto the emulator and planned on using the option to map a directory to the emulator storage card. Problem is, this option is greyed out when I run the emulator. From the e...
I have the WinMo 5.0 SDK installed on Visual Studio 2005 and the option to map a directory works fine for me. I'd guess it's an issue related to eVC, which is pretty old by now. My recommendation is to try VS 2005 or 2008, there's a free 90-day trial you can download from microsoft: http://msdn.microsoft.com/en-us/vstu...
204,345
204,353
How to setup a linux C++ project in Eclipse?
I have an existing C++ project on a linux environment, and would like to import it into the Eclipse IDE. Not sure if I should start a new Eclipse C++ project, or if there was some way to import the source files?
You can create a new Eclipse C++ project "in-place", i.e. if you have your sources checked out at /home/joe/mysources, you can select that directory in the new project wizard (uncheck the "use default location" checkbox first). All your source files will show up in the Eclipse project.
204,360
204,364
What's the term for design ala "object.method1().method2().method3()"?
What's the term for this design? object.method1().method2().method3() ..when all methods return *this? I found the term for this a while ago, but lost it meanwhile. I have no clue how to search for this on google :) Also if anyone can think of a better title for the question, feel free to change it. Thanks Update-Gish...
Looks to me like you are describing a fluent interface. Ive also heard it referred to as pipelineing or chaining. Update-Gishu: http://martinfowler.com/bliki/FluentInterface.html
204,476
204,483
What should main() return in C and C++?
What is the correct (most efficient) way to define the main() function in C and C++ — int main() or void main() — and why? And how about the arguments? If int main() then return 1 or return 0? There are numerous duplicates of this question, including: What are the valid signatures for C's main() function? The return ...
The return value for main indicates how the program exited. Normal exit is represented by a 0 return value from main. Abnormal exit is signaled by a non-zero return, but there is no standard for how non-zero codes are interpreted. As noted by others, void main() is prohibited by the C++ standard and should not be used....
204,576
204,662
Splitting a already split pane (MFC)
In my MFC program I am using a splitter to create two panes. I now want to split one of these panes in half again and put in another view, can someone talk me through how to do it or point me in the direction of some code? I would prefer to code it myself so I am not interested in custom derived classes unless they are...
In CMainFrame::OnCreateClient // Create splitter with 2 rows and 1 col m_wndSplitter.CreateStatic(this, 2, 1); // Create a view in the top row m_wndSplitter.CreateView(0, 0, RUNTIME_CLASS(CView1), CSize(100, 100), pContext); // Create a 2 column splitter that will go in the bottom row of the first m_wndSplitter2.Create...
204,606
204,712
Undefined behavior when exceed 64 bits
In my current 32-bit application, I check (very occasionally) for overflow by doing operations on 64-bit integers. However, on 64-bit systems there does not seem to be a standard 128-bit integer. Is there a simple way of checking for overflow, or a way of getting 128-bit integers, which works on all OSes and compilers?...
Much of the discussion in this question applies: How to detect integer overflow? Many of the techniques used for 32-bit overflow chacking apply to 64-bits as well (not all of the techniques discussed use the next larger integer type to handle the overflow).
204,683
205,034
How do I input 4-byte UTF-8 characters?
I am writing a small app which I need to test with utf-8 characters of different number of byte lengths. I can input unicode characters to test that are encoded in utf-8 with 1,2 and 3 bytes just fine by doing, for example: string in = "pi = \u3a0"; But how do I get a unicode character that is encoded with 4-bytes? I ...
There's a longer form of escape in the pattern \U followed by eight digits, rather than \u followed by four digits. This is also used in Java and Python, amongst others: >>> '\xf0\x90\x84\x82'.decode("UTF-8") u'\U00010102' However, if you are using byte strings, why not just escape each byte like above, rather than re...
204,841
204,959
Where can I look at the C++ standard
Possible Duplicate: Where do I find the current C or C++ standard documents? I want to use STL with the current program I'm working on and the vendor doesn't support what I feel is a reasonable STL, working is not my idea of reasonable. I have been unable to find a C++ Standard or an STL standard that is not just a...
Information on where to get the current standard document: Where do I find the current C or C++ standard documents? Other responses in that question have information on downloads of various drafts of the standards which can be obtained free (the actual ratified standards cannot be obtained free).
204,983
205,000
static const Member Value vs. Member enum : Which Method is Better & Why?
If you want to associate some constant value with a class, here are two ways to accomplish the same goal: class Foo { public: static const size_t Life = 42; }; class Bar { public: enum {Life = 42}; }; Syntactically and semantically they appear to be identical from the client's point of view: size_t fooLife = ...
The enum hack used to be necessary because many compilers didn't support in-place initialization of the value. Since this is no longer an issue, go for the other option. Modern compilers are also capable of optimizing this constant so that no storage space is required for it. The only reason for not using the static co...
205,059
205,083
Is there a C++ decompiler?
I have a program in which I've lost the C++ source code. Are there any good C++ decompilers out there? I've already ran across Boomerang.
You can use IDA Pro by Hex-Rays. You will usually not get good C++ out of a binary unless you compiled in debugging information. Prepare to spend a lot of manual labor reversing the code. If you didn't strip the binaries there is some hope as IDA Pro can produce C-alike code for you to work with. Usually it is very rou...
205,127
206,352
CMapStringToOb::Lookup Won't Work with Japanese Characters
Does anyone know why CMapStringToOb::Lookup doesn't work in Japanese? The code loads a string from the string table, and puts it into a CMapStringToOb object. Later it loads the same string from the string table (so it is guaranteed to be exactly the same) and calls CMapStringToOb::Lookup to find it. It works in all ...
Is your app Unicode or MBCS? Not that I would have an explanation in one of those cases. Just trying to narrow down the scope.
205,270
785,307
ActiveX plugin causes ASSERT to fail on application exit in VS2008
My MFC application using the "ESRI MapObjects LT2" ActiveX plugin throws an ASSERT at me when closing it. The error occurs in cmdtarg.cpp: CCmdTarget::~CCmdTarget() { #ifndef _AFX_NO_OLE_SUPPORT if (m_xDispatch.m_vtbl != 0) ((COleDispatchImpl*)&m_xDispatch)->Disconnect(); ASSERT(m_dwRef <= 1); //<--- Fa...
The following solved it for me: In the window that contains the control, add an OnDestroy() handler: void CMyWnd::OnDestroy() { // Apparently we have to disconnect the (ActiveX) Map control manually // with this undocumented method. COleControlSite* pSite = GetOleControlSite(MY_DIALOG_CONTROL_ID); if(NU...
205,945
205,985
Why does the C++ STL not provide any "tree" containers?
Why does the C++ STL not provide any "tree" containers, and what's the best thing to use instead? I want to store a hierarchy of objects as a tree, rather than use a tree as a performance enhancement...
There are two reasons you could want to use a tree: You want to mirror the problem using a tree-like structure: For this we have boost graph library Or you want a container that has tree like access characteristics For this we have std::map (and std::multimap) std::set (and std::multiset) Basically the characteristic...
206,045
206,054
How do you mark a struct template as friend?
I have code like this: template <typename T, typename U> struct MyStruct { T aType; U anotherType; }; class IWantToBeFriendsWithMyStruct { friend struct MyStruct; //what is the correct syntax here ? }; What is the correct syntax to give friendship to the template ?
class IWantToBeFriendsWithMyStruct { template <typename T, typename U> friend struct MyStruct; }; Works in VS2008, and allows MyStruct to access the class.
206,106
206,200
Is !! a safe way to convert to bool in C++?
[This question is related to but not the same as this one.] If I try to use values of certain types as boolean expressions, I get a warning. Rather than suppress the warning, I sometimes use the ternary operator (?:) to convert to a bool. Using two not operators (!!) seems to do the same thing. Here's what I mean: ty...
The argument of the ! operator and the first argument of the ternary operator are both implicitly converted to bool, so !! and ?: are IMO silly redundant decorations of the cast. I vote for b = (t != 0); No implicit conversions.
206,172
206,300
How do you programmatically determine whether a Windows computer is a member of a domain?
I need a way to determine whether the computer running my program is joined to any domain. It doesn't matter what specific domain it is part of, just whether it is connected to anything. I'm coding in vc++ against the Win32 API.
Straight from Microsoft: How To Determine If a Windows NT/Windows 2000 Computer Is a Domain Member This approach uses the Windows API. From the article summary: This article describes how to determine if a computer that is running Windows NT 4.0 or Windows 2000 is a member of a domain, is a member of a workgr...
206,257
206,308
Freeing memory allocated to an array of void pointers
I am declaring an array of void pointers. Each of which points to a value of arbitary type. void **values; // Array of void pointers to each value of arbitary type Initializing values as follows: values = (void**)calloc(3,sizeof(void*)); //can initialize values as: values = new void* [3]; int ival =...
You have 3 things that are dynamically allocated that need to be freed in 2 different ways: delete reinterpret_cast<int*>( values[0]); delete reinterpret_cast<float*>( values[1]); free( values); // I'm not sure why this would have failed in your example, // but it would have leaked the 2 items t...
206,272
206,279
Hiding private data members? (C++)
Is there a way to hide private data members of a C++ class away from its users, in the cpp file? I think of the private members as part of the implementation and it seems a little backwards to declare them in the header file.
The "pimpl" idiom is how this is generally handled. See http://www.gotw.ca/gotw/024.htm http://www.gotw.ca/gotw/028.htm http://herbsutter.com/gotw/_100/ (updated for C++11)
206,498
206,533
need access to Class Object via Function Pointer - Binary Search Tree Class Creation Related
Creating Traversals for Binary Search Tree with Recursion. void inOrder(void (*inOrderPtr)(T&)) { if(this->left != NULL) inOrder((*inOrderPtr)(this->left)); inOrderPtr(this->data); if(this->right != NULL) inOrder((*inOrderPtr)(this->right)); } Here is the function. Now this is ob...
It looks like the call to inOrderPtr(this->data) is passing just the data member of the tree node to the print_vals function. If you would like to access the left and right elements, use inOrderPtr(*this). You will have to change various declarations in order for this to compile, such as the declarations for inOrderPtr...
206,564
206,639
What is the performance implication of converting to bool in C++?
[This question is related to but not the same as this one.] My compiler warns about implicitly converting or casting certain types to bool whereas explicit conversions do not produce a warning: long t = 0; bool b = false; b = t; // performance warning: forcing long to bool b = (bool)t; /...
I was puzzled by this behaviour, until I found this link: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=99633 Apparently, coming from the Microsoft Developer who "owns" this warning: This warning is surprisingly helpful, and found a bug in my code just yesterday. I think Martin i...
206,811
206,889
Code standard refactoring on large codebase
My studio has a large codebase that has been developed over 10+ years. The coding standards that we started with were developed with few developers in house and long before we had to worry about any kind of standards related to C++. Recently, we started a small R&D project in house and we updated our coding convention...
My process would be to rename each time someone touches a given module. Eventually, all modules would be refactored, but the incremental approach would result in less code breakage(assuming you have a complete set of tests. ;) )
206,857
206,926
How to implement blocking read using POSIX threads
I would like to implement a producer/consumer scenario that obeys interfaces that are roughly: class Consumer { private: vector<char> read(size_t n) { // If the internal buffer has `n` elements, then dequeue them // Otherwise wait for more data and try again } public: void run() { re...
This code is not production ready. No error checking is done on the results of any library calls. I have wrapped the lock/unlock of the mutex in LockThread so it is exception safe. But that's about it. In addition if I was doing this seriously I would wrap the mutex and condition variables inside objects so they can co...
206,998
207,004
What does "const class" mean?
After some find and replace refactoring I ended up with this gem: const class A { }; What does "const class" mean? It seems to compile ok.
What does "const class" mean? It seems to compile ok. Not for me it doesn't. I think your compiler's just being polite and ignoring it. Edit: Yep, VC++ silently ignores the const, GCC complains.
207,069
281,253
How to link using GCC without -l nor hardcoding path for a library that does not follow the libNAME.so naming convention?
I have a shared library that I wish to link an executable against using GCC. The shared library has a nonstandard name not of the form libNAME.so, so I can not use the usual -l option. (It happens to also be a Python extension, and so has no 'lib' prefix.) I am able to pass the path to the library file directly to the ...
There is the ":" prefix that allows you to give different names to your libraries. If you use g++ -o build/bin/myapp -l:_mylib.so other_source_files should search your path for the _mylib.so.
207,312
207,325
C++ Recursive Traversals with Function Pointers
template <class T> void BT<T>::inOrder(void (*inOrderPtr)(T&)) { inOrderPtr(inOrder(this->root)); } template <class T> void BT<T>::inOrder(Node<T>* root) const { if (root->left != NULL) inOrder(root->left); //something here if (root->right != NULL) inOrder(root->right); } Ok I am ...
This is how to do it properly, but Node::GetItem needs implementing in order for this to be 100% correct: template <class T> T& Node<T>::GetItem() const { // TODO - implement getting a T& from a Node<T> return m_item; // possible implementation depending on Node's definition } template <class T> void BT<T>::...
207,496
207,503
C++ Binary Search Tree Insert via Recursion
So my code is below. I'm not getting any errors and it places everything in the node just fine. But based on my debug statements Everytime anything is inserted it's finding the root. I'm not sure if that is right. But according to output file for the assignment, my answers are different when it comes to the height ...
You need to change the wording of your debug statements Really it should read (not Root node) cout << "Leaf Node Found" << newNode->data << endl; It is only the root when it is first called after that any call with node->left or node->right makes it an intermediate node. To write height() I would do this: template <c...
207,662
207,711
Writing utf16 to file in binary mode
I'm trying to write a wstring to file with ofstream in binary mode, but I think I'm doing something wrong. This is what I've tried: ofstream outFile("test.txt", std::ios::out | std::ios::binary); wstring hello = L"hello"; outFile.write((char *) hello.c_str(), hello.length() * sizeof(wchar_t)); outFile.close(); Opening...
I suspect that sizeof(wchar_t) is 4 in your environment - i.e. it's writing out UTF-32/UCS-4 instead of UTF-16. That's certainly what the hex dump looks like. That's easy enough to test (just print out sizeof(wchar_t)) but I'm pretty sure it's what's going on. To go from a UTF-32 wstring to UTF-16 you'll need to apply ...
207,730
207,743
Templated superclass linking problem
I'm trying to create a C++ class, with a templated superclass. The idea being, I can easily create lots of similar subclasses from a number of superclasses which have similar characteristics. I have distilled the problematic code as follows: template_test.h: template<class BaseClass> class Templated : public BaseClass ...
With templated classes, the definitions must be available for each translation unit that uses it. The definitions can go in a separate file, usually with .inl or .tcc extension; the header file #includes that file at the bottom. Thus, even though it's in a separate file, it's still #included for each translation unit; ...
207,768
207,777
How to fill a vector with non-trivial initial values?
I know how to fill an std::vector with non-trivial initial values, e.g. sequence numbers: void IndexArray( unsigned int length, std::vector<unsigned int>& v ) { v.resize(length); for ( unsigned int i = 0; i < length; ++i ) { v[i] = i; } } But this is a for-loop. Is there an elegant way to do th...
You can use the generate algorithm, for a more general way of filling up containers: #include <iostream> #include <algorithm> #include <vector> struct c_unique { int current; c_unique() {current=0;} int operator()() {return ++current;} } UniqueNumber; int main () { vector<int> myvector (8); generate (my...