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
3,108,384
3,109,747
c++ static library is too big, why?
This is what I'm doing (this is an example, not a real-life syntax): $ svn co http://svn.boost.org/svn/boost/trunk/libs/regex/src regex $ c++ -o regex/*.obj -c regex/*.cpp I have 17 *.obj files in regex. Now I'm trying to create a static library from them: $ ar -r regex.lib regex/*.obj The size of the library is 10Mb. Is it a correct size? Should it be that big with just 17 C++ files? I have a filling that this library contains duplicated symbols. Many of them.. Thanks in advance for some hint.
You can't predict the size of the output from the number of source files. A file could contain a dozen lines of simple code, or thousands of lines of spaghetti, or a vast data table. Object files (and static libraries, which are just collections of object files) contain metadata used for linking, which can be removed from the final executable. They may also contain a large amount of debugging information, if the compiler was configured to generate that. You're building with no optimisation, which will usually bloat the code quite a bit. Inline functions will appear in every object file that uses them; linking will resolve these duplicates, but simply lumping the objects together with ar won't. I just did the same experiment: I got 3.5Mb rather than 10Mb to start with; adding debug information (-g) increased it to 8Mb; enabling optimisation (-O3) reduced it to 1.6Mb, about the same size as the version installed on my computer. The dynamic library installed on my computer (generated with a linker, not ar), is smaller still, about 666kb. But why are you worrying about the size of the library? Are you planning to distribute a product as a precompiled static library? On floppy disks? Are you trying to develop on an Amiga 500? If you're developing for a limited platform, then worry about the size and runtime footprint of the final executables.
3,108,415
3,108,755
Making C++ COM classes more test-friendly
Our code-base has a lot of COM objects, so typically we'll have something like: //this is the IDL-generated IGetTime interface header #include "gettime.h" //our COM class implementation of IGetTime class CGetTime : public IGetTime { public: CGetTime(CGetTimeCF &factory,...); //COM-specific constructor params /* IUnknown */ STDMETHODIMP QueryInterface(REFIID riid, LPVOID FAR * ppv); STDMETHODIMP_(ULONG) AddRef(); STDMETHODIMP_(ULONG) Release(); /* IGetTime */ STDMETHODIMP GetTheTime(); // }; The way the constructor and a few other things are set up, this class is only easily usable through COM... you can hack a way to create the object but it tends to be flaky. I many cases though, the actual functionality of the class might be usable without COM... and this would also be more easily testable if you could do new CGetTime(); I wondered about having something like this as a pattern: class CGetTimeBase { public: STDMETHODIMP GetTheTime(); }; class CGetTime : public IGetTime, public CGetTimeBase { ... }; Is this a good approach, or is there a better way to have a 'plain C++' class providing the core functionality, and a COM class doing the COM stuff? To minimise amount of code to write I'd rather not introduce wrapper methods, I think, but have the actual implementation method in the non-COM class so it's automatically present in the COM class. Thoughts? };
Where I work, we chose to separate core C++ classes from the COM ones for several reasons: This is easier to maintain. People that don't know COM much can focus on writing core classes and people who do know COM can safely wrap the core classes, without caring about the underlying implementation. Code reusability. This might not be a requirement for you, but since the core classes are decoupled from the COM ones, we case use them directly in C++ projects, where COM is not needed. Core testing. Since the logic is separated from the interface, you can proceed to minimal tests easily. You no longer wonder: "Where is my leak ? Is it a legitimate leak in my core logic or something related to COM?" Core classes can be tested independently and efficiently. This increases both the number of files and the compilation time, but I (we) think it worth it.
3,108,454
3,108,506
Validation For Phone Number and Mobile Number
I need a c,c++ code for validating a Phone Number(8 Digits- Starting with 2) and Mobile Number(10 Digits- Starts with 9). Also it should not allow to enter any space, special charcter, as well as charcters. Here user can enter either phone number or mobile number. Plese Help in this, Thanks,
Here's the code: bool is_valid_number(const std::string& number) { static const std::string AllowedChars = "0123456789"; for(auto numberChar = number.begin(); numberChar != number.end(); ++numberChar) if(AllowedChars.end() == std::find( AllowedChars.begin(), AllowedChars.end(), *numberChar)) { return false; } return true; } // client code std::string number = "091283019823"; bool isMobileNumber = is_valid_number(number) && number.size() == 10 && number[0] == '9'; bool isLandLineNumber = false; // left as an exercise to the reader ;) The function is_valid_number could be improved to work on iterators instead of strings, or written as a functor on a single char and used with std::find_if to write the whole thing as a one-liner.
3,108,455
3,108,672
Virtual methods make the application slower, but can they speed up the linking?
As described in Virtual functions and performance - C++ virtual methods may have an impact on performance (extra lookup in vtable, no inlining, ...). But I was wondering, could the use of virtual functions speed up the linking process? Suppose that I have a class X, calling a method of class Y. If the method is a non-virtual method, then the compiler has to look up the method in class Y to see whether it is valid, and how the call should be translated to assembly the linker has to find the method in class Y and replace the call address in the compiler-generated assembly by the address of the called method. If the method is a virtual method, then the compiler will also have to look up the method in class Y, and has to look up the vtable of class Y to construct the call (using the offset in the vtable) the linker has to do nothing anymore It seems to me that when using virtual methods, the linker doesn't have to do much anymore, and therefore it will be faster (although I think the difference will be small). Is this true? Does someone have experience with this? Was this ever tested?
I don't get it, doesn't the compiler go through the exact same process with virtual calls as non virtual calls only it has to look up where the method would be in the virtual table (as well as hold the virtual table in memory thus ruining locality) and handle generating code for the indirect call also? If anything, virtual calls slow down compilation time.
3,108,472
3,108,553
How to cast an int variable to char in C++?
char a[3]; int x=9; int y=8; a[0]=(char)x; a[1]=(char)y; a[2]='\0'; unsigned char * temp=(unsigned char*)a; but when i am displaying this temp, it's displaying ?8. should display 98. can anyone please help???
char a[3]; int x='9'; int y='8'; a[0]=(char)x; a[1]=(char)y; a[2]='\0'; unsigned char * temp=(unsigned char*)a; printf("%s", temp); You were giving a value of 9 and 8, instead of their ASCII values.
3,108,478
3,108,502
Synchronize system clock with UTC time using C uder Window OS
I have UTC time which is coming from UDP, I have a program to calculate Day and Time of UTC, how can I set my system clock at that day and time, kindly give me some direction so that I can make it possible. I am using Window OS.
To set the current system time, use the SetSystemTime Win32 API function.
3,108,536
3,110,077
Good cross platform functional language for library use in a C++ application?
What are my options in terms of a fast functional language for library use in a cross-platform Qt C++ application? It seems almost all languages (functional or not) have some way of calling C/C++ code in an easy manner. I'd like to go the other way around - write an application in Qt using C++ for stateful business logic, GUIs and stuff but drop down and use a functional language for the core calculation library. Which ones are easy to use in this manner? Can for instance OCaml code be compiled into a static library and then consumed by a C++ app? Thanks, Rickard
Haskell has this capability, though the interaction with Qt/qmake and your build process with ghc may take a little trickery to get working: http://www.haskell.org/haskellwiki/Calling_Haskell_from_C There is also a project called HaskellDirect which seems similar to your purpose as well: http://www.haskell.org/hdirect/
3,108,631
3,108,762
How to pass a pointer to a member function to a C function?
Possible Duplicate: Using a C++ class member function as a C callback function I'm writing an object-oriented library using a C library (winpcap). I need to pass the callback function that is called when a network packet arrives as a function pointer. I would like to pass a member function pointer to winpcap, to keep my design object oriented and to allow for different objects to receive different packets. However member functions as far as I understand have a different calling convention, and thus cannot be passed to a C function. Is there a way to fix this. My experiments with boost::bind (which I hardly manage to use other than trial and error) are not fruitful. Is there a way to change the calling convention of a member function? This is the definition of the callback function I use now and the actual passing of it to winpcap void pcapCallback( byte* param, const struct pcap_pkthdr* header, const byte* pkt_data ); pcap_loop( adhandle, 0, pcapCallback, NULL ); The pcap_loop just takes the name of the function (which is on the global scope at the moment). This is the definition of the function pointer parameter (3rd parameter of pcap_loop). Since this is third party code I can't really change this. I would have to have a member function that can take this form: typedef void (*pcap_handler)(u_char *, const struct pcap_pkthdr *, const u_char *); As far as I understand it, the member function will be using thiscall and the c function pointer wants a cdecl
Kindly refer to detailed topic about How to Implement a Callback to a static C++ Member Function ? How to Implement a Callback to a non-static C++ Member Function ? http://www.newty.de/fpt/callback.html
3,108,965
3,109,021
Error: Cannot add two pointers
It gives the error in the title about this piece of code: string DDateTime::date2OracleDate(DATE Date) { string s; s="TO_DATE('" + DateFormat("%d/%m/%Y",Date) + "','dd/MM/YYYY')"; return s; } I don't understand how that is possible, no pointers involved.... EDIT: string DDateTime::DateFormat(string sFormat,DATE Date) { struct tm tmTemp; RipOf_AfxTmFromOleDate(Date, tmTemp); RipOf_AfxTmConvertToStandardFormat(tmTemp); char sFormatted[MAX_TIME_BUFFER_SIZE]; strftime(sFormatted, MAX_TIME_BUFFER_SIZE, sFormat.c_str(), &tmTemp); return sFormatted; }
The following should work better: string DDateTime::date2OracleDate(DATE Date) { string s = "TO_DATE('"; s += DateFormat("%d/%m/%Y",Date); s += "','dd/MM/YYYY')"; return s; }
3,109,134
3,109,160
What should the following code do and with explanations
class A { public: A() { } ~A() { cout << "A Destructor \n" ; } }; class B :public A{ public: B() { } virtual ~B() { cout << "B Destructor \n" ; } }; class C : public B { public: C() { } ~C() { cout << "C Destructor \n"; } }; int main() { A *pointA = new A; A *pointB = new B; A *pointC = new C; delete pointA; delete pointB; delete pointC; }
It will invoke undefined behavior at the second (and third) delete, because A's destructor is not virtual. §5.3.5/3: if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined. If you make the destructor of A virtual, you get well-defined behavior, and the destructor of the dynamic type is called. (And each of those in turn calls the base destructor.) Your output would be: A destructor B destructor A destructor C destructor B destructor A destructor For what it's worth, when you're that close to a compilable snippet, you should leave the includes. Also, just use struct instead of class to be concise about the public stuff, and leave out empty constructors.
3,109,387
3,109,514
Undefined references when compiling a static Qt build on Windows
I'd like to compile a static version of the Qt toolkit on the Windows platform (Windows XP SP3). I downloaded the latest release for Windows and successfully installed it. Then I opened the Qt 4.6.3 Command Prompt from the Start menu and invoked: configure -static -release -nomake examples -nomake demos -fast Configuration executes fine, and the first part of mingw32-make as well. At some point I get a lot of undefined references: mingw32-make[4]: Entering directory `C:/Qt-static/4.6.3/src/tools/moc' g++ -c -O2 -frtti -fexceptions -mthreads -Wall -DUNICODE -DQT_LARGEFILE_SUPPORT -DQT_MOC -DQT_BOOTSTRAPPED -DQT_LITE_UNICODE -DQT_TEXTCODEC -DQT_NO_CAST_FROM_AS CII -DQT_NO_CAST_TO_ASCII -DQT_NO_CODECS -DQT_NO_DATASTREAM -DQT_NO_GEOM_VARIANT -DQT_NO_LIBRARY -DQT_NO_QOBJECT -DQT_NO_STL -DQT_NO_SYSTEMLOCALE -DQT_NO_TEXTST REAM -DQT_NO_THREAD -DQT_NO_UNICODETABLES -DQT_NO_USING_NAMESPACE -DQT_NODLL -I" ." -I"." -I"......\include" -I"......\include\QtCore" -I"......\include\Qt Xml" -I"....\xml" -I"c:\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1. 1\include" -I"......\mkspecs\win32-g++" -o release\moc.o moc.cpp ... g++ -enable-stdcall-fixup -Wl,-enable-auto-import -Wl,-enable-runtime-pseudo-rel oc -Wl,-s -Wl,-subsystem,console -mthreads -Wl -o ......\bin\moc.exe release/m oc.o release/preprocessor.o release/generator.o release/parser.o release/token.o release/main.o -L"c:\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\ Lib\" -LC:/Qt-static/4.6.3/src/tools/bootstrap/release -lbootstrap -luser32 release/moc.o:moc.cpp:(.text+0x14b): undefined reference to QByteArray::shared_ null' release/moc.o:moc.cpp:(.text+0x150): undefined reference toQByteArray::shared_ null' release/moc.o:moc.cpp:(.text+0x156): undefined reference to `QByteArray::shared_ ... The list of undefined references is actually much longer. This is out of the box on a pretty default Windows installation. I wonder whether I'm doing something wrong or there's a bug in the toolkit.
I had similar problems. In my case Visual Studio had set environment parameters INCLUDE and LIB which confused the make. The solution was to disable them from the command line set INCLUDE= set LIB= before compiling the Qt libraries.
3,109,392
3,109,601
Signal - Slot connection inside loop
In my code I am creating new objects of same type inside loop and connecting a signal to object slot. Here is my trial. A * a; QList<A *> aList; int aCounter = 0; while(aCounter < 2) { a = new A; aList.push_back(a); connect(this,SIGNAL(somethingHappened()),aList[aCounter],SLOT(doSometing())); aCounter++; } When somethingHappened signal is emitted. Both objects slot is called. But I need to handle them seperately. Is it wrong to connect signal to a slot inside loop? If not how can I achieve my desire?
If I understand you correctly you may want to do something like this? A * a; QList<A *> aList; int aCounter = 0; while(aCounter < 2) { a = new A; aList.push_back(a); if ( aCounter == 0 ) connect(this,SIGNAL(somethingHappened()),aList[aCounter],SLOT(doSometing())); aCounter++; } This connects the signal only to the first object (but that's quite obvious). It is not possible to connect a signal to multiple slots, but send it out to just one. If this is really your intention it would be more elegant if you actually connected this one outside the loop. Another possibility would be to connect everything like you did before, but store some kind ob member variable in each instance of A and make the behavior of doSomething() dependant on that.
3,109,414
3,109,494
Library to manage menus in embedded device for C/C++
I'm looking for a library to manage menus. I'm looking for something which is based on configuration files. It doesn't have to manage keyboard input or display, just the menu logic. What I have in mind something like: //menu.xml <menu> <Start /> <Stop /> <Configuration displayname="Configure System"> <Sound type="toggle" /> <Speed display="Speed related settings"> <Speedy type="toggle" default="on" /> <Optimizations type="toggle" /> </Speed> </Configuration> <Filesystem> <SaveSnapshot /> <LoadSnapshot /> </Filesystem> </menu> In the code we would have: //menu.cpp Menu menu("menu.xml"); menu.bind("SaveSnapshot",saveSnapshotPressed); menu.bind("LoadSnapshot",loadSnapshotPressed); menu.bind("Sound",soundSetTo); ... void onKeyPressed(key_t key) { ... switch (key) { case KEY_UP: menu.goUp(); break; case KEY_DOWN: menu.goDown(); break; case KEY_ENTER: menu.action(); break; } // display.cpp void render(...) { for (int i=0;i<menu.items().size();++i) { renderText(getMenuCoord(i),menu.items()[i].c_str()); } ... } Such a library could be very useful to display menus in embedded device. I'll be glad to hear if such library exists, or is there a better idea for this library.
There are things like Kaleido: http://www.digitalairways.com/kaleido-engine.htm which are very nice, but pricey. Emwin is simpler and cheaper but nothing like as rich in terms of functionality: http://www.segger.com/cms/emwin.html
3,109,543
3,109,586
What to do to make application Large Address Aware?
I am currently in process of making our application Large Address Aware. As experience has shown, there are some unexpected gotchas when doing so. I create this post to make a complete list of steps which need to be taken. The development considerations listed in the AMD Large Address Aware guide provide a good starting point, but are by no means complete: The following considerations will help to make sure that the code can handle addresses larger than 2GB: Avoid the use of signed pointer arithmetic (I.e. compares and adds) Pointers use all 32-bits. Don’t use Bit31 for something else. Some dll’s will be loaded just under the 2GB boundary. In this case, no consecutive memory can be allocated with VirtualAlloc(). Whenever possible, use GlobalMemoryStatusEx() (preferred) or GlobalMemoryStatus() to retrieve memory sizes. Therefore, the question is: What is the complete list of things which need to be done when making C++ Win32 native application Large Address Aware?
(obvious) select Support Address Larger than 2 Gigabytes (/LARGEADDRESSAWARE) in the project properties: Linker / System / Enable Large Address check all pointer subtractions and verify the result is stored in a type which can contain the possible difference, or replace them with comparisons or other constructs - see Detect pointer arithmetics because of LARGEADDRESSAWARE). Note: pointer comparison should be fine, contrary to AMD advice, there is no reason why it should cause 4 GB issues make sure you are not assuming pointers have Bit31 zero, do not attempt to use Bit31 for something else. replace all GetCursorPos calls with GetCursorInfo - see GetCursorPos fails with large addresses for all assignments into PVOID64 use PtrToPtr64, needed e.g. when using ReadFileScatter, see ReadFileScatter remark section
3,109,565
3,109,592
C++ or Python (maybe else) to create GUI for console application in C
I have a Visual C console application (created in VC++2008EE) and I need to add GUI to it. One idea was to invoke the console app as a subprocess and communicate with it using stdin and stdout. I tried to do that with Python subprocess module - but it deadlocks (probably because my console app is running continuously). As I understood from http://www.python.org/dev/peps/pep-3145/ it is not possible now to integrate continiously running console application with python subprocess module. The other idea (more strait-forward probably) was to add a form to this console application project. But as I try to do it VS convers the project to one with "Common Language Runtime support" whatever it means, ads the form, a cpp file for form - and it's not compiling anymore saying: Command line error D8016 : '/MTd' and '/clr' command-line options are incompatible error BK1506 : cannot open file '.\Debug\Form_TEST.sbr': No such file or directory No idea what it means. I have never dealed with C++, but I have used C and Python some time. What would you recommend?
If you own the code for the console app, don't mess around trying to talk to it using input and output streams. Extract the logic of your console app into a library, and call that library from a GUI of your choice - either Windows.Forms from C#, Python GTK, ordinary GTK.
3,109,649
3,110,281
Modifying a file from within an executable - permission denied in XP (but not Vista)
I have an application where I need to open an xml file, modify it, and close it again. When I test the code on a laptop running Windows Vista, it works perfectly, but under Windows XP I can't even open the file for read/write access: errno_t _wfopen_s(&inStream, m_fileName, L"r+, ccs = UTF-8"); ...without getting an error code 13, "Permission denied" (although the file will open without any problems if I select "r" rather than "r+' to specify read-only access). Yet the permissions on the file are all set appropriately, as far as I can see, and the file can be opened and modified from the GUI without difficulty. What could possibly be causing this? Any suggestions would be welcome.
Well, with r+ you will ask for write access to the file. A privilege that is harder to come by, do triple-check that the user account indeed has the write privilege in the folder. But sounds like you already checked that. The next consideration is sharing. The fopen() function is quite inappropriate on modern multitasking operating systems, it allows any process to access the opened file and both read and write to it. That rarely comes to a good end, especially write sharing can only produce garbage if the processes don't negotiate access to the file. That's why there's an fopen_s() in the Microsoft CRT, it makes sure that write sharing is denied. It is very rare that you'd want to allow it. When you pass "r" then read sharing is allowed. When you pass "r+" then no sharing is allowed. That can fail if some other process already has the file opened for reading. You need to find that other process. The SysInternals' Handle utility can help you find it. Also consider that it might be your own program. In general, take charge of controlling the sharing yourself, use the _wfsopen() function instead. Note that there's no secure version for it because none is needed.
3,109,737
3,109,865
How to receive and decode SNMP traps in a C (or C++) application?
I am trying to write a very small SNMP trap receiver, listening to UDP port 162. Traps come in fine, but I can not decode them. I have found libber, but it can't decode the traps for some reason. I am probably using it wrong. I imagine decoding an SNMP trap should be fairly simple and that I am missing something crucial. Is it possible to use NET-SNMP as a library and create a small trap-receiving program from it? I would not be surprised at all, but can not find any information about it. Maybe my google-fu is weak.
Well, using net-snmp, you usually use snmptrapd daemon that calls for you external commands/scripts. If you cannot use this way, I suggest you look at snmptrapd.c code. Moreover, if I recall correctly, they build a libsnmptrapd library. It should be easy to find the right API calls ... If I have time I will update my answer with a snippet ... my2c
3,109,943
3,109,979
Returning after throwing exceptions
Is it in any way beneficial to return a value after throwing an exception? If not, can the return statement be left out and is it somehow possible to remove compiler error C4715: not all control paths return a value? Thanks in advance. Edit: (sample code) for (ushort i = 0; i < itsNumUnits; ++i) if (unitFormation[i] == unit) { return unitSetup[i]; } else throw unit; return 0;
There is no need to return a value after exception throw. If you have this error, you should check the paths your code can get to without throwing an exception, e.g. if (something) throw Exception; else return value; Failing to return value in the "else" branch of "if" would cause a compile error because the exception may or may not be thrown depending on value of something.
3,110,022
3,110,066
What do I need to download to use MFC without Visual Studio?
I've got Visual Studio 2008 express, and I need to use afx.h and some other things from MFC. Is there an SDK I can download that includes those? I downloaded the latest Windows SDK, but that didn't include it. Thanks.
MFC is the proprietary class collection for Microsoft paid customer so I don't think you can get them FOC (well legally of course). You can consider Win32++ which attempt to mimic MFC functionalities and its open source.
3,110,140
3,110,178
Take care about precedence of * and ++ in C/C++, (and any keystroke when programming)
Somebody write this function void strToUpper(char *p) { while (*p) { *p = TOUPPER(*p); *p++; //<-- Line to pay attention } } I asked, why do you put the * before p++? answer: because "It's the same", I corrected the code and then stay angry for a while, because both really work the same... void strToUpper(char *p) { while (*p) { *p = TOUPPER(*p); p++; //<-- Line to pay attention } } So I would like to share this with stackoverflow, example: char s[6]="hello"; What would it do? *++ptr; This will evaluate the ++ pre-increment(over the pointer) and then the dereference operator *, so it will let a char value 'e' (second letter of "hello") (that is not used in this case and could generate a warning on compilation) and the pointer will be pointing from the 'e' (position 1) What would it do? *ptr++; This is a little weird because it will evaluate the dereference operator * first, so it will let a char value 'h' (that is neither used in this case), and then the ++ post-increment(to the pointer), so (again) the pointer will be pointing from the 'e' (position 1) What would it do? ptr++; Finally it won't have a Lvalue of char, but it won't generate any warning if isn't used, and the pointer will be pointing from the 'e' (position 1) too. These three forms does the same from the pointer address point of view.. IMHO That's the worst thing of some computer languages (almost everyone).. "There is a poor Hamming distance between any code and any bug" We have no redundancy when programming, if you take a Law book, and write random chars within, It will be readable, but if you type random when programming, you get a bug, 100% accuracy
++ has precedence over *. But I agree, it's unclear when you mix both in the same statement.
3,110,206
3,192,938
Programmatically check if IPv6 is enabled on windows
Is there a way to programmatically check if IPv6 is installed/enabled on windows using c++? Either at an interface level, or system wide.
WSCEnumProtocols() can be used to check whether IPv6 is installed as a protocol.
3,110,306
3,110,344
Reading/Writing Nibbles (without bit fields) in C/C++
Is there an easy way to read/write a nibble in a byte without using bit fields? I'll always need to read both nibbles, but will need to write each nibble individually. Thanks!
Use masks : char byte; byte = (byte & 0xF0) | (nibble1 & 0xF); // write low quartet byte = (byte & 0x0F) | ((nibble2 & 0xF) << 4); // write high quartet You may want to put this inside macros.
3,110,364
3,110,382
C++: Compiler complains about variables initialization in constructor
I have in my header "Test.h" a variable of a class that doesn't have a constructor without arguments. And I have a constructor like this: Test::Test() // <-- Here he complains: // error: no matching function for call to ‘Beer::Beer()’ { int i = 2; theVar = Beer(1, i); // Beer(int, int) is the only constructor } But I'm initializing it after the (empty) initializer list, in the constructor body. How can I solve this? How is this problem called, if it has a name? Thanks
You need to use initializer list. Test::Test() : theVar(1, 2) {} If the problem is that i is the result of some other function call, you can do sometihng like Test::Test() : theVar(1, compute_i()) {} The problem is that the constructor body is executed after all members are initialized. They are initialized first by calling whichever constructors are specified in the initializer list, and if the member is not listed there, by calling its default constructor. That is why you get the error complaining about Beer::Beer(): because nothing else is specified, it tries to call that constructor to initialize theVar, and it doesn't exist. Then after all members are initialized, the constructor body is executed (where you perform an assignment, and not an initialization, of theVar. But the compiler never gets that far, because it couldn't perform the initialization.
3,110,498
3,110,519
C++ Reorganizing an array to fill in the gaps?
I'm not sure if the word Reorganizing is the correct term, but its the only way I can describe what I'm looking for. If I have an array of say, Cats, like so: CAT *myCats[99]; myCats[0] = new CAT; myCats[1] = new CAT; myCats[2] = new CAT; myCats[3] = new CAT; myCats[4] = new CAT; myCats[5] = new CAT; At one point in time, lets say myCats[3] gets deleted: delete myCats[3]; now I have the following: myCats[0] myCats[1] myCats[2] myCats[4] myCats[5] Is there an easy way to reorganize the array so that it moves 4->3 and 5->4, essentially filling in the gaps? myCats[0] myCats[1] myCats[2] myCats[3] myCats[4] Is the best way to accomplish this, to essentially iterate through the array and determining that if a element is empty/missing, I just need to move the next existing element into its place? How would I do this? How would I determine if the Cat element at any point in the array exists? Or is there a more simple pre-determined method for accomplishing what I need? Sorry if the example and syntax is a little off. I'm new to C++. UPDATE Thanks for the quick suggestions. Looks like Vectors are the way to go. I always forget about Vectors. In the front of my mind, a Vector is just a container that holds an x, y and z value :-)
If you are using C++, you can much more easily accomplish this using std::vector: std::vector<CAT*> cats; cats.push_back(new CAT); cats.push_back(new CAT); cats.push_back(new CAT); // remove the second cat delete cats[1]; cats.erase(cats.begin() + 1); Now the vector has two cats in it (the first and third cats that were inserted) and they are at indices zero and one. However, in C++, there's no reason to allocate everything dynamically, so you're likely to be better off with just a vector<CAT>: std::vector<CAT> cats; cats.push_back(CAT()); cats.push_back(CAT()); cats.push_back(CAT()); // remove the second cat cats.erase(cats.begin() + 1); This way, destruction of the cats is handled automatically and you don't have to worry about managing any of the memory yourself. If you do have to use pointers (e.g., your class is a polymorphic base class), you'd probably want to use a std::vector of smart pointers (e.g., shared_ptrs). With smart pointers, you don't have to remember to delete the objects when you are done with them--it gets done automatically. For example, the above code using shared_ptr would look like: std::vector<std::shared_ptr<CAT> > cats; cats.push_back(std::make_shared(new CAT)); cats.push_back(std::make_shared(new CAT)); cats.push_back(std::make_shared(new CAT)); // remove the second cat // note we don't need to call delete; shared_ptr does that for us cats.erase(cats.begin() + 1); (Your standard library may not include shared_ptr in the std namespace yet; in that case, you may find it elsewhere). If you aren't familiar with shared_ptr, the Boost documentation makes for a great introduction.
3,110,557
3,110,600
how can i load BitmapEx.h
I am working on MFC with c++. i got this error: Cannot open include file: 'BitmapEx.h': No such file or directory. plzz tell me how can i include it.
What is this file? Is it on your disk? If it is not one of the standard includes, you should put it in your CPP directory and include with double quotes, #include "BitmapEx.h"
3,110,560
3,111,479
How can you link to a different version of MFC from a Visual C++ project in Visual Studio 2010?
I have a VC++ project in VS2010 that is linking to some dll's built with VS2008. Works fine until I try to pass MFC objects to the VS2008 dll. The artifact of the VS2010 VC++ project (a .dll) is linking against the latest version of MFC that shipped with VS2010, whereas the VS2008 .dll is linking against the previous version of MFC that shipped with VS2008. VS2010 VC++ projects have a "Platform Toolset" property that allows either v90 (VS2008) or v100 (VS2010) and that seems like it ought to do the trick. However, the VS2010 VC++ project is being built with /clr (Common Language Runtime Support), which seems to require targeting v4.0 of the .NET Framework - which is not supported in the v90 (VS2008) toolset.
Setting the Platform Toolset option to v90 works if and only if the Targeted framework is 3.5 (or less, I presume). To change the Targeted framework you have to edit the .vcxproj file directly. To make the change, follow these directions. Note, that the XML element may not be present but the instructions to add the element to the .vcxproj file are in the comments.
3,110,629
3,110,715
convert std::string to basic_ostream?
Is there a conversion for the above?
Convert a std::string to an output stream? Usually it's: convert a string to an input stream that reads characters from the given string: std::string myString = //... std::istringstream iss(myString); See also: http://www.cplusplus.com/reference/iostream/istringstream/
3,110,926
3,112,317
OpenCV - VideoWriter produces a video with a "repeated" image
I'm trying to process each frame in a pair of video files in OpenCV and then write the resulting frames to an output avi file. Everything works, except that the output video file looks strange: instead of one solid image, the image is repeated three times and horizontally compressed so all three copies fit into the window. I suspect there is something going wrong with the number of channels the writer is expecting, but I'm giving it 8-bit single channel images to write. Below are the setting with which I'm initializing my videowriter: //Initialize the video writer CvVideoWriter *writer = cvCreateVideoWriter("out.avi",CV_FOURCC('D','I','V','X'), 30, frame_sizeL, 0); Has anyone encountered this strange output from the openCV videowriter before? I've been checking the resulting frames with cvSaveImage just to see if somehow my processing step is creating the "tripled" image, but it's not. It's only when I write to the output avi with cvWriteFrame that the image gets "tripled" and compressed. Edit: So I've discovered that this only happens when I attempt to write single channel images using write frame. If I write 3 channel 8-bit RGB images, the output video turns out fine. Why is it doing this? I am correctly passing "0" for the color argument when initializing the CvVideoWriter, so it should be expecting single channel images.
In the C++ version you have to tell cv::VideoWriter that you are sending a single channel image by setting the last paramter "false", are you sure you are doing this? edit: alternatively you can convert a greyscale image to color using cvtColor() and CV_GRAY2RGB
3,110,976
3,111,007
In C++, Is it good form to write code that executes before main()?
The constructors of globally declared classes are invoked before main is entered. While this can be confusing to a new reader of the code because it is done so infrequently, is it necessarily a bad idea?
It's not necessarily a bad idea, but usually, yes. First, it's global data, and globals are usually a bad thing. The more global state you have, the harder it becomes to reason about your program. Second, C++ doesn't guarantee intialization order of static objects defined in different translation units (.cpp files) -- so if they depend on one another, you might be in trouble.
3,111,045
3,111,164
Where is disable_if in C++0x?
Boost has both enable_if and disable_if, but C++0x seems to be missing the latter. Why was it left out? Are there meta-programming facilities in C++0x that allow me to build disable_if in terms of enable_if? Oh, I just noticed that std::enable_if is basically boost::enable_if_c, and that there is no such thing as boost::enable_if in C++0x.
At the risk of seeming stupid, just do !expression instead of expression in the bool template parameter in enable_if to make it behave like a disable_if? Of course if that idea works, you could just expand on it to write a class with disable_if-like behavior? Ok, I believe you could implement disable_if like this: template <bool B, typename T = void> struct disable_if { typedef T type; }; template <typename T> struct disable_if<true,T> { };
3,111,072
3,111,091
c++ static function unfound
I have this definition of the function in my class. The .hpp file: class SomeClass { public: static string DoStuff(string s); }; The .cpp file: #include "header.hpp" string SomeClass::DoStuff(string s) { // do something } Compiler says: **error C2039: 'DoStuff' : is not a member of 'SomeClass'** Can somebody help? EDIT: actual offending code header definition class DDateTime{ public: static string date2OracleDate(DATE Date); } string DDateTime::date2OracleDate(DATE Date) { string s; s="TO_DATE('" + DDateTime::DateFormat("%d/%m/%Y",Date) + "','dd/MM/YYYY')"; return s; }
Usually, .cpp files must include the matching .h or .hpp file. Is it the case here ? You can also have namespace issue (missing namespace in .cpp file or static method definition outside of the namespace, and so on.). Actually, it is difficult to answer until we have the real breaking code. Moreover, I don't know if this is sample code, but it seems you used something like using std::string or using namespace std in your header file. This is a bad idea because it will polute every file in which your header is included. What If someone wants to use your header file but don't want to "use" std because string is the name of one of its classes ?
3,111,147
3,111,269
How do I configure Qt to work with Visual Studio 2010?
I downloaded open-source version of Qt from the site and have compiled it with nmake, but I'm having trouble using it in my projects. It seems that Visual Studio can't find the Qt headers, even though I added the paths to my PATH, INCLUDE, and LIB variables. I tried installing the Qt Visual Studio add-in but it only supports Visual Studio 2008. Has anyone gotten Qt to work with Visual Studio 2010? Or do I have to wait until Qt 4.7 is officially released for Visual Studio 2010 support?
Traditionally VS support was part of the paid licences, with the OS package you only get mingw support. Things are changing, but might have some rough edges for a while. OTOH, mingw has a HUGE advantage: deployment. You don't have to chase around the vcredist_x86 files and all the associated voodoo. Just be sure to include all the .DLLs you use and that's it. Also, there's QtCreator. It's not as featureful or omniscient as VS; but it does feel a lot nicer and easier to use. It takes off all the tedious work of nmake, and embeds the UI editors. And it's cross platform! honestly, for me VS can drop dead this minute and i won't miss it.
3,111,392
3,111,503
Find width of a tab item? (WinAPI)
I want to be able to know how much room a particular tab takes up, is there a way to calculate this knowing it's text and having its item struct? Thanks
Assuming a SysTabControl how about TCM_GETITEMRECT?
3,111,501
3,111,551
Make a template accept a specific class/family of classes?
I have a template method that is designed to work with a specific set of classes. Since I have no real need for runtime polymorphism, I've decided to not use pointers to the parent class, but rather will have the compiler put everything together for me. I want to either restrict the type that can be passed to the template, or make GCC issue sensible errors when an incorrect type is passed. Is this possible?
Yes. It is possible using a number of different techniques depending on the specific needs of the day. There's boost::enable_if. There's MPL and static_assert...(use BOOST_STATIC_ASSERT if you're not using a C++0x compiler). There's Boost.Concepts. Yes. It is possible.
3,111,647
3,111,695
safe integer conversion in c++
I want to create a simple integer range checker and converter using c++ templates. The code looks like this: // D is the "destination" type and S the "source" type template <class D, class S> inline D SafeConvert( S value ); template <class S> inline int SafeConvert<int>( S value ) { ASSERT( value >= S(INT_MIN) && value <= S(INT_MAX) ); return int(value); } /// error C2768: 'SafeConvert' : illegal use of explicit template arguments template <class S> inline size_t SafeConvert<size_t>( S value ) { ASSERT( value >= S(0) && value <= S(size_t(-1)) ); return size_t(value); } /// error C2768: 'SafeConvert' : illegal use of explicit template arguments // ... void test() { size_t v = INT_MAX+1; int iv = SafeConvert<int>(v); } However I have the following come compilation errors: error C2768: 'SafeConvert' : illegal use of explicit template arguments My question is how to tell the compiler that I want to specialize only the D class ? Thanks.
You can't partially specialize function templates. You need to mimic it with a class wrapper or use standard function overloading. An example of mimicing: template <typename T1, typename T2> struct processor; template < typename T1, typename T2 > T1 fun(T2 t2) { return processor<T1,T2>::apply(t2); } template < typename T2 > struct processor<int,T2> { static int apply(T2 t2) { .... } }; ...etc...
3,111,864
3,111,889
How to create a library and call the header files using < > instead of ""?
I've been writing a library lately for my C++ computer class. I would like to put all my .lib and my header files inside a folder outside the project that's going to be calling the library. How can I call the library header files using the < > operators instead of the " "? I'm using visual studio [specifically VS03] Thanks, Y_Y
To include files in a separate directory from the directory where your source files are, you must add the directory with the headers to your "Additional Include Directories" property in the "C\C++, General" property page for your project. Then you can include the headers with either <> or "". See http://msdn.microsoft.com/en-us/library/36k2cdd4(VS.71).aspx The quote form just searches in the "." directory first.
3,111,873
3,111,906
c++ inherit from a virtal base class
I want to do the following: class ErrorBase { public: void SetError(unsigned errorCode) { mErrorCode = errorCode; } char const* Explanation(unsigned errorCode) const { return errorExplanations[errorCode]; } private: char const* errorExplanations[]; unsigned mErrorCode; }; class MyError : virtual public ErrorBase { public: enum ErrorCodes { eNone, eGeneric, eMySpecificError }; MyError() { // I want this to refer to the parent class's attribute, // such that when Explanation() is executed, it uses this errorExplanations = { "no error", "error in MyClass", "specific error" } } ~MyError() { } }; But I get the following error on the line declaring errorExplanations in the child class: error: expected primary-expression before '{' token How do I declare errorExplanations in the child class such that I can instantiate a child, and call myChild.Explanation() and get one of the error strings defined in the child's constructor? Any suggestions/corrections regarding my usage of const, virtual, public, etc are appreciated, Thanks!
Either you pass the array of error messages to the base class in its constructor (syntax may not be perfect but hopefully you get the idea): class ErrorBase { public: ErrorBase(char const* errorExplanations[]) { this->errorExplanations = errorExplanations; } ... private: char const* errorExplanations[]; ... }; class MyError : virtual public ErrorBase { public: ... MyError() : ErrorBase( { "no error", "error in MyClass", "specific error" } ) { } ... }; Or you make Explanation virtual and provide the desired implementation in the derived class: class ErrorBase { public: ... virtual char const* Explanation(unsigned errorCode) const = 0; protected: unsigned mErrorCode; }; class MyError : virtual public ErrorBase { public: ... MyError() : errorExplanations( { "no error", "error in MyClass", "specific error" } ) { } virtual char const* Explanation(unsigned errorCode) const { return errorExplanations[errorCode]; } ... private: char const* errorExplanations[]; };
3,111,892
3,112,025
Pointer-to-member-func, template & inheritance mixup
I am trying to create a generic "callback" object that will hold arbitrary data and invoke member functions of related classes. Due to internal policy, I cannot use Boost. The callback object looks like this: template<typename Object, typename Data> class Callback { public: typedef void (Object::*PHandler)(Callback*); Callback(Object* obj, PHandler handler) : pObj(obj), pHandler(handler) {} Callback& set(PHandler handler) { pHandler = handler; return *this; } void run() { (pObj->*pHandler)(this); } public: Data data; protected: Object* pObj; PHandler pHandler; }; And the class it works on: struct Object1 { struct Data { int i; }; typedef Callback<Object1, Data> Callback1; void callback(Callback1* pDisp) { printf("%cb\n", pDisp->data.i); } void test() { Callback1 cb(this, &Object1::callback); cb.data.i = 1; cb.run(); } }; The following test works as expected: Object1 obj1; obj1.test(); So far so good. However, when a coworker tried to derive from the Callback class instead of using a typedef, they got compilation errors due to incompatible pointers: struct Object2 { struct Data { int i; Data(int j) { i = j; } }; class Callback2 : public Callback<Object2, Data> { Callback2(Object2* obj, PHandler handler, int i) : Callback(obj, handler) { data.i = i; } }; void callback(Callback2* pDisp) { printf("%cb\n", pDisp->data.i); } void test() { Callback2 cb(this, &Object2::callback, 2); cb.run(); } }; I tried using the "curiously recurring template pattern" in the Callback class and managed to get derived classes working, but it broke code that used the typedef method. My question is: How can I modify the Callback class to work with both cases, and without requiring extra work on the part of the user of the class?
You have to pass the class type of the derived. To not break the typedef-way, you can can give that parameter a default value. Something like the following should work template<typename Object, typename Data, typename Derived = void> class Callback; namespace detail { template<typename Object, typename Data, typename Derived> struct derived { typedef Derived derived_type; }; template<typename Object, typename Data> struct derived<Object, Data, void> { typedef Callback<Object, Data, void> derived_type; }; } template<typename Object, typename Data, typename Derived> class Callback : detail::derived<Object, Data, Derived> { typedef typename detail::derived<Object, Data, Derived>::derived_type derived_type; derived_type &getDerived() { return static_cast<derived_type&>(*this); } public: // ... stays unchanged ... derived_type& set(PHandler handler) { pHandler = handler; return getDerived(); } void run() { (pObj->*pHandler)(&getDerived()); } // ... stays unchanged ... }; Alternatively you can simply have two classes for this. One for inheritance and one if you don't inherit. The first is for inheritance template<typename Object, typename Data, typename Derived> class CallbackBase { typedef Derived derived_type; derived_type &getDerived() { return static_cast<derived_type&>(*this); } public: // ... stays unchanged ... derived_type& set(PHandler handler) { pHandler = handler; return getDerived(); } void run() { (pObj->*pHandler)(&getDerived()); } // ... stays unchanged ... }; And the second is for non-inheritance. You can make use of the base-class for this template<typename Object, typename Data> struct Callback : CallbackBase<Object, Data, Callback<Object, Data> > { Callback(Object* obj, PHandler handler) : Callback::CallbackBase(obj, handler) {} };
3,111,920
3,112,066
how to transfer C++ number format to C# number format?
have the flowing C++ code: CString info, info2; info.Format("%2d", Value[i]); info2.Format("%4.1f", Value[j]); want to have the equivalent code in C# how to do it?
Code ported to C#: String info; String info2; info = String.Format("{0,2:D}", Value[i]); info2 = String.Format("{0,6:0.0}", Value[j]); 6 is used for aligning the string 4 digits plus decimal point plus decimal digit. NOTE take care of the current Culture used, you might get , instead of . for some Cultures.
3,112,003
3,112,185
Perform CRUD for todos/tasks/appointments from Outlook?
How can I perform CRUD (Create, Read, Update, Delete) for todos/tasks/appointments/etc from Outlook. Does Microsoft have a data api like Google that I can use to interact with Microsoft applications? I prefer this in C++ (Microsoft Visual C++), but Java will also work.
Here is a tutorial article which might be along the lines of what you are looking for: Automate Microsoft Outlook from C++
3,112,092
3,112,153
Recompile MFC DLL while client exe is running
Is it possible to recompile an MFC DLL while its "client" executable is running, and have the executable detect and pick up the new changes? If it's possible, is it foolish? Being able to recompile the DLL without restarting the exe would save some time in my coding workflow. I am using Visual Studio 2008, code is written in native C++/MFC. My code changes are entirely contained in the DLL, not the EXE. Thanks!
Unfortunately, unless the executable has support for hot-swapping DLLs, you can't do it. The standard DLL loading mechanism in Windows will load it either at the start of the process or at first use of a function exported by the DLL and will not watch the file for changes in order to reload it. Also, depending on how the DLL is loaded, the file might be locked for changes. You will have to stop your client executable before recompiling.
3,112,105
3,112,219
C++ iostreams question
I am now diving into boost::iostreams and I'm looking for a way to create a stream that iterates over some container<char>. Right now I have the code that work for a std::vector<char>, but it does ONLY for it, because I wrote std::vector-specific code. I am doing the following thing: template <class Object, class Container> void Load(Object& object, const Container& container) { using namespace boost::iostreams; // Create a stream that iterates over vector and use it in // the following procedure LoadImpl(object, stream<array_source>(&container[0], container.size())); } where LoadImpl(...) is described the following way: template <class Object void LoadImpl(Object& object, std::istream& stream) { ... } and is used to wrap serializing / deserializing using some certain stream. Could you give me any advice on how to make Load routine more generic? Let's say, I would like to have an ability to substitute std::vector<char> to it as long as some std::string container.
Instead of passing the container as a parameter to your functions, what about using the approach taken by the standard library, and use iterators? Your function would be templated on the iterator type instead of the container type and would take a begin and end iterator instead of a container. Then it's a simple matter to iterate over the range for any container type you give it.
3,112,234
3,112,404
multimap accumulate values
I have a multimap defined by typedef std::pair<int, int> comp_buf_pair; //pair<comp_t, dij> typedef std::pair<int, comp_buf_pair> node_buf_pair; typedef std::multimap<int, comp_buf_pair> buf_map; //key=PE, value = pair<comp_t, dij> typedef buf_map::iterator It_buf; int summ (int x, int y) {return x+y;} int total_buf_size = 0; std::cout << "\nUpdated buffer values" << std::endl; for(It_buf it = bufsz_map.begin(); it!= bufsz_map.end(); ++it) { comp_buf_pair it1 = it->second; // max buffer size will be summ(it1.second) //total_buf_size = std::accumulate(bufsz_map.begin(), bufsz_map.end(), &summ); //error?? std::cout << "Total buffers required for this config = " << total_buf_size << std::endl; std::cout << it->first << " : " << it1.first << " : " << it1.second << std::endl; } I would like to sum all the values pointed by it1.second How can the std::accumulate function access the second iterator values?
Your issue is with the summ function, you actually need something better than that to be able to handle 2 mismatched types. If you're lucky, this could work: int summ(int x, buf_map::value_type const& v) { return x + v.second; } If you're unlucky (depending on how accumulate is implemented), you could always: struct Summer { typedef buf_map::value_type const& s_type; int operator()(int x, s_type v) const { return x + v.second.first; } int operator()(s_type v, int x) const { return x + v.second.first; } }; And then use: int result = std::accumulate(map.begin(), map.end(), 0, Summer());
3,112,278
3,136,097
Is codeblocks 10.05. compatible with QtWorkbench?
windows xp sp2 , codeblocks 10.05. , Qt 4.6 Does anyone know if codeblocks_10.05 is compatible with QtWorkbench-0.6.0_alpha. I made everything written on http://code.google.com/p/qtworkbench but when I go to compile, codeblocks freeze. I may have made a mistake somewhere in the setup, I do not know. The main question: Is it even CB 10:05 compatible with qtworkbench 0.6.0 alpha. Please give us your experiences.
FROM CREATOR OF QtWorkBench: Comment 12 by y.pagles, Jun 11, 2009 I don't think that it's going to work with any different revision than the 8.02 one. So , the answer is 99% NO !!!
3,112,550
3,112,569
Reference variables in C++
Why are reference variables not present/used in C? Why are they designed for C++?
Because C was invented first. I don't know if they hadn't thought about references at the time (being mostly unnecessary), or if there was some particular reason not to include them (perhaps compiler complexity). They're certainly much more useful for object-oriented and generic constructs than the procedural style of C.
3,112,602
3,115,063
C++ implicit conversions and ambiguity in overloaded function call
I am facing the following problem: I have a class V (say a vector) from which I can produce two classes: CI and I (think of const_iterator and iterator). If I have a const V then I can only produce CI (again think of iterator and const_iterator). Essentially I would like to subsitute (const V& v) with (CI ci) and (V& v) with (I i). Moreover I would like to be able to still pass a V obj directly to functions expecting a I or a CI hence the implicit conversions from V and const V to CI and I. The problem I am facing is that while overloaded functions can distinguish between (const V& v) and (V& v), they cannot "distinguish" between (CI ci) and (I i) when I pass a V obj. In code: struct V {}; struct I { I( V& v ){} }; struct CI { CI( const V& v ){} //I would like to say const only }; void fun( I i ) { double x = 1.0; } void fun( CI ci ) { double x = 2.0; } void fun2( V& v ) { double x = 1.0; } void fun2( const V& v ) { double x = 2.0; } Notice I could have defined conversions operator in V (is it equivalent?) instead of defining the constructors in CI and I. Now: V v; const V cv; fun2( v ); fun2( cv ); fun( v ); //AMBIGUOUS! fun( cv ); Is there a way to solve this problem WITHOUT adding any extra indirection (i.e. the fun functions cannot be modified and v MUST be passed DIRECTLY to fun but you are free to modify everything else). Thank you in advance for any help!
What you need here is explicit constructors: struct I { explicit I( V& v ){} }; struct CI { explicit CI( const V& v ){} //I would like to say const only }; Too many C++ programmers overlook the explicit keyword for constructors. All unary, parameterized constructors should be explicit by default. Implicit constructors invite ambiguity problems like these as well as leading to very goofy, roundabout conversion processes that can easily lead to problematic and very inefficient code. Now you're set, ambiguity problem solved. Without explicit constructors, you cannot prevent this ambiguity problem. For the client code, you do need to modify it to be explicit about its conversions: V v; const V cv; fun2( I(v) ); fun2( CI(cv) ); fun( I(v) ); fun( CI(cv) ); Such syntax will be required now to construct objects of I or CI, but that's a good thing: no one can accidentally introduce ambiguity problems anymore.
3,112,698
3,112,715
Expected a declaration (compiler error C2059)
The following is giving me a compiler error: #include <foo.h> #define ODP ( \ L"bar. " \ // C2059 here L"baz.") #define FFW (5) What am I doing wrong?
You forgot the line splice characters #define ODP ( \ \ L"bar. " \ \ L"baz.") Not sure why you put those newlines though. It all gets down to #define ODP (L"bar. baz.") Note that the characters must be the last ones on the line. And you cannot put a line comment (//) before them, because the line comment would extend to the next physical line. Use C Style comments if you still want to comment the lines separately #define ODP ( \ /* this is bar */ \ L"bar. " \ /* this is baz */ \ L"baz.")
3,112,755
3,113,074
How to get nmake to push through errors ( behaviour of make -k)
I'm using cmake to generate an nmake build system using the "NMake Makefiles" generator. When I compile, even if I specify "nmake /K", the build stops after the first .cpp file which had an error. I understand that it should not compile targets who have a failed dependency, but several independent source files should be handleable in this way.
GNU make's -k option also bails out if it gets too many errors. Try nmake /I just like make -i
3,112,869
3,112,984
fscanf / fscanf_s difference in behaviour
I'm puzzled by the following difference in behaviour: // suppose myfile.txt contains a single line with the single character 's' errno_t res; FILE* fp; char cmd[81]; res = fopen_s(&fp, "D:\\myfile.txt", "rb" ); fscanf(fp,"%80s",cmd); // cmd now contains 's/0' fclose(fp); res = fopen_s(&fp, "D:\\myfile.txt", "rb" ); fscanf_s(fp,"%80s",cmd); // cmd now contains '/0' ! fclose(fp); The results do not depend in the order of call (i.e., call fscanf_s first, you'd get the empty string first). Compiled on VC++ - VS2005. Can anyone reproduce? Can anyone explain? Thanks!
From the docs on fscanf_s(), http://msdn.microsoft.com/en-us/library/6ybhk9kc.aspx: The main difference between the secure functions (with the _s suffix) and the older functions is that the secure functions require the size of each c, C, s, S and [ type field to be passed as an argument immediately following the variable. For more information, see scanf_s, _scanf_s_l, wscanf_s, _wscanf_s_l and scanf Width Specification. And http://msdn.microsoft.com/en-us/library/w40768et.aspx: Unlike scanf and wscanf, scanf_s and wscanf_s require the buffer size to be specified for all input parameters of type c, C, s, S, or [. The buffer size is passed as an additional parameter immediately following the pointer to the buffer or variable. For example, if reading a string, the buffer size for that string is passed as follows: char s[10]; scanf("%9s", s, 10); So you should call it like so: fscanf_s(fp,"%80s",cmd, sizeof(cmd));
3,112,933
3,113,052
Function that returns a pointer to const 2-d array (C++)
I'm an intermittent programmer and seem to have forgotten a lot of basics recently. I've created a class SimPars to hold several two-dimensional arrays; the one shown below is demPMFs. I'm going to pass a pointer to an instance of SimPars to other classes, and I want these classes to be able to read the arrays using SimPars accessor functions. Speed and memory are important. I know life is often simpler with vectors, but in this case, I'd really like to stick to arrays. How do I write the accessor functions for the arrays? If I'm interested in the nth array index, how would I access it using the returned pointer? (Should I write a separate accessor function for a particular index of the array?) What's below is certainly wrong. // SimPars.h #ifndef SIMPARS_H #define SIMPARS_H #include "Parameters.h" // includes array size information class SimPars { public: SimPars( void ); ~SimPars( void ); const double [][ INIT_NUM_AGE_CATS ] get_demPMFs() const; private: double demPMFs[ NUM_SOCIODEM_FILES ][ INIT_NUM_AGE_CATS ]; }; #endif // SimPars.cpp SimPars::SimPars() { demPMFs[ NUM_SOCIODEM_FILES ][ INIT_NUM_AGE_CATS ]; // ...code snipped--demPMFs gets initialized... } //...destructor snipped const double [][ INIT_NUM_AGE_CATS ] SimPars::get_demPMFs( void ) const { return demPMFs; } I would greatly appreciate some kind of explanation with proposed solutions.
Basically, you have three options: return the entire array by reference, return the first row by pointer, or return the entire array by pointer. Here is the implementation: typedef double array_row[INIT_NUM_AGE_CATS]; typedef array_row array_t[NUM_SOCIODEM_FILES]; array_t demPMFs; const array_t& return_array_by_reference() const { return demPMFs; } const array_row* return_first_row_by_pointer() const { return demPMFs; } const array_t* return_array_by_pointer() const { return &demPMFs; } And here are the use cases: SimPars foo; double a = foo.return_array_by_reference()[0][0]; double b = foo.return_first_row_by_pointer()[0][0]; double c = (*foo.return_array_by_pointer())[0][0]; How would I return just the nth row of the array? Again, you have three choices: const array_row& return_nth_row_by_reference(size_t row) const { return demPMFs[row]; } const double* return_first_element_of_nth_row_by_pointer(size_t row) const { return demPMFs[row]; } const array_row* return_nth_row_by_pointer(size_t row) const { return demPMFs + row; }
3,113,018
3,113,369
trying to see if vector<string> has no values in map<string, string>
Just for fun I was trying to write a one line with std::find_if with boost::bind to check whether all the keys given in a vector in a map has no values, but really could not come up with a neat line of code. Here is what I attempted vector<string> v; v.push_back("a"); v.push_back("2"); ... map<string, string> m; m.insert("b","f"); ... std::find_if(v.begin(), v.end(), boost::bind(&string::empty, boost::bind(&map<string,String>::operator[], _1), _2 )) != v.end(); Obviously this is a big fail... anyone tried something like this?
The following line of code returns true only if all elements from v are not present in m: bool a = v.end() == std::find_if( v.begin(), v.end(), boost::bind( &str_map_t::const_iterator::operator!=, boost::bind<str_map_t::const_iterator>( &str_map_t::find, &m, _1 ), m.end() ) ); Explanation: Here we have two functors: boost::bind<str_map_t::const_iterator>( &str_map_t::find, &m, _1 ) This functor will return const_iterator which points to the element from m or to m.end() if not found. Here you should explicitly point return type str_map_t::const_iterator for boost::bind to get rid of ambiguity. boost::bind( &str_map_t::const_iterator::operator!=, _1, _2 ) This one will return true if _1!=_2 and false otherwise. Combine 1 and 2 and we'll get the full code: #include <iostream> #include <vector> #include <algorithm> #include <iterator> #include <string> #include <map> #include <boost/bind.hpp> using namespace std; int main(int argc, char *argv[]) { vector<string> v; v.push_back("x"); v.push_back("a"); v.push_back("6"); typedef map<string, string> str_map_t; str_map_t m; m.insert( str_map_t::value_type( "b", "f" ) ); bool a = v.end() == std::find_if( v.begin(), v.end(), boost::bind( &str_map_t::const_iterator::operator!=, boost::bind<str_map_t::const_iterator>( &str_map_t::find, &m, _1 ), m.end() ) ); std::cout << a << endl; return 0; } I wouldn't say it is readable code and I'd recommend to write a custom functor to get it more readable. A more readable version could look like the following (without bind): struct not_in_map { not_in_map( const str_map_t& map ) : map_(map) {} bool operator()( const string& val ) { return map_.end() != map_.find( val ); } private: const str_map_t& map_; }; bool a = v.end() == std::find_if( v.begin(), v.end(), not_in_map(m) );
3,113,055
3,113,128
extraneous empty lines when reading from an ifstream
In my program, I've redirected stdout to print to a file 'console.txt'. A function writes to that file like this: void printToConsole(const std::string& text, const TCODColor& fc, const TCODColor& bc) { // write the string cout << text << "@"; // write the two color values cout << static_cast<int>(fc.r) << " " << static_cast<int>(fc.g) << " " << static_cast<int>(fc.b) << " " << static_cast<int>(bc.r) << " " << static_cast<int>(bc.g) << " " << static_cast<int>(bc.b) << " " << endl; } I have a function that reads from that file that looks like this: void Console::readLogFile() { ifstream log("console.txt", ifstream::in); if(!log.is_open()) { cerr << "ERROR: console.txt not found!" << endl; return; } // read new input into the stack char str[256]; while(!log.eof()) { log.getline(str, 256); cerr << "str: " << str << endl; stk.push(static_cast<string>(str)); // stk is a std::stack<std::string> member of the class this function // belongs to. } cerr << endl; /* Do some stuff with str and stk here */ log.close(); clearLogFile(); } void Console::clearLogFile() { FILE* log; log = fopen("console.txt", "w"); fclose(log); } Often, console.txt is empty when readLogFile is called. I would expect that the while(!log.eof()) loop would never execute in that case, but it does. There is always at least one extraneous blank line in the file, sometimes two, and when input is read from the file, the input line is sandwiched between two blank lines. After a few calls to this function, the while(!log.eof()) loop then goes into an infinite loop pulling blank lines from the file. A typical runthrough of the program looks like this: str: str: Player moved.@191 191 191 0 0 0 str: str: str: Player moved.@191 191 191 0 0 0 str: str: // there should be a 'Player moved.' line in here str: str: // here as well str: str: // also here str: str: str: Player moved.@191 191 191 0 0 0 str: str: str: str: str: str: str: (onto infinite loop) Can anyone see what I'm doing wrong here? EDIT: As Amardeep suggested, I changed the while(!log.eof()) loop to a do{...}while(!log.fail); loop. This fixed the infinite loop problem, but not the extraneous lines. The program behaves as before, except where it once went into the infinite loop, it now reads nothing but blank lines where it should read input, like this: str: str: str: str: (etc.)
eof() status is not set until you attempt a read. You should change your read loop to do the getline() then check the fail() status instead of relying on eof(), which doesn't cover the breadth of things that can go wrong trying to read the file.
3,113,102
3,113,117
Create a C++ container that contain the filenames within a directory
I need to generate a container of filenames within a directory in C++ and it must be cross platform compatible. Someone recommended using the WIN32_FIND_DATA data structure. Is this the best option and if so how would I implement it? The user will not enter the filenames, but rather the C++ function will automatically search the directory and create a container of filenames. I don't know how to read in filenames like this either. I have a strong focus on standards too, so <dirent.h> is not an ideal solution because it is not ISO C standard even though its a header in the C POSIX library.
I'm guessing WIN32_FIND_DATA isn't your best bet for cross platform, but there are probably libraries to help provide it on linux. Consider using boost filesystem to dump the files into a std::vector. Something like this (adapted from here): void show_files(const path & directory) { if(!exists(directory)) return; directory_iterator end ; for( directory_iterator iter(directory) ; iter != end ; ++iter ) if (is_directory(*iter)) continue; // skip directories cout << "File: " << iter->native_file_string() << "\n" ; } }
3,113,134
3,113,878
Is it possible to convert vb.net source to C++?
Are there any tools converting vb.net source to C++ eg gnu C++. I know that Mono can transfer the projects to different platforms but i would rather prefer to convert the source. Since all we know that .net uses its own binary libs not available to other complilers is there any tool at least converting vb.net to C++ .net? Thanks in advance
C, C++, or Objective-C are a totally different family of languages to VB.NET. In addition, C++/CLI (what you've called C++.NET) will never run on an iPhone in the new language obligations. I think you'd need to start from scratch.
3,113,139
3,114,231
How to create map<string, class::method> in c++ and be able to search for function and call it?
I'm trying to create a map of string and method in C++, but I don't know how to do it. I would like to do something like that (pseudocode): map<string, method> mapping = { "sin", Math::sinFunc, "cos", Math::cosFunc, ... }; ... string &function; handler = mapping.find(function); int result; if (handler != NULL) result = (int) handler(20); To be honest I don't know is it possible in C++. I would like to have a map of string, method and be able to search for function in my mapping. If given string name of function exists then I would like to call it with given param.
Well, I'm not a member of the popular here Boost Lovers Club, so here it goes - in raw C++. #include <map> #include <string> struct Math { double sinFunc(double x) { return 0.33; }; double cosFunc(double x) { return 0.66; }; }; typedef double (Math::*math_method_t)(double); typedef std::map<std::string, math_method_t> math_func_map_t; int main() { math_func_map_t mapping; mapping["sin"] = &Math::sinFunc; mapping["cos"] = &Math::cosFunc; std::string function = std::string("sin"); math_func_map_t::iterator x = mapping.find(function); int result = 0; if (x != mapping.end()) { Math m; result = (m.*(x->second))(20); } } That's obviously if I have understood correctly that you want a method pointer, not a function/static method pointer.
3,113,178
3,113,357
Dealing with char buffers
As a C++ programmer I sometimes need deal with memory buffers using techniques from C. For example: char buffer[512]; sprintf(buffer, "Hello %s!", userName.c_str()); Or in Windows: TCHAR buffer[MAX_PATH+1]; // edit: +1 added ::GetCurrentDirectory(sizeof(buffer)/sizeof(TCHAR), &buffer[0]); The above sample is how I usually create local buffers (a local stack-allocated char array). However, there are many possible variations and so I'm very interested in your answers to the following questions: Is passing the buffer as &buffer[0] better programming style than passing buffer? (I prefer &buffer[0].) Is there a maximum size that is considered safe for stack allocated buffers? Update: I mean, for example, the highest value that can be considered safe for cross-platform desktop applications on Mac, Windows, Linux desktops (not mobile!). Is a static buffer (static char buffer[N];) faster? Are there any other arguments for or against it? When using static buffers you can use return type const char *. Is this (generally) a good or a bad idea? (I do realize that the caller will need to make his own copy to avoid that the next call would change the previous return value.) What about using static char * buffer = new char[N]; , never deleting the buffer and reusing it on each call. I understand that heap allocation should be used when (1) dealing with large buffers or (2) maximum buffer size is unknown at compile time. Are there any other factors that play in the stack/heap allocation decision? Should you prefer the sprintf_s, memcpy_s, ... variants? (Visual Studio has been trying to convince me of this for a long time, but I want a second opinion :p )
I assume your interest comes about primarily from a performance perspective, since solutions like vector, string, wstring, etc. will generally work even for interacting with C APIs. I recommend learning how to use those and how to use them efficiently. If you really need it, you can even write your own memory allocator to make them super fast. If you are sure they're not what you need, there's still no excuse for you to not write a simple wrapper to handle these string buffers with RAII for the dynamic cases. With that out of the way: Is passing the buffer as &buffer[0] better programming style than passing buffer? (I prefer &buffer[0].) No. I would consider this style to be slightly less useful (admittedly being subjective here) as you cannot use it to pass a null buffer and therefore would have to make exceptions to your style to pass pointers to arrays that can be null. It is required if you pass in data from std::vector to a C API expecting a pointer, however. Is there a maximum size that is considered safe for stack allocated buffers? This depends on your platform and compiler settings. Simple rule of thumb: if you're in doubt about whether your code will overflow the stack, write it in a way which can't. Is a static buffer (static char buffer[N];) faster? Are there any other arguments for or against it? Yes, there is a big argument against it, and that is that it makes your function no longer re-entrant. If your application becomes multithreaded, these functions will not be thread safe. Even in a single-threaded application, sharing the same buffer when these functions are recursively called can lead to problems. What about using static char * buffer = new char[N]; and never deleting the buffer? (Reusing the same buffer each call.) We still have the same problems with re-entrancy. I understand that heap allocation should be used when (1) dealing with large buffers or (2) maximum buffer size is unknown at compile time. Are there any other factors that play in the stack/heap allocation decision? Stack unwinding destroys objects on the stack. This is especially important for exception-safety. Thus even if you allocate memory on the heap within a function, it should generally be managed by an object on the stack (ex: smart pointer). ///@see RAII. Should you prefer the sprintf_s, memcpy_s, ... variants? (Visual Studio has been trying to convince me of this for a long time, but I want a second opinion :p ) MS was right about these functions being safer alternatives since they don't have buffer overflow problems, but if you write such code just as is (without writing variants for other platforms), your code will be married to Microsoft since it will be non-portable. When using static buffers you can use return type const char *. Is this (generally) a good or a bad idea? (I do realize that the caller will need to make his own copy to avoid that the next call would change the previous return value.) I'd say in almost every case, you want to use const char* for return types for a function returning a pointer to a character buffer. For a function to return a mutable char* is generally confusing and problematic. Either it's returning an address to global/static data which it shouldn't be using in the first place (see re-entrancy above), local data of a class (if it's a method) in which case returning it ruins the class's ability to maintain invariants by allowing clients to tamper with it however they like (ex: stored string must always be valid), or returning memory that was specified by a pointer passed in to the function (the only case where one might reasonably argue that mutable char* should be returned).
3,113,229
3,113,259
ofstream doesn't flush
I have the following code, running on Suse 10.1 / G++ 4.1.0, and it doesn't write to the file: #include <fstream> #include <iostream> int main(){ std::ofstream file("file.out"); file << "Hello world"; } The file is correctly created and opened, but is empty. If I change the code to: #include <fstream> #include <iostream> int main(){ std::ofstream file("file.out"); file << "Hello world\n"; } (add a \n to the text), it works. I also tried flushing the ofstream, but it didn't work. Any suggestions?
If you check your file doing a cat , it may be your shell that is wrongly configured and does not print the line if there is no end of line. std::endl adds a \n and flush.
3,113,413
3,113,431
Converting an uint64 to string in C++
What's the easiest way to convert an uint64 value into a standart C++ string? I checked out the assign methods from the string and could find no one that accepts an uint64 (8 bytes) as argument. How can I do this? Thanks
#include <sstream> std::ostringstream oss; uint64 i; oss << i; std:string intAsString(oss.str());
3,113,583
3,113,621
How could one implement C++ virtual functions in C
The C++ language provides virtual functions. Within the constraints of a pure C language implementation, how can a similar effect be achieved?
Stolen from here. From the C++ class class A { protected: int a; public: A() {a = 10;} virtual void update() {a++;} int access() {update(); return a;} }; a C code fragment can be derived. The three C++ member functions of class A are rewritten using out-of-line (standalone) code and collected by address into a struct named A_functable. The data members of A and combined with the function table into a C struct named A. struct A; typedef struct { void (*A)(struct A*); void (*update)(struct A*); int (*access)(struct A*); } A_functable; typedef struct A{ int a; A_functable *vmt; } A; void A_A(A *this); void A_update(A* this); int A_access(A* this); A_functable A_vmt = {A_A, A_update, A_access}; void A_A(A *this) {this->vmt = &A_vmt; this->a = 10;} void A_update(A* this) {this->a++;} int A_access(A* this) {this->vmt->update(this); return this->a;} /* class B: public A { public: void update() {a--;} }; */ struct B; typedef struct { void (*B)(struct B*); void (*update)(struct B*); int (*access)(struct A*); } B_functable; typedef struct B { A inherited; } B; void B_B(B *this); void B_update(B* this); B_functable B_vmt = {B_B, B_update, A_access}; void B_B(B *this) {A_A(this); this->inherited.vmt = &B_vmt; } void B_update(B* this) {this->inherited.a--;} int B_access(B* this) {this->inherited.vmt->update(this); return this->inherited.a;} int main() { A x; B y; A_A(&x); B_B(&y); printf("%d\n", x.vmt->access(&x)); printf("%d\n", y.inherited.vmt->access(&y)); } More elaborate than necessary, but it gets the point across.
3,113,667
3,113,874
Deleting user-defined vectors - C++
I have 2 classes, say A & B. Class B has a destructor of its own. Within class A, I have a vector of pointers to objects of class B. The vector is as follows: vector<B*> vect; In the destructor for class A, how do I retrieve memory? If I cycle through the vector, do I retrieve each object and use delete on every retrieved object? I tried that out in the destructor, but it segfaults. Any help in solving this problem is most welcome. I am sorry but I cannot post the code.
Some other posts pointed out that you're better of using smart pointers instead of pointers. If you have to use pointer for any reason whatsoever you should delete them in a loop first. for ( std::vector<B*>::iterator it = vect.begin(); it != vect.end(); ++it) delete (*it); vect.clear(); edit: If your program segfault in the destructor then your code is wrong. Maybe you put stack element by adress in the vector, but to delete an object it has to be on the heap. #include <iostream> #include <vector> #include <string> class data { public: std::string d; data(std::string _d) : d(_d) { } }; class container { public: std::vector<data*> c; container() { c.clear(); } void add (data *d) { c.push_back(d); } ~container() { for (std::vector<data*>::iterator it = c.begin(); it != c.end(); ++it) delete (*it); c.clear(); } }; int main (int argc, char* argv[]) { typedef std::vector<std::string> sVec; typedef sVec::iterator sVecIter; std::vector<std::string> cmd (argv+1, argv+argc); { container k; for (sVecIter it = cmd.begin(); it != cmd.end(); ++it) k.add(new data((*it))); } return 0; } This works without problem.
3,113,904
3,113,972
The python exception vs C++ exception handling
With the following code, I get the "Gotcha!" with python. try: x = 0 y = 3/x except Exception: # ZeroDivisionError print "Gotcha!" I think this is the equivalent C++ code, but it can't catch the exeption. #include <iostream> int main() { int x = 0; //float y = 3.0/x; int z = 0; try { z = 3 / x; } catch (std::exception) { std::cout << "Gotcha!"; } std::cout << z; } Floating point exception What went wrong? How can I catch this exception?
In C++, dividing by zero doesn't generate an exception; it causes undefined behaviour. You must check you divisor before actually performing the division, as there is no way to know what will happen if you do actually evaluate a division expression with a zero divisor.
3,113,929
3,113,948
How can I know the name of the exception in C++?
With Python, I could get the name of the exception easily as follows. run the code, i.e. x = 3/0 to get the exception from python "ZeroDivisionError: integer division or modulo by zero" tells me this is ZeroDivisionError Modify the code i.e. try: x=3/0 except ZeroDivisionError: DO something Is there any similar way to find the exception name with C++? When I run the x = 3/0, the compiled binary just throws 'Floating point exception', which is not so useful compared to python.
While you can't easily ask for the name of the exception, if the exception derives from std::exception you can find out the specified reason it was shown with what(): try { ... } catch (const std::exception &exc) { std::err << exc.what() << std::endl; } On a side note, dividing by 0 is not guaranteed to raise a C++ exception (I think the MS platforms may do that but you won't get that on Linux).
3,113,962
3,114,214
Question about rvalue in C++0x
I create many times I use class DataBuffer in many places in code, so it should be fast and lightweight. Moreover I use various buffer sizes, so to reduce memory allocations I wrote such template: template<unsigned int T_buffer_size> class DataBuffer { public: DataBuffer (const unsigned int &buffer_size); char buffer [T_buffer_size]; const unsigned int buffer_size; }; The problem is, that i have to copy DataBuffer objects few times. That's why I'm wondering if move constructor can help here. Is there an easy way to move my 'buffer' array between objects? It's easy to implement this class: class DataBuffer { public: DataBuffer (const unsigned int &buffer_size); char *buffer; const unsigned int buffer_size; }; But because 'buffer' is a regular pointer it takes more time to access data stored inside it...
But because 'buffer' is a regular pointer it takes more time to access data stored inside it... I think you're mistaken. Accessing an array on the heap is not necessarily slower than accessing one on the stack, e.g. The real difference will be in creating and destroying the array. You can't really have it both ways, directly speaking (but do read further). If your DataBuffer allocates on the heap, it will pay the price for the overhead of heap-based allocation and deallocation, but you will be able to shallow swap the data and implement something like a move constructor (see Alexandrescu's mojo as a simple proposal to the problem). If it allocates data on the stack, then it will be very fast to create and destroy, but will have to deep copy data which can be a bit expensive (though memcpy is awfully fast and perfectly fine for a char buffer). However, you can get the best of both worlds by writing your own memory allocator. I only recommend doing this if you really want to put the effort into it and have seen, with the aid of the profiler, that this is a real bottleneck. I don't have the time or room to teach you this here, but I must warn you that it is not as trivial as it seems to write one (consider alignment as an example). The determination of whether you go for the first example or the second should primarily be dictated by whether you can always determine the buffer size at compile time. If so, go for the first solution as it allows the buffer to be allocated on the stack or the heap. You can still shallow swap data by doing: DataBuffer<some_size>* d1 = new DataBuffer<some_size>; DataBuffer<some_size>* d2 = 0; std::swap(d1, d2); ... or for more sophisticated examples, you can use things like boost::shared_ptr.
3,113,965
3,114,694
Programmatically make a Header item 'hot' or 'selected'
I'm using a Win32 Header. I want to make it so that the header item I click on stays 'selected' or looks selected until I press another one. I want to avoid disabling it for aesthetic reasons. Thanks
If this header is part of a listview, you can provide a visual clue with ListView_SetSelectedColumn
3,113,997
3,114,098
SVNKit like wrapper for C or C++
Before I start building one myself; Is there a wrapper for C or C++ which does the same thing as SVNKit?
There is an API provided in C - see the Subversion Documentation
3,114,086
3,114,150
Error processing : return value vs exception in C++
In the course of asking about catching 'divide by 0' exception, I found that with C++, we can't do that. I mean, divide by 0 doesn't throw an std::exception. Some of the hints that I found were I have to check the value, and throw the exception by self. I say it's confusing, as I've thought that C++ adopted the exception idea in order to replace the 'good old C/UNIX report error by returning value method'. Here are my questions Q1 : Why C++ doesn't throw std::exception error for divide by 0? Is there any reason behind that? Q2 : Normally, what error processing scheme the C++ users use? Always throw an error, and the exception is the divide by 0 error? Q3 : In general, OOP languages prefer (or even enforce) using exception. Is this correct?
C++ assumes you know what you're doing, doesn't pay for things you don't ask for, and makes no assumptions about the platforms it's intended for. If you want to divide numbers, it would be quite inefficient to mandate the compiler check the denominator and throw before dividing. (We didn't ask it to do that.) So that option is out; we can't have this check on every division, and it's especially wasteful since most divisions are not by zero. So, how can we just divide by zero and find out if it worked? Because C++ cannot assume anything about it's platform, it cannot assume there is a way to check the result, hardware-wise. That is to say, while many CPU's will jump to an interrupt of some sort when division by zero occurs, the C++ language cannot guarantee such a thing. The only option then is to let the behavior be undefined. And that's exactly what you get: undefined behavior. OOP languages might do something or another, it doesn't matter since OOP isn't well-defined and C++ isn't an OOP language anyway. In general, use the tool that's most appropriate. (Exceptions are for exceptional situations.)
3,114,124
3,114,174
In C/C++, are volatile variables guaranteed to have eventually consistent semantics betwen threads?
Is there any guarantee by any commonly followed standard (ISO C or C++, or any of the POSIX/SUS specifications) that a variable (perhaps marked volatile), not guarded by a mutex, that is being accessed by multiple threads will become eventually consistent if it is assigned to? To provide a specific example, consider two threads sharing a variable v, with initial value zero. Thread 1: v = 1 Thread 2: while(v == 0) yield(); Is thread 2 guaranteed to terminate eventually? Or can it conceivably spin forever because the cache coherency never kicks in and makes the assignment visible in thread 2's cache? I'm aware the C and C++ standards (before C++0x) do not speak at all about threads or concurrency. But I'm curious if the C++0x memory model, or pthreads, or anything else, guarantees this. (Apparently this does actually work on Windows on 32-bit x86; I'm wondering if it's something that can be relied on generally or if it just happens to work there).
It's going to depend on your architecture. While it is unusual to require an explicit cache flush or memory sync to ensure memory writes are visible to other threads, nothing precludes it, and I've certainly encountered platforms (including the PowerPC-based device I am currently developing for) where explicit instructions have to be executed to ensure state is flushed. Note that thread synchronisation primitives like mutexes will perform the necessary work as required, but you don't typically actually need a thread synchronisation primitive if all you want is to ensure the state is visible without caring about consistency - just the sync / flush instruction will suffice. EDIT: To anyone still in confustion about the volatile keyword - volatile guarantees the compiler will not generate code that explicitly caches data in registers, but this is NOT the same thing as dealing with hardware that transparently caches / reorders reads and writes. Read e.g. this or this, or this Dr Dobbs article, or the answer to this SO question, or just pick your favourite compiler that targets a weakly consistent memory architecture like Cell, write some test code and compare what the compiler generates to what you'd need in order to ensure writes are visible to other processes.
3,114,189
3,114,407
Is there a simple way to forward to a member function with a matching function signature?
Is there a simple way to forward to a member function with a matching function signature? typedef std::tr1::function<int(int,int,int,int)> TheFn; class C { int MemberFn(int,int,int,int) { return 0; } TheFn getFn() { //is there a simpler way to write the following line? return [this](int a,int b,int c,int d){ return this->MemberFn(a,b,c,d); }; } };
Have you tried bind? // C++0x update struct test { void f( int, int, int, int ); }; int main() { std::function<void (int,int,int,int)> fn; test t; fn = std::bind( &t::f, &t, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4 ); fn( 1, 2, 3, 4 ); // t.f( 1, 2, 3, 4 ) } I have left the full qualification of all elements, but std::placeholders applied so many times don't really help readability... I guess a using std::placeholders would not hurt at all: using std::placeholders; fn = std::bind( &t::f, &t, _1, _2, _3, _4 ); EDIT: To make it closer to the question code, so that it is clearer that this has the exact same functionality that the original code: typedef std::function<int(int,int,int,int)> TheFn; class C { int MemberFn( int, int, int, int ) { return 0; } public: int MemberFn2(int,int,int,int) { return 2; } TheFn getFn() { using std::placeholders; return std::bind( &C::MemberFn, this, _1, _2, _3, _4 ); } }; int main() { C instance; TheFn fn1 = instance.getFn(); std::cout << fn1( 1, 2, 3, 4 ) << std::endl; // 0 using std::placeholders; TheFn fn2 = std::bind( &C::MemberFn2, &instance, _1, _2, _3, _4 ); std::cout << fn2( 1, 2, 3, 4 ) << std::endl; } As you can see in both cases you are doing the same. I have used private and public methods for the example to show that when you bind, the member method access level is checked at the place of bind, not at the place of call. So even if MemberFn is private within the class you can call it through the binded functor. If the member is public, you can actually bind from outside of the class.
3,114,223
3,114,290
How do I write a C++ dictionary to a Lua table?
I have some C++ code that interacts with some Lua code. Basically, I want to be able to get some results (in the form of a dictionary a.k.a. a collection of items) from a query message and then push them out to Lua as a table so that I can easily access all the results from Lua by using the dictionary. Right now, I just get one specific value that I want and send that out but it would be nice to send all of them out and not have to request a specific one.
Assuming you're familiar with the Lua API in general, here's the basic process: Create a new table on the stack (lua_newtable) For each item in the dictionary Push the value onto the stack Push the key onto the stack Call lua_settable
3,114,339
3,114,360
Converting COFF lib file to OMF format
Is there any way to convert COFF library (lib file) to OMF library for using with C++Builder6 ? This coff is not just import library, it conatians some code. When I try to convert it using borland's coff2omf.exe, I get 1KB file from 15KB file.
It's fairly typical for an OMF object file to be a lot smaller than an equivalent COFF object, so what you're getting may well be valid. If you find that it's really not, you can probably break the lib file into individual object files, disassemble the object files, re-assemble them to OMF object files, and put those together into an OMF lib file.
3,114,376
3,120,737
Can't draw triangles in OpenGL but other primitives render fine
Good afternoon, I'm trying to learn to use a graphics library that uses OpenGL. I can draw 2D primitives (text and lines) but 3D triangles don't render. I've tried everything I can think of but as an OpenGL newcomer I've probably missed something obvious. This code is not intended to be efficient. I'm trying to get it to work first. Here's the setup at startup: // 800 by 600 windows 32 bit depth Driver->setDisplay( UDriver::CMode( ScreenWidth, ScreenHeight, 32 ) ); NL3D::CViewport viewport; viewport.initFullScreen(); Driver->setViewport( viewport ); NLMISC::CMatrix mtx; mtx.identity(); Driver->setViewMatrix( mtx ); Driver->setModelMatrix( mtx ); // screen size is same as pixel resolution // CFrustum(float left, float right, float bottom, float top, float znear, float zfar, bool perspective= true) Driver->setMatrixMode2D( CFrustum( 0.0f, ScreenWidth, 0.0f, ScreenHeight, -2.0f, 10000.0f, false ) ); Here's the code in my rendering loop: static NL3D::CMaterial mat; mat.initUnlit(); mat.setColor( CRGBA( 255, 255, 0, 128 ) ); float x = 200.0f; float y = 200.0f; float width = 200.0f; // (float)ScreenWidth * 0.125f; float height = 200.0f; // (float)ScreenHeight * 0.125f; static NL3D::CVertexBuffer vb; if ( vb.getName().empty() ) vb.setName("drawBitmap"); vb.setVertexFormat( NL3D::CVertexBuffer::PositionFlag | NL3D::CVertexBuffer::TexCoord0Flag ); vb.setNumVertices( 4 ); { NL3D::CVertexBufferReadWrite vba; vb.lock( vba ); vba.setVertexCoord( 0, NLMISC::CVector( x, 0, y ) ); vba.setVertexCoord( 1, NLMISC::CVector( x + width, 0, y ) ); vba.setVertexCoord( 2, NLMISC::CVector( x + width, 0, y + height ) ); vba.setVertexCoord( 3, NLMISC::CVector( x, 0, y + height ) ); vba.setTexCoord( 0, 0, 0.f, 1.f ); vba.setTexCoord( 1, 0, 1.f, 1.f ); vba.setTexCoord( 2, 0, 1.f, 0.f ); vba.setTexCoord( 3, 0, 0.f, 0.f ); } dynamic_cast<NL3D::CDriverUser*>(Driver)->getDriver()->activeVertexBuffer( vb ); static NL3D::CIndexBuffer pb; if ( pb.getName().empty() ) pb.setName("drawBitmap"); pb.setFormat( NL_DEFAULT_INDEX_BUFFER_FORMAT ); pb.setNumIndexes( 6 ); { CIndexBufferReadWrite iba; pb.lock( iba ); iba.setTri( 0, 0, 1, 2 ); iba.setTri( 3, 2, 3, 0 ); } dynamic_cast<NL3D::CDriverUser*>(Driver)->getDriver()->activeIndexBuffer( pb ); dynamic_cast<NL3D::CDriverUser*>(Driver)->getDriver()->renderTriangles( mat, 0, 2 ); Any suggestions? Thanks
It turned out to be multiple OpenGL contexts. It wasn't setting things back before trying to draw.
3,114,460
3,114,520
Need to make context available to C++ ostream insertion operators
For an API that I am working on, I want to allow the user to insert custom objects into an ostream, but these objects have no meaning on their own, and are too memory constrained to include an additional pointer or reference for context. (Think tens of millions of 16-/32-/48-bit objects in an embedded system with limited memory.) Suppose the user initializes the underlying context, and looks up one of these objects: DDB ddb("xc5vlx330t"); Tilewire tw = ddb.lookUpTilewire("DSP_X34Y0", "DSP_IMUX_B5_3"); ... std::cout << complexDataStructure; In an entirely different scope, possibly nested far away from the user's explicit code, we may need to insert the object into an ostream, with ddb unavailable. os << tw; The actual value encapsulated by tw is 97,594,974, but the desired output is this: DSP_IMUX_B5_3@[263,84] DSP "DSP_X34Y0" (1488@77406) In order for this to work, the appropriate insertion operator would need access to ddb, but it cannot rely on static or global variables or functions (for multithreading reasons). What I'd like to do is allow the user to request and use a stream wrapper kind of like this: ostream& wrappedCout = ddb.getWrappedOstream(std::cout); The returned subclass of ostream would include a reference to ddb for use by special stream inserters that needed it, and a reference to the original stream—std::cout in this case—where it would forward all of its output. Unfortunately, the inheritance or composition schemes that I have come up with are messy to code up (not an enormous concern), and possibly problematic for the user (a much larger concern). Any suggestions on how to elegantly make ddb available to insertion operators? I am marginally aware of boost.Iostreams, but not sure that it will help me out here.
Write a custom stream manipulator that stores a reference to ddb using the iword/pword mechanism. Here is an example, you'd need to add locking around the iwork_indexes map in a multithreaded program. class dbb { public: explicit dbb(int value) : m_value(value) {} int value() const { return m_value; } private: int m_value; }; class dbb_reliant_type { public: dbb_reliant_type(const std::string& value) : m_value(value) {} const std::string& value() const { return m_value; } private: std::string m_value; }; typedef std::map<std::ostream*, int> iword_map; iword_map iword_indexes; inline int get_iword_index(std::ostream& os) { iword_map::const_iterator index = iword_indexes.find(&os); if(index == iword_indexes.end()) { std::pair<iword_map::iterator, bool> inserted = iword_indexes.insert(std::make_pair(&os, os.xalloc())); index = inserted.first; } return index->second; } inline std::ostream& operator<<(std::ostream& os, const dbb& value) { const int index = get_iword_index(os); if(os.pword(index) == 0) os.pword(index) = &const_cast<dbb&>(value); return os; } std::ostream& operator<<(std::ostream& os, const dbb_reliant_type& value) { const int index = get_iword_index(os); dbb* deebeebee = reinterpret_cast<dbb*>(os.pword(index)); os << value.value() << "(" << deebeebee->value() << ")"; return os; } int main(int, char**) { dbb deebeebee(5); dbb_reliant_type variable("blah"); std::cout << deebeebee << variable << std::endl; return 0; }
3,114,577
3,114,620
forward class friend declaration
Hi i have a problem, I try to do the follow, class A depends on class B and vice versa like this class A; class B{ A foo; friend B A::doSomething(); }; class A { B bar; B doSomething; }; The friend declartion does not work because A is an incomplete declartion. Is there any way to avoid this? (Swapp classes declaration order is not a solution I did not want to construct a more complicated example where swapping does not work anymore)
What you're trying to do right now would make your classes infinitely large (as I understand, bar and foo are class member variables, hence this means that B includes A, which includes B, ...). You could use pointers and store A* foo or B* bar in one of your classes or somehow redesign your application to avoid this circular dependency.
3,114,671
3,114,700
Winpcap saving raw packets not from an adapter
I am trying to build an application that converts my old custom Ethernet logs (bin files) to standard winpcap style logs. The problem is that I can't seem to find an example of how to opening a pcap_t* without using an adapter (network card). The temp.pkt has not been created. I have looked thou the examples provided with Winpcap and all of them use a live adapter when dumping packets. This example is the closest \WpdPack\Examples-pcap\savedump\savedump.c is the closest, see example below slightly modified. #ifdef _MSC_VER /* * we do not want the warnings about the old deprecated and unsecure CRT functions * since these examples can be compiled under *nix as well */ #define _CRT_SECURE_NO_WARNINGS #endif #include "pcap.h" int main(int argc, char **argv) { pcap_if_t *alldevs; pcap_if_t *d; int inum; int i=0; pcap_t *adhandle; char errbuf[PCAP_ERRBUF_SIZE]; pcap_dumper_t *dumpfile; /* Open the adapter */ if ((adhandle= pcap_open(??????, // name of the device 65536, // portion of the packet to capture. // 65536 grants that the whole packet will be captured on all the MACs. 1, // promiscuous mode (nonzero means promiscuous) 1000, // read timeout errbuf // error buffer )) == NULL) { fprintf(stderr,"\nUnable to open the adapter. %s is not supported by WinPcap\n", d->name); /* Free the device list */ pcap_freealldevs(alldevs); return -1; } /* Open the dump file */ dumpfile = pcap_dump_open(adhandle, argv[1]); if(dumpfile==NULL) { fprintf(stderr,"\nError opening output file\n"); return -1; } // --------------------------- struct pcap_pkthdr header; header.ts.tv_sec = 1 ; /* seconds */ header.ts.tv_usec = 1; /* and microseconds */ header.caplen = 100; /* length of portion present */ header.len = 100 ; /* length this packet (off wire) */ u_char pkt_data[100]; for( int i = 0 ; i < 100 ; i++ ) { pkt_data[i] = i ; } pcap_dump( (u_char *) dumpfile, &header, (u_char *) &pkt_data); // --------------------------- /* start the capture */ // pcap_loop(adhandle, 0, packet_handler, (unsigned char *)dumpfile); pcap_close(adhandle); return 0; }
If all you're doing is converting your own file format to .pcap, you don't need a pcap_t*, you can just use something like: FILE* create_pcap_file(const char *filename, int linktype) { struct pcap_file_header fh; fh.magic = TCPDUMP_MAGIC; fh.sigfigs = 0; fh.version_major = 2; fh.version_minor = 4; fh.snaplen = 2<<15; fh.thiszone = 0; fh.linktype = linktype; FILE *file = fopen(filename, "wb"); if(file != NULL) { if(fwrite(&fh, sizeof(fh), 1, file) != 1) { fclose(file); file = NULL; } } return file; } int write_pcap_packet(FILE* file,size_t length,const unsigned char *data,const struct timeval *tval) { struct pcap_pkthdr pkhdr; pkhdr.caplen = length; pkhdr.len = length; pkhdr.ts = *tval; if(fwrite(&pkhdr, sizeof(pkhdr), 1, file) != 1) { return 1; } if(fwrite(data, 1, length, file) != length) { return 2; } return 0; }
3,114,695
3,114,832
Installing Allegro in Dev-C++ using their Packages
I'm trying to install Allegro in Dev-C++, and rather than do it manually, I noticed the new version was in the available packages, so that'd be easier. Here it is in the manager. Here it is showing itself containing the header file. And when I try to run the simplest of Allegro programs, it doesn't recognize it. Anyone know how to fix this? Or a better way to do it? Thanks.
You need to configure your project to reference the correct libraries. MinGW does not support auto-linking, so you'll need to configure DevCPP's project file to point MinGW at the right location.
3,114,776
3,114,989
How to concatenate using lstrcat in Visual C++?
I would like to append two strings together so that I can rename a file using the MoveFile function. But my strings refuse to concatenate, so instead of adding "E:\" to "FILE-%s-%02d%02d%02d-%02d%02d.txt" to give me "E:\FILE-%s-%02d%02d%02d-%02d%02d.txt", it gives me just "E:\" as if nothing happened. Here is a snippet of my full code: drivePathAgain = "E:\\"; sprintf(newname, "FILE-%s-%02d%02d%02d-%02d%02d.txt", szVolNameBuff, lt.wYear, lt.wMonth, lt.wDay, lt.wHour, lt.wMinute); lstrcat((LPWSTR)drivePathAgain, (LPWSTR)newname); result = MoveFile((LPCWSTR) drivePath, (LPCWSTR) drivePathAgain ); I can't append newname to drivePathAgain. If you need me to post the entire code to get the big picture, I can. Is there a way to append strings like that? Thanks
Based on your casting to LPWSTR, I would assume your project is setup in Unicode mode. That means functions like lstrcpy and MoveFile are accepting pointers to strings of wchar_t not char. If you don't know what this means, you need to research the difference between Ascii and Unicode. I would suspect that may be the source of your problem. And even if it isn't, casting from char* to wchar_t* (also known as LPWSTR) will likely cause problems for you eventually. Casting pointers is not the same as converting from one of those string types to the other.
3,114,806
3,115,007
Creating a Lua Table from a const char **
I have a const char ** which is going to be of varying lengths, but I want to create a Lua array from the const char **. Myconst char ** is something like this arg[0]="Red" arg[1]="Purple" arg[2]="Yellow" I need to convert this array to a global table in Lua, but I'm not sure about how to go about this as I'm not very good at manipulating Lua.
int main() { char* arg[3] = { "Red", "Purple", "Yellow" }; //create lua state Lua_state* L = luaL_newstate(); // create the table for arg lua_createtable(L,3,0); int table_index = lua_gettop(L); for(int i =0; i<3; ++i ) { // get the string on Lua's stack so it can be used lua_pushstring(L,arg[i]); // this could be done with lua_settable, but that would require pushing the integer as well // the string we just push is removed from the stack // notice the index is i+1 as lua is ones based lua_rawseti(L,table_index,i+1); } //now put that table we've been messing with into the globals //lua will remove the table from the stack leaving it empty once again lua_setglobal(L,"arg"); }
3,114,815
3,114,887
What control style is this?
I want to make a control where the bottom is nice and beveled as seen here: http://img19.imageshack.us/f/finalzh.png/ alt text http://img19.imageshack.us/f/finalzh.png/ What style must I add to my control to achieve the same look as this? Thanks
You could create a static control with a WS_EX_CLIENTEDGE or WS_EX_WINDOWEDGE extended style, and place it in a containing child window, which clips the top and sides so you only see the bottom bevel. Looking at the picture, you may even not need the child window - just position the static window at -4x-4 (use GetSystemMetrics SM_CX_BORDER to find out the real size of the window border) and size it 2x the border width larger that needed.
3,114,949
3,114,978
Anyone with experience on embedding CINT into a C++ app?
I'm talking about ROOT's CINT. I've been developing a game in c++ which uses Python for programming the AI. As much as I love Python, and how easy it makes programming the AI (generators and FP are really sexy), it makes non trivial algorithms run so slow. Then I remembered I read somewhere about CINT, and how it can be embeddable. Now I need your help to decide if implement CINT as an alternate scripting system. With python I use Boost::Python, which makes it almost unpainful to expose classes and objects once you get used to it. Is there such ease with CINT?
I've written classes compiled against Root, and then accessed them directly in the interpreter. That's easy, though all such classes are expected to derive from TObject. What I don't know is if that is a cint requirement or a ROOT requirement. you might be best off asking on the RootTalk CINT Support forum To address the questions in the comments: The derivation from TObject can be second hand: your classes can be derived from something derived from TObject, it just has to be a TObject. Root provides a tool (makecint) and some macros (ClassDef and ClassImp) to support integrating your code with the interpreted execution environment: write your clas deriving it from TObject; include the ClassDef macro in the header and the ClassImp macro in the source file; run makecint over the code to generate all the tedious integration nonesense, then compile your code and the generated code to a shared object (or, I presume, a dll on a windows box); start the interpreter; load the library with .L; and your class is fully integrated with the interpreted environment (tab completion will work and all that). The build can be automated with make (and presumable other tools). ##Again,## I don't know how much of this belongs to ROOT and how much to cint. But it is all open source, so you can snag and adapt what you need.
3,114,997
3,586,308
TOUGH: Dealing with deeply nested pointers in C++
I define this structure: struct s_molecule { std::string res_name; std::vector<t_particle> my_particles; std::vector<t_bond> my_bonds; std::vector<t_angle> my_angles; std::vector<t_dihedral> my_dihedrals; s_molecule& operator=(const s_molecule &to_assign) { res_name = to_assign.res_name; my_particles = to_assign.my_particles; my_bonds = to_assign.my_bonds; my_angles = to_assign.my_angles; my_dihedrals = to_assign.my_dihedrals; return *this; } }; and these structures: typedef struct s_particle { t_coordinates position; double charge; double mass; std::string name; std::vector<t_lj_param>::iterator my_particle_kind_iter; s_particle& operator=(const s_particle &to_assign) { position = to_assign.position; charge = to_assign.charge; mass = to_assign.mass; name = to_assign.name; my_particle_kind_iter = to_assign.my_particle_kind_iter; return *this; } } t_particle; struct s_bond { t_particle * particle_1; t_particle * particle_2; std::vector<t_bond_param>::iterator my_bond_kind_iter; s_bond& operator=(const s_bond &to_assign) { particle_1 = to_assign.particle_1; particle_2 = to_assign.particle_2; my_bond_kind_iter = to_assign.my_bond_kind_iter; return *this; } }; and then in my code I return a pointer to an s_molecule (typedef'd to t_molecule, but still). Using this pointer I can get this code to work: for (unsigned int i = 0; i < current_molecule->my_particles.size(); i++) { std::cout << "Particle " << current_molecule->my_particles[i].name << std::endl << "Charge: " << current_molecule->my_particles[i].charge << std::endl << "Mass: " << current_molecule->my_particles[i].mass << std::endl << "Particle Kind Name: " << (*current_molecule->my_particles[i].my_particle_kind_iter).atom_kind_name << std::endl << "x: " << current_molecule->my_particles[i].position.x << " y: " << current_molecule->my_particles[i].position.y #ifdef USE_3D_GEOM << "z: " << current_molecule->my_particles[i].position.z #endif << std::endl; } If I replace it with: for (std::vector<t_particle>::iterator it = current_molecule->my_particles.begin(); it !=current_molecule->my_particles.end(); it++) { std::cout << "Particle " << (*it).name << std::endl << "Charge: " << (*it).charge << std::endl << "Mass: " << (*it).mass << std::endl << "Particle Kind Name: " << (*(*it).my_particle_kind_iter).atom_kind_name << std::endl << "x: " << (*it).position.x << " y: " << (*it).position.y #ifdef USE_3D_GEOM << "z: " << (*it).position.z #endif << std::endl; } I now get nasty segfaults... Not to put too much here, but I'm also getting segfaults when I tried to do this: std::cout << "Bond ATOMS : " << (*current_molecule).my_bonds[0].particle_1->name << std::endl Again, current_molecule is a pointer to a s_molecule structure, which contains arrays of structures, which in turn either directly have vars or are pointers. I can't get these multiple layers of indirection to work. Suggestions on fixing these segfaults. FYI I'm compiling on Linux Centos 5.4 with g++ and using a custom makefile system.
Again, this issue was answered here: Weird Pointer issue in C++ by DeadMG. Sorry for the double post.
3,115,087
3,115,128
Add tabs in reverse order?
By default tabs get added from right to left, so if I insert 1,2,3,4,5 then the tabs will read 5,4,3,2,1. How can I make it read 1,2,3,4,5 thanks. http://img96.imageshack.us/i/ahhh.png/ http://img96.imageshack.us/i/ahhh.png This is obtained from inserting Untitled Project first and Untitled 5 last. What I would want would be for Untitled 5 to be selected at the far right and for Untitled Project to be at the far left and the ones inbetween following this idea...
Insert them in the correct order in the first place. If they're already there and you want to reorder them, remove them, sort them how you want, and then add them in the correct order.
3,115,133
3,115,137
Header files included in multi .cpp files
I followed a simple example as below. But compile failed. Could you please have a look and give me some suggestion. vs2010 console application used.Thank you. Error message pgm.h(11): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int pgm.h(11): error C2143: syntax error : missing ',' before '&' 1> multi_fct.cpp pgm.h(11): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int pgm.h(11): error C2143: syntax error : missing ',' before '&' 1> ch3_p96.cpp pgm.h(11): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int pgm.h(11): error C2143: syntax error : missing ',' before '&' ch3_p96.cpp(24): error C2664: 'prn_info' : cannot convert parameter 1 from 'const char [8]' to 'const int' 1> There is no context in which this conversion is possible ch3_p96.cpp(26): error C3861: 'fct1': identifier not found pgm.h #include <iostream> #include <cstdlib> #include <string> #define N 3 void fctl(int k); void fct2(); void prn_info(const string& pgm_name); ch3_p96.cpp #include "stdafx.h" #include <iostream> #include "pgm.h" using namespace std; int main() { char ans; int k, n = N; cout << "This program does not do very much.\n"; cout << "Do you want more information?\n"; cout << "Enter either y or Y is yes.\n" << endl; cin >> ans; if (ans == 'y' || ans == 'Y') prn_info("ch3_p96"); // multi_main for (k = 0; k < n; ++k) fct1(k); cout << "Best Regards!" << endl; } multi_fct.cpp #include "StdAfx.h" #include <iostream> #include "pgm.h" using namespace std; void fct1(int n) { int i; cout << "Hello from fct1()" << endl; for (i = 0; i < n; ++i) fct2(); } void fct2() { cout << "Hello from fct2()" << endl; } multi_prn.cpp #include "StdAfx.h" #include <iostream> #include <string> #include "pgm.h" using namespace std; void prn_info(const string& pgm_name) { cout << "Usage: " << pgm_name << endl; cout << "This program illustrates a " << endl; cout << "Program is more than one file. " << endl; cout << "In this example, a single" << endl; cout << ".h file is included at the" << endl; cout << "top of our three .cpp files." << endl; cout << "Thus pgm.h acts as the \"glue\"" << endl; cout << "that binds the program." << endl; }
You need to namespace qualify string: std::string. The compiler error is saying that it didn't find a type name, so it's guessing that string is an int, and continuing to try and parse your code. Also, in one place you use fctl (fct lower-case-L) and in one place you use fct1 (fct one).
3,115,146
3,115,153
Parsing a line with a variable number of entries in C or C++ (no boost)
I have a file containing lines of the form, double mass, string seq, int K, int TS, int M, [variable number of ints] 688.83 AFTDSK 1 1 0 3384 2399 1200 790.00 MDSSTK 1 3 1 342 2 I need a (preferably simple) way of parsing this file without boost. If the number of values per line had been constant then I would have used the solution here. Each line will become an object of class Peptide: class Peptide { public: double mass; string sequence; int numK; int numPTS; int numM; set<int> parents; } The first three integers have specific variable names in the object while all the following integers need to be inserted into a set. I was fortunate enough to get two really awesome responses but the run time differences made the C implementation the best answer for me.
The best way I know of to parse an ascii text file is to read it line-by-line and use strtok. It's a C function, but it'll break your input into individual tokens for you. Then, you can use the string parsing functions atoi and strtod to parse your numeric values. For the file format you specified, I'd do something like this: string line; ifstream f(argv[1]); if(!f.is_open()) { cout << "The file you specified could not be read." << endl; return 1; } while(!f.eof()) { getline(f, line); if(line == "" || line[0] == '#') continue; char *ptr, *buf; buf = new char[line.size() + 1]; strcpy(buf, line.c_str()); Peptide pep; pep.mass = strtod(strtok(buf, " "), NULL); pep.sequence = strtok(NULL, " "); pep.numK = strtol(strtok(NULL, " "), NULL, 10); pep.numPTS = strtol(strtok(NULL, " "), NULL, 10); pep.numM = strtol(strtok(NULL, " "), NULL, 10); while(ptr = strtok(NULL, " ")) pep.parents.insert(strtol(ptr, NULL, 10)); cout << "mass: " << mass << endl << "sequence: " << sequence << endl << "numK: " << numK << endl << "numPTS: " << numPTS << endl << "numM: " << numM << endl << "parents:" << endl; set<int>::iterator it; for(it = parents.begin(); it != parents.end(); it++) cout << "\t- " << *it << endl; } f.close();
3,115,147
3,116,917
Creating a control like this
How could I create a control that looks like this one: http://img195.imageshack.us/img195/4268/eeeeae.png http://img195.imageshack.us/img195/4268/eeeeae.png I just want that small end. Thanks
If that's a Windows ComboBox control with a visual style applied to it, you can render its themed button wherever you like using DrawThemeBackground() and CP_DROPDOWNBUTTON.
3,115,188
3,118,879
How does Snipping Tool do this?
I noticed that Snipping Tool (On Windows Vista / 7) has a Toolbar control. I'v used Spy++ and copied its exact styles but when I press down, it does not do like theirs. Theirs stays stuck on the clicked control, indicating that this tool is 'in use' I want to have this effect in my application. Thanks
I don't have a NT6 system near me ATM but I think you are just talking about the BSTYLE_CHECK toolbar button style
3,115,314
3,115,437
Decorator vs Strategy Pattern (vs ?) to extend functionality
I've been trying to read through different implementations of Scene Graphs for 3D engine development to learn design patterns used in this domain, but unfortunately the code bases are too big for me grasp (yet, hopefully). So, let's say we have a class Model that stores pointers to geometry, shaders, textures etc. and we want to allow animation of each of the members separately, say GeometryAnimator, TextureAnimator and so on, but a Model could also be static of course. What I see is that both the strategy pattern (with no-op for static entities) and the decorator pattern could be used to achieve this. What are the benefits/drawbacks of each in this application? Or do I over complicate matters? Thanks for your help!
A simple yet perfectly fine solution for this is to establish interfaces/abstact base classes for all the various things that a scene node can represent. class Texture { ... }; class Geometry { ... }; // etc class SceneNode { public: // The following return null by default but // can be overriden by SceneNode subclasses // to return interface pointers. virtual Geometry* geometry() { return 0; } virtual Texture* texture() { return 0; } }; class Model: public SceneNode, public Texture, public Geometry { public: // Override the functions of inherited interfaces virtual Geometry* geometry() { return this; } virtual Texture* texture() { return this; } }; This is actually the approach that high-end 3D packages take in some form or another. With it, given any scene node, you can query it if it supports a particular interface (ex: a texture one) and then do animation through that, e.g. Maya and XSI do this but with an interface method capable of returning all interfaces that returns void* which the client has to cast accordingly. They then create reference types that hide the casting required. You don't need to always resort to classic design patterns for all of your programming solutions. Consider them as tools and suggestions but always asking which design pattern would work for a given problem will not always lead to the most straightforward solution. You have to think for yourself but design patterns can help you.
3,115,561
3,116,198
Calling shutdown and closesocket twice on same socket
In my application I call shutdown and closesocket functions twice on the same socket. I know this is not right thing to do and I have to ensure that these functions are called only once. But why don't either of these calls fail when called a second time? If the handle of m_Socket is 1500, then what will it's value be when shutdown and closesocket functions are called on it? shutdown(m_SocServer, 2); closesocket(m_SocServer);
First one must distinguish two different things: Performing operations on a socket, some of which may bring it in an unusable state. Terminating the socket handle. Calling shutdown with parameter 2 (which is SD_BOTH) is (1). That is, you flush all the pending out buffer, plus discard all the receive buffer. So that you can't read/write anymore. However you still hold a valid socket handle. You still may query/set its options if you want. For instance, one could call getpeername on it to discover the address you were connected to. Also, depending on the implementation, calling shutdown again doesn't have to result in an error. Maybe it has an accumulative effect. On the other hand calling closesocket is (2). Once you called it - you can't do anything with that socket handle. It's now invalid. If you socket has a value of 1500 - it will still have it, even after a call to closesocket. Because it's just a variable. It's like asking what value will have the pointer after you delete it. However this socket value (1500) is no more valid. You can't call any socket function with this value. Moreover, if you create another socket meanwhile - it's very likely to receive the same number. Here you may find yourself in a more severe problem - doing actions on another socket without noticing it. For some it's a good practice assigning INVALID_SOCKET value to a socket variable right after you call closesocket on it. P.S. Perhaps calling shutdown + closesocket don't fail specifically because you're closing another socket.
3,115,628
3,115,647
condition execution using if or logic
when using objects I sometimes test for their existence e.g if(object) object->Use(); could i just use (object && object->Use()); and what differences are there, if any?
They're the same assuming object->Use() returns something that's valid in a boolean context; if it returns void the compiler will complain that a void return isn't being ignored like it should be, and other return types that don't fit will give you something like no match for 'operator&&'
3,115,733
3,116,215
Killing the focus isn't killing the focus
Here is what I'm doing. I'v created a combobox but I'm not using it for that. When I click it, it calls trackpopup and brings up a context menu. However after I'v clicked the context menu, I'd like it to close the combobox in the same way it would if you clicked anywhere (killing the focus) or selected an item from the combobox. Here's the event for the combobox: if(uMsg == WM_COMMAND) { HMENU m; m = CreatePopupMenu(); MENUITEMINFO itm; itm.cbSize = sizeof(MENUITEMINFO); itm.fMask = MIIM_FTYPE | MIIM_STRING; itm.fType = MIIM_STRING; itm.dwTypeData = "Kill time"; itm.cch = 12; POINT p; GetCursorPos(&p); InsertMenuItem(m,4,false,&itm); if((int)HIWORD(wParam) == CBN_DROPDOWN) { SendMessage(engineGL.controls.TopSelHwnd,WM_KILLFOCUS,(WPARAM)engineGL.controls.TopSelHwnd,0); SendMessage(engineGL.controls.TopSelHwnd,WM_IME_SETCONTEXT,(WPARAM)0,(LPARAM)ISC_SHOWUIALL); TrackPopupMenu(m,0,p.x,p.y,NULL,hWnd,NULL); SendMessage(hWnd,WM_KILLFOCUS,0,0); SetFocus(HWND_DESKTOP); } return 1; } How can I make it so that after I click an item on the context menu, the combobox closes properly as if I'd actually chosen an item from it? Thanks
I'm not sure. Need to try your code. However I'm sure that one should not send the WM_KILLFOCUS message manually. Instead you need to set the focus to another window by calling SetFocus. The OS will automatically send messages to the window losing the focus and the new window that is gaining the focus.
3,116,180
3,150,285
Compiling mp4v2 on Mac OS X
Anybody can help me with compiling mp4v2 on Mac OS X? I've tried configuring and compiling as per the instructions but I got a lot of errors originating from the C++ headers. The configure command was ./configure --enable-ub followed by plain make at the Terminal. From the looks of the error messages, it seems that a number of header files are missing from my installation. The problem is that I did not remove any header files and installed Xcode as-is from the installer DMG. It seems that these files are required but not present in my from my Xcode installation: /usr/include/c++/4.2.1/bits/c++config.h /usr/include/c++/4.2.1/bits/c++locale.h /usr/include/c++/4.2.1/bits/c++io.h /usr/include/c++/4.2.1/bits/ghtr.h /usr/include/c++/4.2.1/bits/atomic_word.h (and then some) They are all included by the STL C++ headers provided by the system (all of the files that references to these missing files are in /user/include/c++/4.2.1. Anybody can help tell me where do I get these "missing" header files? Here are the version details of each software involved: Snow Leopard 10.6.4 Xcode 3.2.3 (the one that came with iOS SDK 4.0) MP4v2 1.9.1 i686-apple-darwin10-g++-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5664) The following are some excerpts of the error messages: g++ -DHAVE_CONFIG_H -arch i386 -arch x86_64 -arch ppc -arch ppc64 -I./include -I./include -I. -I. -Wall -Wformat -g -O2 -fvisibility=hidden -c libplatform/impl.h -o libplatform/impl.h.gch/static In file included from /usr/include/c++/4.2.1/ios:43, from /usr/include/c++/4.2.1/istream:44, from /usr/include/c++/4.2.1/fstream:45, from ./libplatform/platform_base.h:6, from ./libplatform/platform_posix.h:31, from ./libplatform/platform.h:24, from libplatform/impl.h:6: /usr/include/c++/4.2.1/iosfwd:44:28: error: bits/c++config.h: No such file or directory /usr/include/c++/4.2.1/iosfwd:45:29: error: bits/c++locale.h: No such file or directory /usr/include/c++/4.2.1/iosfwd:46:25: error: bits/c++io.h: No such file or directory In file included from /usr/include/c++/4.2.1/bits/ios_base.h:45, from /usr/include/c++/4.2.1/ios:48, from /usr/include/c++/4.2.1/istream:44, from /usr/include/c++/4.2.1/fstream:45, from ./libplatform/platform_base.h:6, from ./libplatform/platform_posix.h:31, from ./libplatform/platform.h:24, from libplatform/impl.h:6: /usr/include/c++/4.2.1/ext/atomicity.h:39:23: error: bits/gthr.h: No such file or directory /usr/include/c++/4.2.1/ext/atomicity.h:40:30: error: bits/atomic_word.h: No such file or directory In file included from /usr/include/c++/4.2.1/memory:54, from /usr/include/c++/4.2.1/string:48, from /usr/include/c++/4.2.1/bits/locale_classes.h:47, from /usr/include/c++/4.2.1/bits/ios_base.h:47, from /usr/include/c++/4.2.1/ios:48, from /usr/include/c++/4.2.1/istream:44, from /usr/include/c++/4.2.1/fstream:45, from ./libplatform/platform_base.h:6, from ./libplatform/platform_posix.h:31, from ./libplatform/platform.h:24, from libplatform/impl.h:6: Thanks
I finally got it right: ./configure --disable-gch --enable-ub=ppc,i386,x86_64 Refer to mp4v2 issue 58. Furthermore there are additional steps required when you use Snow Leopard to build but you also want mp4v2 to be usable under Leopard. Thanks
3,116,286
3,116,439
How can I programmatically launch visual studio and send it to a specific file / line?
I have a nice tidy way of capturing unhandled exceptions which I display to my users and (optionally) get emailed to myself. They generally look something like this: Uncaught exception encountered in MyApp (Version 1.1.0)! Exception: Object reference not set to an instance of an object. Exception type: System.NullReferenceException Source: MyApp Stack trace: at SomeLibrary.DoMoreStuff() in c:\projects\myapp\somelibrary.h:line 509 at SomeAlgothim.DoStuff() in c:\projects\myapp\somealgorithm.h:line 519 at MyApp.MainForm.ItemCheckedEventHandler(Object sender, ItemCheckedEventArgs e) in c:\projects\myapp\mainform.cpp:line 106 at System.Windows.Forms.ListView.OnItemChecked(ItemCheckedEventArgs e) at System.Windows.Forms.ListView.WmReflectNotify(Message& m) at System.Windows.Forms.ListView.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) Is it possible to launch visual studio and have it open c:\projects\myapp\somelibrary.h on the offending line and if so, how? I'd also like to do this from the (html) email I generate if that's possible?
You can automate Visual Studio, using for example VBScript: filename = Wscript.Arguments(0) lineNo = Wscript.Arguments(1) ' Creates an instance of the Visual Studio IDE. Set dte = CreateObject("VisualStudio.DTE") ' Make it visible and keep it open after we finish this script. dte.MainWindow.Visible = True dte.UserControl = True ' Open file and move to specified line. dte.ItemOperations.OpenFile(filename) dte.ActiveDocument.Selection.GotoLine (lineNo) Save this as say debugger.vbs and run it, passing the filename and line no as command line args: debugger.vbs c:\dev\my_file.cpp 42
3,116,509
3,116,544
Is there any advantage for Java over C#
This question may sound silly.. but my intention is to understand advantages of Java over all other programming languages ?? I guess c# is more or less similar to java.. also c# is derived from c++ which inturn is derived from C.. So learning which language is more easier or helpful in understanding concepts & developing programs..
Java is supported on most platforms, whereas C# mostly runs on other platforms but is not supported by Microsoft. There are more external tools (like static code analyzers) for Java than for C#, although it is a matter of time before this goes the other way. When a scientific study is done into VM optimization or error detection, Java is mostly used. Since Java and C# are developed by different companies, there are differences in licensing, usage terms and conditions, pricing for support or software, etc. Update: .NET Core is now also supported on Linux and macOS.
3,116,516
3,116,583
snmp agent libraries for C/C++?
I have to implement a performance statistics MIB for a linux based device and I am looking for a good agent development library. I came across net-snmp and agent++ libraries. I am looking for easier to understand and robust library. Which is the best library if usability and robustness is main criteria?
I have used net-snmp. It is robust and works well. The API is in C but quite simple to encapsulate. More than a library and APIs it is a well tested set of tools to handle SNMP. A reference. I don't know agent++. It is perhaps simpler to deal with as it seems to be a C++ lib. my2c
3,116,563
3,116,716
Doxygen: multiple \mainpage blocks in a C++ project
I wasn't able to determine what the behavior of doxygen is regarding the \mainpage section, in two cases: If you specify no \mainpage section, does it use any other page instead and if so how is this picked? What if two files both specify a \mainpage section?
The \mainpage command specifies content used to customise the index page, so if you lack one it's just a blank page with the normal Doxygen header and footer. I think the safest thing to say about having multiple \mainpage commands is that it is undefined in the classic sense of yielding unpredictable results depending on version and platform. Similarly, I've had weird results when I accidentally created more than one \page command with the same page name. Further Thought Prompted by answering another Doxygen question, remember you can get Doxygen to obey the preprocessor directives so you can have #if conditionals protect the multiple mainpage directives and run different config files over the same code base, where the config files define one of several flag values. I have used this generate the docs from different perspectives approach to publish Macintosh and Windows-oriented versions of the same reference.
3,116,626
3,117,062
Recursively Insert Element Into A Binary Tree
So I finished my List exercise and went ahead with Binary Trees. My code thus far: Tree.h #include "Node.h" class Tree { private: int mCount; Node *root; public: Tree(); ~Tree(); void insert(int, Node *); }; Tree.cpp void Tree::insert(int data, Node *node) { if( root == 0 ) { Node *temp = new Node; temp->setData(100); temp->setRight(0); temp->setLeft(0); root = temp; } else { if( data > root->getData() ) return insert( data, root->getRight() ); else return insert( data, root->getLeft() ); } } main.cpp int main(int argc, char** argv) { Tree *tree = new Tree; tree->insert( 100, 0 ); std::cin.get(); return 0; } I hope this is sufficient code. Node and Tree are two separate classes. I'm having difficulties wrapping my head around the recursion. I have Node *root defined in my Tree class to have a root node at the top of the tree. However, the way I see it, when I call tree->insert insert in main, I don't have to specify any node. The root from the Tree class will do all the looking. However, when I'm in the code and need to recur, then I am suddenly a parameter short, as shown above. My solution was to just place the parameter Node *node in the argument list for insert() anyway and call it with a 0 from main. I would also need to call tree->display(0); as parameter for Node *node as well. This seems hackish. Am I missing something obvious?
A few points: First, don't use Node**. That err "uglifies" your code. Use Node*& instead (see answers here) if you really need to. Second, you do not need a recursive call (unless you want to use one). Non-recursive insert method: void Tree::insert(int data) { if(!root) { root = new Node(data); // Node constructor should receive // the data value and init internal value from it // it should also set left and right pointers to 0 return; } Node* insertIterator = root; Node* parent = 0; while(insertIterator) { parent = insertIterator; insertIterator = data < insertIterator->getData() ? insertIterator->getLeft() : insertIterator->getRight(); } if(data < parent->getData()) parent->setLeft( new Node(data) ); else parent->setRight( new Node(data) ); } If you do use a recursive method, use a recursive method that finds the insertion point, instead of a recursive method that performs the insertion. Basically, replace the while loop in the code above with a separate method (FindInsertionPoint in my code below): Node* Tree::FindInsertionPoint(int data, Node * parent) // this should be private { Node* insertPoint = data < parent.getData() ? parent->getLeft() : parent->getRight(); return insertPoint ? FindInsertionPoint(data, insertPoint) : parent; } void Tree::Insert(int data) // this should be public { if(!root) { root = new Node(data); return; } Node* parent = FindInsertionPoint(data, root); if(data < parent.getData()) parent->setLeft(new Node(data)); // see comment on Node constructor above else parent->setRight(new Node(data)); // see comment on Node constructor above } Edit: I'm having difficulties wrapping my head around the recursion. Look at it like this: to find the insertion point, you know that you need to insert as a child of the left or the right subnode. To insert to the left, you need to insert as a child of the left or the right subnode of the left child of the current node. That is, if you insert to the left, call the find the insertion point part for the left child; otherwise, call the find the insertion point for the right subnode. What you need to do to define a recursive algorithm: identify the algorithm as it applies to a part of your data (in this case, you need to insert as a child of the left or the right subnode). identify the stopping condition (when is the algorithm stopping?). If you do not, you get infinite recursion and a stackoverflow error :). identify the variable part of the algorithm (this should tell you what parameters your recursive function will have).
3,116,670
3,116,686
In C and C++, can I use macros definitions containing space?
I am wondering if macro definitions can contain space. Let's take for example this code: #define MACRO_PARAM int param2 int function(int param1, MACRO_PARAM) { return param1+param2; } This works ok with Visual Studio 8 and gcc 3.4.5 (mingw). For me this is good enough for the moment but is this standard? or can I rely on this behavior across different compilers? Thanks, Iulian PS: To answer to the question why would you wanna do that?: I'm using bison flex for a project and I'm trying to make something reentrant (I need to declare some macros for function parameters).
You'll need to end each line of the definition with a \ (except the last).
3,116,980
3,116,995
Do I have to set pointer to nullptr in destructor?
Possible Duplicate: Is it worth setting pointers to NULL in a destructor? Do I have to do something like so: ~MyClass() { delete[] my_data_; my_data_ = nullptr;//DO I HAVE TO WRITE THIS LINE? } Thank you.
delete[] my_data_; Should do all you need, after you use this then setting my_data_ to nullptr is not necessary.
3,117,462
3,117,594
Polymorphic Enum in C++
I have these Enum declarations: enum MessageType{ REQ_LOGIN, REQ_GET_FIELD, RES_LOGIN, RES_GET_FIELD } enum Request{ REQ_LOGIN, REQ_GET_FIELD }; enum Respond{ RES_LOGIN, RES_GET_FIELD }; Obviously I'm repeating elements in Enum's. Is there any way to prevent this? EDIT: I'm using "MessageType" on a general purpose class to send it through network, on the other side I parse the object of this class and dispatch message. But I have different clients; some expects only objects with "Request" type member and some expects only objects with "Response" type member. Using "Message" class, I'm creating "DispatcherRequest"s. class Message { public: ………. MessageType messageType; } struct DispatcherRequest { .......... Request type; };
Why not try something like this? enum MainType{ REQUEST, RESPONSE }; enum SubType{ LOGIN, GET_FIELD }; class Message { MainType type; SubType sub_type; ... };
3,117,478
3,117,541
strange double pointer null check
Is this a valid null check on a DOUBLE pointer parameter passed in a function if (!pdblValue) return E_POINTER;
In C++ the "if" statement uses a boolean expression. If it is true, it executes the part inside the conditional block. If it is false, it doesn't. pdblValue is of type pointer. Negating it (!pdblValue) will give a long integer expression which is different to zero if the value of the pointer was NULL, and zero otherwise. This will be converted into a boolean because that is what is needed in the condition. The different from zero value will be converted to true, and the zero value, to false. Hence, this will have the same semantics than the more natural form: if (pdblValue == NULL) ... In which you are actually providing a boolean expression - the one that you were actually meaning.
3,117,619
3,117,781
Get/set combo-box text in Win32 (not MFC)
I can use GetDlgItemText to get the text from a control, but I want to clear the selection and SetDlgItemText(IDC_CTRL,_T("")); doesn't work. What is the right approach here?
Assuming I'm reading the MSDN documentation for the Combo Boxes and the CB_SETCURSEL message right, you can send a CB_SETCURSEL message to the combo box with the wParam(In this case it will be the index of the string in the combo box) being set to -1. This should then clear the selection. You can also decide to use the ComboBox_SetCurSel macro that wraps the message sending, it can make life a bit easier. Once again -1 will clear the selection. Of course that would require you to get the handle of the combo box if you don't have it(I'm assuming you do, but in case you don't) you can possibly get it using the GetDlgItem function by supplying the handle for the dialog box and the id of the combo box.