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,089,047
3,089,139
stating jmp_buf as pointer
I'm tring to define jmp_buf as pointer and using it in nested longjmp(s).as follow: ... jmp_buf *bfj; ... and then writing if else: if( setjmp(*bfj) == 0){ DS[SP-2].int_val=(int)bfj;; //to store the bfj }else {} and somewhere else using the stored bfj to longjmp bfj = (jmp_buf *)DS[TOP].int_val; longjmp(*bfj,1); where DS[TOP].int_val is where I stored it. as it may seems clear,I want to do nested gotos and returns using stored bfj. but well when I try to debug I get "unhandeled exception". I get this at the very starting point: if( setjmp(*bfj) == 0) I would be pleased if someone would tell the solution.
From your code, you are not actually allocating memory for your jmp_buf. There are a couple of things you can do: Dynamically allocate your jmp_buf with new and you will want to delete it when you are done with it Put the jmp_buf on the stack jmp_buf bfj; and when you want it's pointer, you would take it's address with &bfj. So, #1 would look like: jmp_buf *bfj = new jmp_buf; ... if( setjmp(*bfj) == 0){ DS[SP-2].int_val=(intptr_t)bfj; while #2 would look like: jmp_buf bfj; ... if( setjmp(bfj) == 0){ DS[SP-2].int_val=(intptr_t)&bfj; Another potential issue is that you should never cast a pointer to an int as a pointer may take more memory then an int (this happens on the common 64 bit programming models). If you can't store the pointer directly, you should use intptr_t instead.
3,089,174
3,089,227
ld doesn't recognize object file
I'm having problems with compiling a project I'm working on. Everything else works just fine, but when I compile, I get this error message: /usr/bin/ld:obj/content/xmSound.o: file format not recognized; treating as linker script I have no idea why this happens. It's probably some error in the code, but I don't know. The source file xmSound.o is compiled from can be found here and the makefile I'm using is here.
Run 'file obj/content/xmSound.o' and compare what it says for that file with some other object file that the loader does not complain about. The chances are that the rule for building that object file is incorrect, somehow, and the file you have is not an object file at all.
3,089,278
3,089,283
Is there a C++ equivalent to Java's Collection interface for STL container classes?
I would like to pass arbitrary container as an argument of function and iterate over it (no erasing nor pushing elements). Unfortunately it looks like there is no standard way of doing this. First solution which comes to my mind is an interface (let's call it CollectionInterface) implemented by classes that will wrap STL containers. so the function declaration would look like: f(const CollectionInterface * collection); Or, I was thinking about method template, which has an advantage that it keeps binding at compilation time: template <class CONTAINER> void f(const CONTAINER & collection); Which way do you think is better?
ForwardIterator? This is a type of InputIterator (or OutputIterator) that also allows multi-pass algorithms (incrementing it does not invalidate prior values). Iterators (which are quite different from Java iterators) are the central thread unifying C++ collections. For examples of algorithms working on them (and associated iterator type requirements), you can start with <algorithm>. In particular, search provides an example of using ForwardIterator. It finds the first occurrence within the range [first1, last1] of the sequence defined by the range [first2, last2). These are all objects meeting the requirements of ForwardIterator.
3,089,302
3,089,318
How to order a string[] in c++
The input is string[] like below. "CSE111: CSE110 MATH101" "CSE110:" I need to order the strings based on some logic. For example my output should be a string[] like "CSE110","MATH122","CSE111" My question is While scanning through the input array, if one string is picked to be the first string of the output array, then how do I skip all occurrences of that particular string, while I continue to process the string[] for the second output string etc.. Eg: Input: "CSE111: CSE110 MATH101" "CSE110:" If CSE110 is picked to be the first string in the output, then when I scan through the input string[] for the second string to be a part of output, I should not consider CSE110. How can I achieve this? The answer I am looking forward to is something like: Store the input in a string[] loop through the strings one by one using strtok or stringstream >> operator. Once the first string is found ...blah blah blah .... Hope my question is clear enough. I will be glad to provide more details. Edit1:More Explanation The strings represent the order in which the classes need to taken . If a class has pre-requisite , the pre-requisite has to be taken first. ie. if Input is "CSE111: CSE110 MATH101" "CSE110:" The class CSE111 has a pre-requisite of CSE110 MATH101 . So I need to consider first CSE1110(No Pre-requisite) - MATH101((No Pre-requisite) and then CSE111 . (Further Ties can broken in alphabetical order. ) I hope this helps..
I hopefully got it now: For a string of the form A: B C D, the course A has B, C, and D as prerequisites. In that case you want a mapping from a course to its prerequisites, e.g.: typedef std::set<std::string> CourseSet; typedef std::map<std::string, CourseSet> Prerequisites; Now you can fill a Prerequisites by tokenizing, using the first part as the key and a CourseSet as the value. As it seems that you just want one of the possible orders for all courses in the input, you could then do the following: complete the prerequisites for the courses (i.e. include the courses they indirectly depend on) now a>b if a has b as a prerequisite if b doesn't have a as a prerequisite use e.g. the lexicographical order
3,089,454
3,089,709
"Selected" style for WinAPI toolbar button?
Is there a way to make a toolbar button look different than the rest (Aside from changing bitmap or setting its state to Disable? Is there away to make it look highlighted all the time? I want the selected tool to look selected. Thanks (Sort of like the way open applications are "Selected" in Windows 7.
Send the TB_SETHOTITEM message
3,089,602
3,089,627
Is there a thread safe queue class for Visual Studio C++ 6.0?
I would like to implement a thread safe queue in VS 6.0 Is there a good class to use for this? This is an MFC application using the CWinApp. My former post lead me to here but I don't have the luxury to code in VS 2010, stuck in 6.0 land. o well..... Thank You.
Obviously you accepted the wrong answer to that question! :-) The code I linked in my answer will work fine with VC++ 6.
3,089,744
3,089,754
Accessing a nonmember function of a derived class from a base class
I'm trying to call a nonmember function of a derived class from a base class, but getting this error: error: no matching function for call to 'generate_vectorlist(const char&)' Here's the relevant code snippets from the base class: //Element.cpp #include "Vector.h" ... string outfile; cin >> outfile; const char* outfile_name = outfile.c_str(); generate_vectorlist(*outfile_name); //ERROR ... and the derived class (this is a template class, so everything's in the header): //Vector.h template <class T> void generate_vectorlist(const char* outfile_name = "input.txt" ) { std::ofstream vectorlist(outfile_name); if (vectorlist.is_open()) for (Element::vciter iter = Element::vectors.begin(); iter!=Element::vectors.end(); iter++) { Vector<T>* a = new Vector<T>(*iter); vectorlist << a->getx() << '\t' << a->gety() << '\t'<< a->getz() << std::endl; delete a; } else { std::cout << outfile_name << " cannot be opened." << std::endl;} vectorlist.close(); } My guess is there's just a small syntax thing that I'm missing. Any ideas?
You're dereferencing the pointer so you're passing a const char, not a const char*. try this: generate_vectorlist(outfile_name);
3,089,840
3,089,852
C Preprocessor and if-else condition statement
I run my C code in vs2010 (win32 console application). It was compiled as C++ application. #include "stdafx.h" #define YES 1; #define NO 0; // function to determine if an integer is even int isEven(int number) { int answer; if ( number % 2 == 0) answer = YES; else answer = NO; return answer; } int main() { int isEven(int number); if (isEven(17) == YES) printf("yes "); else printf("no "); if ( isEven(20) == YES) printf("yes\n"); else printf("no\n"); return 0; } Compiler error as below. p300.cpp(18): error C2181: illegal else without matching if p300.cpp(30): error C2143: syntax error : missing ')' before ';' p300.cpp(30): error C2059: syntax error : ')' p300.cpp(31): warning C4390: ';' : empty controlled statement found; is this the intent? p300.cpp(33): error C2181: illegal else without matching if p300.cpp(37): error C2143: syntax error : missing ')' before ';' p300.cpp(37): error C2059: syntax error : ')' p300.cpp(38): warning C4390: ';' : empty controlled statement found; is this the intent? p300.cpp(40): error C2181: illegal else without matching if Then I also tried to insert several of { } for each of if-else condition statement, but the code still compiled failed. What's wrong with my code?
The compile error is due to the semicolons on your #define statements. Remove them. #define is a preprocessor macro, not c syntax. It doesn't need a semicolon. The preprocessor does straight substitution on YES and NO, which makes: if ( number % 2 == 0) answer = YES; else answer = NO; Turn into: if ( number % 2 == 0) answer = 1;; // <-- Notice the two semicolons! else answer = 0;; That makes two statements between if and else, so compiler errors ensue. I suspect you get different compiler errors when you add { and } due to if (isEven(17) == YES) becoming if (isEven(17) == 1;) By the way, this question is tagged c, but your filename is .cpp, which is a common suffix for c++. If you are using c++, definitely use the bool type. bool is_even = true; bool is_odd = false;
3,089,891
3,089,911
Create a IM program (like MSN or Gtalk ) using C++
My question is that create a IM software like MSN or Gtalk, to have the basic function using C++. You can use any technology and libary to do that. Can someone give me a suggestion? I add that this not my homework. This is my job question. Because I am a fresh man in my company. So, they give me some questions to let me dirty my hand.
My suggestion from experience with doing this sort of thing before is to find a library that implements Jabber also known as XMPP (Google Talk) for you. That way all you have to do is create the user interface. If you are working with Windows, MSDN has some great tutorials for creating user interfaces in C++. If you are using Linux, you will probably want to look for an X windows tutorial. Other than that, check out this link for a list of C++ libraries for Jabber/XMPP. Good luck!
3,089,897
3,090,102
setw : Alignment for UTF-8 text file
all the while, I am using setw for my ANSI text file alignment. Recently, I want to support UTF-8 in my text file. I found out that setw no longer work. #include <windows.h> #include <iostream> // For StringCchLengthW. #include <Strsafe.h> #include <fstream> #include <iomanip> #include <string> #include <cassert> std::string wstring2string(const std::wstring& utf16_unicode) { // // Special case of NULL or empty input string // if ( (utf16_unicode.c_str() == NULL) || (*(utf16_unicode.c_str()) == L'\0') ) { // Return empty string return ""; } // // Consider WCHAR's count corresponding to total input string length, // including end-of-string (L'\0') character. // const size_t cchUTF16Max = INT_MAX - 1; size_t cchUTF16; HRESULT hr = ::StringCchLengthW( utf16_unicode.c_str(), cchUTF16Max, &cchUTF16 ); if ( FAILED( hr ) ) { throw std::exception("Error during wstring2string"); } // Consider also terminating \0 ++cchUTF16; // // WC_ERR_INVALID_CHARS flag is set to fail if invalid input character // is encountered. // This flag is supported on Windows Vista and later. // Don't use it on Windows XP and previous. // // CHEOK : Under Windows XP VC 2008, WINVER is 0x0600. // If I use dwConversionFlags = WC_ERR_INVALID_CHARS, runtime error will // occur with last error code (1004, Invalid flags.) //#if (WINVER >= 0x0600) // DWORD dwConversionFlags = WC_ERR_INVALID_CHARS; //#else DWORD dwConversionFlags = 0; //#endif // // Get size of destination UTF-8 buffer, in CHAR's (= bytes) // int cbUTF8 = ::WideCharToMultiByte( CP_UTF8, // convert to UTF-8 dwConversionFlags, // specify conversion behavior utf16_unicode.c_str(), // source UTF-16 string static_cast<int>( cchUTF16 ), // total source string length, in WCHAR's, // including end-of-string \0 NULL, // unused - no conversion required in this step 0, // request buffer size NULL, NULL // unused ); assert( cbUTF8 != 0 ); if ( cbUTF8 == 0 ) { throw std::exception("Error during wstring2string"); } // // Allocate destination buffer for UTF-8 string // int cchUTF8 = cbUTF8; // sizeof(CHAR) = 1 byte CHAR * pszUTF8 = new CHAR[cchUTF8]; // // Do the conversion from UTF-16 to UTF-8 // int result = ::WideCharToMultiByte( CP_UTF8, // convert to UTF-8 dwConversionFlags, // specify conversion behavior utf16_unicode.c_str(), // source UTF-16 string static_cast<int>( cchUTF16 ), // total source string length, in WCHAR's, // including end-of-string \0 pszUTF8, // destination buffer cbUTF8, // destination buffer size, in bytes NULL, NULL // unused ); assert( result != 0 ); if ( result == 0 ) { throw std::exception("Error during wstring2string"); } std::string strUTF8(pszUTF8); delete[] pszUTF8; // Return resulting UTF-8 string return strUTF8; } int main() { // Write the file content in UTF-8 { std::ofstream file; file.open("c:\\A-UTF8.txt"); file << std::setw(12) << std::left << wstring2string(L"我爱你") << "????" << std::endl; file << std::setw(12) << std::left << "ILU" << "????"; } { std::ofstream file; file.open("c:\\A-ANSI.txt"); file << std::setw(12) << std::left << "WTF" << "????" << std::endl; file << std::setw(12) << std::left << "ILU" << "????"; } return 0; } My output for A-ANSI.txt is WTF ???? ILU ???? My out put for A-UTF8.txt is 我爱你 ???? ILU ???? How can I make A-UTF8.txt's text aligned properly?
Even in a "monospaced" font, some East Asian characters are wider than others. You also have to consider combining characters, which have no width of their own. There's a wcswidth function that may do what you want.
3,089,921
3,089,946
C++ iterator in for loop pitfalls?
I see somewhere it mentions: for ( itr = files.begin(); itr < files.end(); ++itr ) // WRONG for ( itr = files.begin(); itr != files.end(); ++itr ) // ok Why is the first expression wrong? I always used the first expression, and didn't have any problems.
Ordering comparisons such as <, >, <=, >= will work for random-access iterators, but many other iterators (such as bidirectional iterators on linked lists) only support equality testing (== and !=). By using != you can later replace the container without needing to change as much code, and this is especially important for template code which needs to work with many different container types.
3,089,927
3,089,941
How to retrieve an integer value from a character?
How can I convert a character into an integer value? For example, I've been trying to read "A" as 1, "B" as 2, and so forth. I tried comparing the character to each letter in the alphabet and return the appropriate value. int intvalue(char letter) { if(letter == "A") return 1; else if(letter == "B") return 2; else if(letter == "C") return 3; else if(letter == "D") return 4; else if(letter == "E") return 5; else if(letter == "F") return 6; else if(letter == "G") return 7; else if(letter == "H") return 8; else if(letter == "I") return 9; else if(letter == "J") return 10; else if(letter == "K") return 11; else if(letter == "L") return 12; else if(letter == "M") return 13; else if(letter == "N") return 14; else if(letter == "O") return 15; else if(letter == "P") return 16; else if(letter == "Q") return 17; else if(letter == "R") return 18; else if(letter == "S") return 19; else if(letter == "T") return 20; else if(letter == "U") return 21; else if(letter == "V") return 22; else if(letter == "W") return 23; else if(letter == "X") return 24; else if(letter == "Y") return 25; else if(letter == "Z") return 26; } I got "error: ISO C++ forbids comparison between pointer and integer". Does anyone know how to fix this? Or even better, a different way to go about this? I feel like my above function is very brute-forceish.
You need to use character literals, not string literals, e.g., if (letter == 'A') ^ note the single quotes That said, if you are willing to assume you are running on a system using the ASCII character set, you can simply use arithmetic: int charIndex = (letter - 'A') + 1; In the ASCII character set, letters are at consecutive indices, so this works. This may not work with other character sets.
3,090,038
3,090,047
Memory comparison, which is faster?
I have a 3D vector class. The private variables are defined: union { struct { double x; double y; double z; }; double data[3]; }; In implementing operator==, which is faster? return this->x == v.x && this->y == v.y && this->z == v.z; OR return memcmp(this->data, v.data) == 0;
Unfortunately the two aren't equivalent. (Specifically NaNs and signed zeros don't use bitwise comparison inside the FPU). So you should make your choice based on correctness, not speed.
3,090,080
3,090,092
Need some help in serialization
I am trying to write a program to serialize a linked list to a file without using any libraries. My problem is how to add or remove nodes to the serialized structure since I dont have next pointer ? Also how can I avoid fragmentation ?
If your linked list doesn't have loops, then the fact that this is a "linked list" is a memory detail, not a serialization detail. Just write the node values out into the file and build the next pointers when you deserialize. However, if your linked list does have loops, then you'll need something smarter. You'll need to store next pointers as a file offsets to the node (or something similar) to encode the "link". For each node in your linked list, store two words. The first is the data, the second is the offset of the next node. Here is an illustration of the circularly linked list: +-> 1234 -> 5678 -> 2398 -+ | | +-------------------------+ 0 : 4bytes: 1234 : int data <------------+ 4 : 4bytes: 8 : offset of next node -+ | | | 8 : 4bytes: 5678 : int data <----------+ | 12 : 4bytes: 16 : offset of next node -+ | | | 16 : 4bytes: 2398 : int data <----------+ | 20 : 4bytes: 0 : offset of next node ---+
3,090,268
3,090,308
how much memory is required for metadata when using new int[10]?
When array is created using 'new' and deleted using 'delete' operator, delete knows the size of array. As mentioned in other SO threads, this size information is stored in metadata. My question: what exactly is stored in metadata and how much space is needed for that? Is it only the size which is stored in metadata?
According to C++ Standard 5.3.4/12: new T[5] results in a call of operator new[](sizeof(T)*5+x), <...>where x is a non-negative unspecified values representing array allocation overhead. <...> The amount of overhead may vary from one invocation of new to another.
3,090,270
3,096,215
How to use a phoenix expression with boost::transform_iterator?
<Update> As usual for me, the question was a wrong one. The actual question is: why doesn't transform_iterator use the conventional result_of<> metafunction to determine the return type, instead of accessing UnaryFunc::result_type directly. Posted an answer with a work around. </Update> Specifically, is there a way to make a phoenix expression expose a result_type type as expected for the std::unary_function concept? boost::transform_iterator seems to expect this, and from looking at the src of it, I don't see a simple work around. Here's some code that reproduces the problem I've been having: #include <boost/iterator/transform_iterator.hpp> #include <boost/spirit/home/phoenix.hpp> #include <numeric> #include <iostream> using namespace boost::phoenix; using namespace boost::phoenix::arg_names; int main(void){ int i[] = {4,2,5,3}; std::cout << std::accumulate( boost::make_transform_iterator(i, _1*_1), boost::make_transform_iterator(i+4, _1*_1), 0 ) << std::endl; return 0; } The relavent portion of the error message from compiling this is (gcc 4.3.4, boost 1.43): /usr/include/boost/iterator/transform_iterator.hpp:43: error: no type named ‘result_type’ in ‘struct boost::phoenix::actor<... I have the same problem with boost::lambda (missing result_type). I thought that I had seen similar usage for make_transform_iterator and lambda in the past, now I'm wondering if I just imagined it. Is there a provided wrapper or some other mechanism in phoenix or lambda to expose result_type?
It looks like this is fixed in the boost trunk (see line 51, result_of<> instead of an indirect UnaryFunc::result_type). So this shouldn't be an issue in 1.44 and above. Here's a workaround for boost < 1.44. The transform_iterator instantiation accesses UnaryFunc::result_type only if the Reference template parameter is not provided. So one trick is to replace make_transform_iterator with a version that calls the result_of<> meta function on the UnaryFunc and use the result for the Reference template parameter. #include <boost/iterator/transform_iterator.hpp> #include <boost/utility.hpp> #include <iterator> template <class UnaryFunc, class Iterator> boost::transform_iterator< UnaryFunc, Iterator, typename boost::result_of< UnaryFunc(typename std::iterator_traits<Iterator>::value_type) >::type > make_trans_it(Iterator it, UnaryFunc fun){ return boost::transform_iterator< UnaryFunc, Iterator, typename boost::result_of< UnaryFunc(typename std::iterator_traits<Iterator>::value_type) >::type >(it, fun); };
3,090,457
3,094,268
Extending legacy C++ Windows app with WinForms
I'm working on an legacy C++ application that runs on rugged business mobile devices made by Intermec. I need to add some functionality and would like to build it using WinForms. The idea is that users would click a button in the old app which would launch a WinForms screen. Then they do some stuff, click OK and are returned to the C++ app. The question is, can I somehow "embed" the Winforms app inside the C++ app so that I can open a Winform as a modal dialog and pass information between the 2 applications. Thanks very much for helping. Cheers Mark
First let's be clear that the compact framework is not the full framework and therefore a lot of things that will work on the desktop are not going to work for you. You really only have one option, though there are a lot of different ways to use the one option. Since teh Compact Framework does not support EE Hosting (i.e. loading the CLR up in a native application) your only option for running managed code is to write and execute a managed application. Period. Now, as I said, there are options on how you go about this. For example you could launch the application when you launch the MFC application and simply have it running without a Form, then use some form of IPC (point to point queues would probably make the most sense, but a memory-mapped file might also be useful) and then have the applications "talk" top one another. So your C++ app could send a message that says "show Form A" and when Form A closes, the managed application could send back data.
3,090,473
3,090,640
StdAfx + Header file - Order of inclusion in MFC application
I am using Visual Studio 2005. I created an MFC based console application named "StdAfx dependancy". The IDE created the following files for me. Resource.h StdAfx Dependancy.h stdafx.h StdAfx Dependancy.cpp stdafx.cpp I added another class CHelper with Helper.h and Helper.cpp as below. Helper.h: #pragma once class CHelper { public: CHelper(void); ~CHelper(void); }; Helper.cpp #include "StdAfx.h" #include "Helper.h" CHelper::CHelper(void) { } CHelper::~CHelper(void) { } I created an object for CHelper in the main function; to achieve this I added Header.h file in the first line of StdAfx Dependancy.cpp as below; and I got the following errors. d:\codes\stdafx dependancy\stdafx dependancy\stdafx dependancy.cpp(33) : error C2065: 'CHelper' : undeclared identifier d:\codes\stdafx dependancy\stdafx dependancy\stdafx dependancy.cpp(33) : error C2146: syntax error : missing ';' before identifier 'myHelper' d:\codes\stdafx dependancy\stdafx dependancy\stdafx dependancy.cpp(33) : error C2065: 'myHelper' : undeclared identifier But when I include it after stdafx.h, the error vanishes. Why? // Stdafx dependancy.cpp : Defines the entry point for the console application. // #include "Helper.h" #include "stdafx.h" #include "Stdafx dependancy.h" // #include "Helper.h" --> If I include it here, there is no compilation error #ifdef _DEBUG #define new DEBUG_NEW #endif // The one and only application object CWinApp theApp; using namespace std; int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { int nRetCode = 0; // initialize MFC and print and error on failure if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0)) { // TODO: change error code to suit your needs _tprintf(_T("Fatal Error: MFC initialization failed\n")); nRetCode = 1; } else { CHelper myHelper; } return nRetCode; }
This link must give you some clue. Purpose of stdafx.h The lines defined before the #include "stdafx.h" are ignored by the compiler. So if you want to actually include those files then you need to include them after the #include "stdafx.h". Hope it is clear.
3,090,694
3,090,760
Duplication in Drive letters
i get device insertion and removal notification from WM_DEVICECHANGE i get the dbcc_name from the DBT_DEVTYP_DEVICEINTERFACE i get the corresponding drive letter from the DBT_DEVTYP_VOLUME if i insert the device one by one it works correctly but if i insert two device at a time i get duplication in drive letters how can i solve it kindly provide me some ideas my code snippet if ( DBT_DEVICEARRIVAL == wParam || DBT_DEVICEREMOVECOMPLETE == wParam ) { PDEV_BROADCAST_HDR pHdr = ( PDEV_BROADCAST_HDR )lParam; PDEV_BROADCAST_DEVICEINTERFACE pDevInf; PDEV_BROADCAST_VOLUME pDevVolume = reinterpret_cast<PDEV_BROADCAST_VOLUME>(lParam); switch( pHdr->dbch_devicetype ) { case DBT_DEVTYP_DEVICEINTERFACE: pDevInf = ( PDEV_BROADCAST_DEVICEINTERFACE )pHdr; updateDevice( pDevInf, wParam , pDevVolume ); break; case DBT_DEVTYP_VOLUME: pDevVolume = ( PDEV_BROADCAST_VOLUME )pHdr; QString aDrive = FirstDriveFromMask( pDevVolume->dbcv_unitmask ); break; } }
The DEV_BROADCAST_VOLUME docs mention this piece of info: Although the dbcv_unitmask member may specify more than one volume in any message, this does not guarantee that only one message is generated for a specified event. Multiple system components may independently generate messages for logical volumes at the same time. In other words - one message can carry information about multiple volumes added (almost) simultaneously, but that does not guarantee that only one message will be generated for these volumes. You should check dbcv_unitmask for more than one volumes.
3,090,725
3,090,744
How to extract audio/video file duration?
I need to find the duration of numerous formats of audio and video files, in milliseconds. I've been searching around for a while, but I can't find anything that will let me do this. I'm using C/++ in Linux. Thanks in advance.
There is a MediaInfo SourceFourge project that shows this info. You can look in its code for that.
3,090,748
3,091,462
Displaying current language layout in traybar
Basically I want to write an application which would display the current language as a tray icon. Mainly I can code C++ and C#. Guess Google would help me out but I would like to ask it here first, since the community, the knowledge here is something I trust. (Never wrangled with such parts of the system so far. So that's why I would like to ask the community.) Okay thanks to your help, I managed to discover two ways. Using the DllImport in C# (importing the user32.dll) and the InputLanguage. Found a snippet: public void SetNewCurrentLanguage() { // Gets the default, and current languages. InputLanguage myDefaultLanguage = InputLanguage.DefaultInputLanguage; InputLanguage myCurrentLanguage = InputLanguage.CurrentInputLanguage; textBox1.Text = "Current input language is: " + myCurrentLanguage.Culture.EnglishName + '\n'; textBox1.Text += "Default input language is: " + myDefaultLanguage.Culture.EnglishName + '\n'; // Changes the current input language to the default, and prints the new current language. InputLanguage.CurrentInputLanguage = myDefaultLanguage; textBox1.Text += "Current input language is now: " + myDefaultLanguage.Culture.EnglishName; } I applied this like the following: InputLanguage myCurrentLanguage = InputLanguage.CurrentInputLanguage; notifyIcon.Text = myCurrentLanguage.LayoutName + '\n' + myCurrentLanguage.Culture.DisplayName; This displays it if you hover it above the icon. However, it won't update on switch, nor show the layout as text in the tray area. For that, I found a "Drawing in VB.NET" article, maybe this will help me working out this issue. About the switch detect, that's a good question.
To get the user's overall UI language, GetUserDefaultUILanguage. To get the current thread's language, GetThreadUILanguage or GetThreadLocale. To get the current keyboard input language, GetKeyboardLayout. To display a notification area icon in Windows prior to Windows 7, Shell_NotifyIcon. In Windows 7 Shell_NotifyIcon might still work if the user sets appropriate options, but otherwise you have to find another way. If you have more than one possible keyboard input language, Windows already displays the current keyboard input language in the language bar unless the user has disabled it. The user might put the language bar in the task bar, though it's not quite the same as being in the notification area. If you want to receive notices when the user changes a language, WM_SETTINGCHANGE might let you know when you should call SystemParametersInfo to check. I'm not sure if there's a better way.
3,090,968
3,091,032
Best practices and tools for debugging differences between Debug and Release builds?
I've seen posts talk about what might cause differences between Debug and Release builds, but I don't think anybody has addressed from a development standpoint what is the most efficient way to solve the problem. The first thing I do when a bug appears in the Release build but not in Debug is I run my program through valgrind in hopes of a better analysis. If that reveals nothing, -- and this has happened to me before -- then I try various inputs in hopes of getting the bug to surface also in the Debug build. If that fails, then I would try to track changes to find the most recent version for which the two builds diverge in behavior. And finally I guess I would resort to print statements. Are there any best software engineering practices for efficiently debugging when the Debug and Release builds differ? Also, what tools are there that operate at a more fundamental level than valgrind to help debug these cases? EDIT: I notice a lot of responses suggesting some general good practices such as unit testing and regression testing, which I agree are great for finding any bug. However, is there something specifically tailored to this Release vs. Debug problem? For example, is there such a thing as a static analysis tool that says "Hey, this macro or this code or this programming practice is dangerous because it has the potential to cause differences between your Debug/Release builds?"
The very existence of two configurations is a problem from debugging point of view. Proper engineering would be such that the system on the ground and in the air behave the same way, and achieve this by reducing the number of ways by which the system can tell the difference. Debug and Release builds differ in 3 aspects: _DEBUG define optimizations different version of the standard library The best way around, the way I often work, is this: Disable optimizations where performance is not critical. Debugging is more important. Most important is disable function auto-inlining, keep standard stack frame and variable reuse optimizations. These annoy debug the most. Monitor code for dependence on DEBUG define. Never use debug-only asserts, or any other tools sensitive to DEBUG define. By default, compile and work /release.
3,091,152
3,091,414
looking for a MemoryStream in C++
In the wonderful world of C# i can create a memory stream without specifying its size, write into it and then just take the underlying buffer. How can i do the same in c++? basicly i need to do: memory_stream ms(GROW_AS_MUCH_AS_YOU_LIKE); ms << someLargeObjects << someSmallObjects << someObjectsWhosSizeIDontKnow; unsigned char* buffer = ms.GetBuffer(); int bufferSize = ms.GetBufferSize(); rawNetworkSocket.Send(buffer, bufferSize); By the way I have boost in my project though I'm not all that familiar with it. Thank you.
#include <sstream> std::ostringstream buffer; // no growth specification necessary buffer << "a char buffer" << customObject << someOtherObject; std::string contents = buffer.str(); size_t bufferSize = contents.size(); rawNetworkSocket.Send(contents); // you can take the size in Send Using this approach you will have to parse the result where you receive it (as the code above just transforms your data into an unstructured string. Another problem with it is that since C++ doesn't support reflection, you will have to define operator << for your objects. This is the code for a Custom class: template<typename C, typename T> std::basic_ostream<C,T>& operator << ( std::basic_ostream<C,T>& out, const Custom& object) { out << object.member1 << "," << object.member2 /* ... */ << object.memberN; return out; } If you want structured serialization, have a look at boost::serialization.
3,091,185
3,091,253
Do without USES_CONVERSION macro
I have this code that uses the USE_CONVERSION macro in a C++ project... I was wondering if this is written well, (not written by me), and if there's any better ways to do it, without the USES_CONVERSION and W2A macros. STDMETHODIMP CInterpreter::GetStringVar(BSTR bstrNamespace, BSTR bstrVar, BSTR *pbstrValue) { USES_CONVERSION; try { if (!pbstrValue) return E_POINTER; char* pszNamespace= W2A(_bstr_t(bstrNamespace).operator wchar_t*()); char* pszVar= W2A(_bstr_t(bstrVar).operator wchar_t*()); // Is this not better done another way???? char pszErrStr[kPYTHONERRBUFSIZE]; char pszStrValue[kPYTHONSTRVALUESIZE]; BOOL bResult= Python_GetStringVar(pszNamespace, pszVar, pszErrStr, pszStrValue, kPYTHONSTRVALUESIZE); *pbstrValue= _bstr_t(pszStrValue).operator BSTR(); if (!bResult) throw x::internal_error(A2W(pszErrStr)); return S_OK; } }
There is the class-based ATL::CA2W and friends (in atlconv.h, I believe) that don't put the string on the stack and don't use macros. You don't need a USES_CONVERSION in the function: throw x::internal_error(ATL::CA2W(pszErrStr)); Also, since your arguments are BSTR (wchar_t *), you don't need to convert them to _bstr_t. NOTE: The lifetime of the converted string is the lifetime of the CW2A object, so you will need to put it into a string class, e.g.: CStringA arg = CW2A(bstrArg); NOTE 2: pbstrValue is an output value. The _bstr_t instance will destroy the memory allocated for the BSTR. Therefore, you need to either use SysAllocString directly, or detach the BSTR: pbstrValue = SysAllocString(CA2W(retval)); or: pbstrValue = CComBSTR(CA2W(retval)).Detach(); NOTE 3: Explicit use of the conversion operators (.operator BSTR()) is not needed -- the compiler will call the correct one for you. NOTE 4: Since this looks like a COM call, you really do not want to be throwing a C++ exception. You probably want to set an IErrorInfo object (probably with a helper): if (!bResult) { SetError(CA2W(errorStr)); return E_FAIL; }
3,091,186
3,091,220
Qt - How to get the "Temp" dir for an arbitrary user?
For each OS there is a location for storing temporary data. It could be like: C:/Users/[user name]/AppData/Temp (or so). How can I get this path independently from OS with QT?
It is not possible to get the temp directory for an arbitrary user, but for the current user you can use QDir::temp() or QDir::tempPath().
3,091,300
3,091,932
MessageBox with timeout OR Closing a MessageBox from another thread
If my application crashes, I use an ExceptionFilter to catch the crash, perform some final actions, then show a message box to the user that the application has crashed. Because the application already crashed, there's not much I can (or I dare) to do, because if I do too much, the executed code might access corrupted memory and crash again. Some of the things I currently can't do (or I don't dare to do) is to close network connections, Oracle database sessions, ... Problem is that if an application crashes, and the user is out to lunch while the MessageBox is open, other users might be blocked, because of the open database session. Therefore I want: Either a MessageBox with a time-out. Problem is that you can't do this with the standard MessageBox Win32 API function, and I don't want to make a specific dialog for it (because I want to minimize the executed logic after the crash) Or the possibility to close the MessageBox from another thread (the other thread can provide the time-out logic). Did I overlook something in the Win32 API and is there a possibility to have a MessageBox with a time-out? Or what is the correct way to close an open MessageBox from another thread (how to get the MessageBox handle, how to close it, ...)?
I noticed that if the main thread simply exits the application while the other thread still has the ::MessageBox open, that the MessageBox is being adopted by a process called CSRSS. This solves my problem, since this only requires a time-out on the Event in the main thread (WaitForSingleObject with timeout). However, this raised another question: https://stackoverflow.com/questions/3091915/explanation-why-messagebox-of-exited-application-is-adopted-by-winsrv.
3,091,301
3,091,441
How to get file path from NTFS index number?
I have dwVolumeSerialNumber, nFileIndexHigh, nFileIndexLow values obtained from a call to GetFileInformationByHandle. How can I get file path from these values?
Because of hard links, there may be multiple paths that map to the given VolumeSerialNumber and FileIndex. To find all such paths: Iterate volumes to find one whose root directory matches dwVolumeSerialNumber Recursively enumerate all directories on the volume, skipping symbolic links and reparse points, to find all files with matching nFileIndexHigh and nFileIndexLow. This can be quite time-consuming. If you really need to do this as fast as possible and your filesystem is NTFS, you can raw read the entire MFT into a buffer and parse it yourself. This will get all directories that fit inside an MFT entry in one fell swoop. The rest of the directories can be read through the OS or also through raw reads, depending on the amount of work you want to do. But any way you look at it, this is a lot of work and doesn't even apply to FAT, FAT32 or any other filesystem. A better solution is probably to hang onto the original path if at all possible.
3,091,318
3,091,740
Custom interactive shell
I've run into the following problem: My console utility should be running as a process (hope it's the right term) so every command goes to it directly. Like gnuplot, interactive shells (irb, etc.). This shows what I'm talking about: Mikulas-Dites-Mac-2:Web rullaf$ command Mikulas-Dites-Mac-2:Web rullaf$ irb >> command NameError: undefined local variable or method `command' for main:Object from (irb):1 >> exit Mikulas-Dites-Mac-2:Web rullaf$ first command is executed as shell command, but after I enter irb, it's not. You get the point. irb puts console into some special mode, or it simply parses the given input itself in some loop? Is here any proper way to create such a behavior in c++? Thanks
You have to parse the input yourself. Depending on the complexity of the input, this might be accomplished by some simple string matching for trivial cases. A very simple example: #include <iostream> #include <string> int main() { std::string input; for(;;) { std::cout << ">>"; std::cin >> input; if(input=="exit") return 0; else if(input=="test") std::cout << "Test!\n"; else std::cout << "Unknown command.\n"; } } Obviously, this little program will print a prompt (>>) and understand the commands exit and test and will print Unknown command. on all other commands. For everything else, you probably want to learn some more about pattern matching or parsing; Google is your friend (take a look at bison for example and a good tutorial).
3,091,400
3,091,884
iPhone CoreAudio hang when stopping
I have an iPhone app that is recording audio and then broadcasting it across the network. In response to a "stop" from the far end it queues a notification to stop the recording. Alas when it gets to the AudioQueueStop call the application just hangs (ie Stop never exits). Thanks to the notification all AudioQueue manipulation is happening on the same thread. Has anyone got any idea whats going on here? Edit: I have set up a listener in the UI thread that handles the recorder. Then from my network thread I use a "postNotificationName" beliving that it was post a message to the UI thread and everything would run from that thread. This does not appear to be the case. When I break point the function that is called by the postNotificationName it appears that the call is being made on the networking thread and NOT on the UI Thread. I assume this is my error. Anyone know how to make it work by notifying the UIThread to handle it? Edit2: OK I've re-written it to use performSelectorOnMainThread. And it still crashes. On the plus side I just learnt how to get a lot more info out of XCode so I can see the call stack goes: semaphore_timedwait_signal_trap semaphore_timedwait_signal _pthread_cond_wait pthread_cond_timedwait_relative_np CAGuard::WaitFor ClientAudioQueue::ServicePendingCallbacks AudioQueueStop [etc] Anyone got any ideas why it hangs?
How do you call AudioQueueStop ? The function supports two modes: synchronous and asynchronous. The preferred way is to use the asynchronous stopping as the function will return immediately, while the remaining buffers will be played/recorded. If you want to go synchronous and you get a hang, then maybe there is a dead-lock or a race condition somewhere. Have you tried to pause the application under the debugger and check the threads' stack-frames to see where the problem is ?
3,091,484
3,091,498
Exception in two line Xerces program
The following code gives me an exception on the XMLFormatTarget line, but if I change the string from "C:/test.xml" to "test.xml" it works fine. // test.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <xercesc/util/XMLString.hpp> #include <xercesc/framework/LocalFileFormatTarget.hpp> using namespace xercesc; int main() { XMLPlatformUtils::Initialize(); XMLFormatTarget *formatTarget = new LocalFileFormatTarget("C:/test.xml"); return 0; } [edit] Xerces exception is: Error Message: unable to open file 'C:\test.xml' Windows exception is: Access is denied
It could be that you don't have sufficient permissions to write to C:\. In such a case, Xerces might report the error throwing an exception. An Access Denied exception is typically what we could expect if you try to write to a system directory without administrator credentials. Maybe it has also something to do with the directory separators: XMLFormatTarget *formatTarget = new LocalFileFormatTarget("C:\\test.xml"); On Windows, directory separators are backslashes "\". Some libraries don't care (and I never used Xerces, so I can't tell). In C and C++, backslash is also an escape character and so you must double it if you want a litteral "\" in your string. Also, telling us what was the exception you got would help us even more. Not directly related, but from your code, it seems you never delete formatTarget. I assume this is sample code, but if it is not, you should add the following line to your code: delete formatTarget; Or use a scoped pointer instead: boost::scoped_ptr<XMLFormatTarget> formatTarget(new LocalFileFormatTarget("C:\\test.xml")); To avoid memory leaks.
3,091,718
3,091,781
Base 256 GUID String Representation w/Character Offset 0x01F
I need to make a string representation of a 128bit GUID that represents 8bit chunks instead of 4bit; so like base 256 :/ Why? Because I need to shorten the length of the string hex representation of the GUID, it is too long. I have a max array size of 31 plus NULL terminator. Also the character value cannot be from 0x000 to 0x01F.... It's giving me a headache but I know it can be done. Any suggestions on the best and safest way how? Right now I'm just mucking around with memcpy and adding 0x01F but the numbers keep bouncing around in my head.... can't nail 'em down no! And I have to interconvert :\
Try base64 encoding : it packs 6-bits per character and is still portable. You will need 22 chars to store 128 bits GUID in a portable way.
3,091,833
3,091,871
Calling member functions from a constructor
I know this question has a similar title to this: C++: calling member functions within constructor? but I am asking a more general question. Is it good practice to call member functions from within a constructor? It makes reading the code easier and I prefer the encapsulation type way of doing it (ie. each block of code has a single objective). An illustrative example, in python: class TestClass: def __init__(self): self.validate() def validate(self): # this validates some data stored in the class Is this a better way of doing it than writing the validate code inside the constructor? Are there drawbacks to this method? For example is it more costly with the function overhead? I personally prefer it for readability but that's just my preference. Cheers
I don't think there is anything inherently wrong in calling member functions from a constructor provided that they are not virtual functions. The problem with calling virtual member functions from a constructor is that a subclass can override the function. This will cause the constructor to call the overridden implementation in the subclass, before the constructor for the subclass part of the object has been called. In Java, any one of the private, static or final access modifiers will make the method safe to call from a constructor by preventing a virtual call to the superclass method. I don't think these techniques are available in Python.
3,092,198
3,092,217
C++, preventing class instance from being created on the stack (during compiltaion)
I know there are methods to prevent a class from being created on the heap, by preventing the user from using the new and delete operator. I am trying to do just the opposite. I have a class that I want to prevent the user from creating an instance of it on the stack, and that only instances instigated using the new operator will compile. More specifically, I want the following code to receive an error during compilation: MyClass c1; //compilation error MyClass* c1 = new MyClass(); //compiles okay From searching the web, I found this suggestion on how to do it: class MyClass { public: MyClass(); private: void destroy() const { delete this; } ... private: ~MyClass(); }; int main(int argc,char** argv) { MyClass myclass; // <--- error, private destructor called here !!! MyClass* myclass_ptr = new MyClass; myclass_ptr->destroy(); } What I don't understand is why this should work. Why would the destructor be called while creating an instance of MyClass?
When myclass reaches the end of its scope (the next }) the compiler calls the destructor to free it from the stack. If the destructor is private, however, then the destructor cannot be accessed, so the class cannot be placed on the stack. I don't like the look of delete this. In general I think objects should not destroy themselves. Perhaps a better way is to have a private constructor for your class then use a static function to create an instance. // In class declaration... static MyClass* Create() { return new MyClass(); // can access private constructor } // ... MyClass myclass; // illegal, cannot access private constructor MyClass* pMyClass = MyClass::Create(); delete pMyClass; // after usage
3,092,280
3,115,666
Does any MOF implementation exist in C++?
Is there any alternative to JMI for C++? Thanks for the links or suggestions.
EMF4CPP has just now been published. It is basically an implementation of Ecore in C++ (and Ecore is basically an adaptation of the Essential MOF OMG standard). Hope it helps
3,092,444
3,092,544
keeping private parts outside c++ headers: pure virtual base class vs pimpl
I recently switched back from Java and Ruby to C++, and much to my surprise I have to recompile files that use the public interface when I change the method signature of a private method, because also the private parts are in the .h file. I quickly came up with a solution that is, I guess, typical for a Java programmer: interfaces (= pure virtual base classes). For example: BananaTree.h: class Banana; class BananaTree { public: virtual Banana* getBanana(std::string const& name) = 0; static BananaTree* create(std::string const& name); }; BananaTree.cpp: class BananaTreeImpl : public BananaTree { private: string name; Banana* findBanana(string const& name) { return //obtain banana, somehow; } public: BananaTreeImpl(string name) : name(name) {} virtual Banana* getBanana(string const& name) { return findBanana(name); } }; BananaTree* BananaTree::create(string const& name) { return new BananaTreeImpl(name); } The only hassle here, is that I can't use new, and must instead call BananaTree::create(). I do not think that that is really an problem, especially since I expect to be using factories a lot anyway. Now, the wise men of C++ fame, however, came up with another solution, the pImpl idiom. With that, if I understand it correctly, my code would look like: BananaTree.h: class BananaTree { public: Banana* addStep(std::string const& name); private: struct Impl; shared_ptr<Impl> pimpl_; }; BananaTree.cpp: struct BananaTree::Impl { string name; Banana* findBanana(string const& name) { return //obtain banana, somehow; } Banana* getBanana(string const& name) { return findBanana(name); } Impl(string const& name) : name(name) {} } BananaTree::BananaTree(string const& name) : pimpl_(shared_ptr<Impl>(new Impl(name))) {} Banana* BananaTree::getBanana(string const& name) { return pimpl_->getBanana(name); } This would mean I have to implement a decorator-style forwarding method for every public method of BananaTree, in this case getBanana. This sounds like an added level of complexity and maintenance effort that I prefer not to require. So, now for the question: What is wrong with the pure virtual class approach? Why is the pImpl approach so much better documented? Did I miss anything?
I can think of a few differences: With the virtual base class you break some of the semantics people expect from well-behaved C++ classes: I would expect (or require, even) the class to be instantiated on the stack, like this: BananaTree myTree("somename"); otherwise, I lose RAII, and I have to manually start tracking allocations, which leads to a lot of headaches and memory leaks. I also expect that to copy the class, I can simply do this BananaTree tree2 = mytree; unless of course, copying is disallowed by marking the copy constructor private, in which case that line won't even compile. In the above cases, we obviously have the problem that your interface class doesn't really have meaningful constructors. But if I tried to use code such as the above examples, I'd also run afoul of a lot of slicing issues. With polymorphic objects, you're generally required to hold pointers or references to the objects, to prevent slicing. As in my first point, this is generally not desirable, and makes memory management much harder. Will a reader of your code understand that a BananaTree basically doesn't work, that he has to use BananaTree* or BananaTree& instead? Basically, your interface just doesn't play that well with modern C++, where we prefer to avoid pointers as much as possible, and stack-allocate all objects to benefit form automatic lifetime management. By the way, your virtual base class forgot the virtual destructor. That's a clear bug. Finally, a simpler variant of pimpl that I sometimes use to cut down on the amount of boilerplate code is to give the "outer" object access to the data members of the inner object, so you avoid duplicating the interface. Either a function on the outer object just accesses the data it needs from the inner object directly, or it calls a helper function on the inner object, which has no equivalent on the outer object. In your example, you could remove the function and Impl::getBanana, and instead implement BananaTree::getBanana like this: Banana* BananaTree::getBanana(string const& name) { return pimpl_->findBanana(name); } then you only have to implement one getBanana function (in the BananaTree class), and one findBanana function (in the Impl class).
3,092,475
3,092,538
C++ mixins via templates: why doesn't this work?
I've got a interface that's implemented as an abstract base class with a number of pure virtual public methods. These pure virtual functions can be implemented using a template since the differences between subclasses aren't large - so my idea was to use multiple inheritance to mix-in the appropriately templated helper-class that provides the implementation. However, the compiler complains that the base class is abstract; it isn't considering the helper mix-in's implementation so thinks there's no implementation of a required method. For example: class TrivialList { int count; public: TrivialList(int count) : count(count){} virtual double Average() const=0; int Count() const {return count;} virtual ~TrivialList(){} }; template<typename TIndexable> class AverageHelper { public: double Average() const { TIndexable const & self = static_cast<TIndexable const &>(*this); double sum=0.0; for(int i=0;i<self.Count();++) sum += self.Get(i); return sum / self.Count(); } }; class IndexableList : public TrivialList, public AverageHelper<IndexableList> { std::vector<double> backend; public: IndexableList(int count) : TrivialList(count), backend(count) { } double & Get(int i) { return backend[i];} double const & Get(int i) const { return backend[i];} }; IndexableList * MakeList() {return new IndexableList(5);} //error! // cannot instantiate abstract class I'm using MSC 10.0 (Visual Studio 2010); the code fails with a similar error using g++ 4.5. Get or the real-world equivalents in my project cannot be virtual because they're extremely minor operations that need to be inlined for adequate performance (think put-pixel/get-pixel) - so I need the generic algorithms to be templated rather than generic via virtual function calls.
It doesn't work because AverageHelper<>::Average() doesn't override TrivialList::Average(). In order to override a virtual function, the overriding class must inherit from the class containing the function to be overridden. You could change your template thus: template<typename TIndexable, typename Base > class AverageHelper : public Base { public: template< typename T > AverageHelper(T arg) : Base(arg) {} // ... }; class IndexableList : public AverageHelper<IndexableList,TrivialList> { public: IndexableList(int count) : AverageHelper<IndexableList,TrivialList>(count) {} // ... }; You might want to virtually derive from TrivialList: template<typename TIndexable, typename Base > class AverageHelper : virtual public Base { // ... };
3,092,483
3,092,537
C++: Strange behaviour of `new`
SDL provides me this struct: typedef struct SDL_Rect { Sint16 x, y; Uint16 w, h; } SDL_Rect; I want to create a new SDL_Rect on the heap as class variable: // Forward declaration private: SDL_Rect *m_pcScreenRect; And in the constructor I do this: /* Screen Rectangle (for clearing) */ m_pcScreenRect = new SDL_Rect; m_pcScreenRect->x = 0; m_pcScreenRect->y = 0; m_pcScreenRect->w = 800; m_pcScreenRect->h = 600; printf("Rect(x:%d, y:%d, w:%d, h:%d)\n", m_pcScreenRect->x, m_pcScreenRect->y, m_pcScreenRect->w, m_pcScreenRect->h); Which prints Rect(x:0, y:0, w:800, h:600) So this is correct. Problem 1 But when I don't initialize x and y, it prints rubbish numbers like: Rect(x:-11280, y:63, w:800, h:600) Rect(x:25584, y:167, w:800, h:600) Rect(x:-11280, y:40, w:800, h:600) // This is just, run, terminate, run, terminate, .... And I thought the default value for an int is 0? Problem 2 In my gameloop, I have the same line to check the values of the SDL_Rect. In the loop I get results like this: Clear (x:0, y:40, w:0, h:560) Clear (x:0, y:99, w:0, h:501) Clear (x:0, y:55, w:0, h:545) Clear (x:0, y:55, w:0, h:545) // Again: run, terminate, run, terminate.... When my constructor looks like this: /* Screen Rectangle (for clearing) */ m_pcScreenRect = new SDL_Rect; //m_pcScreenRect->x = 0; //m_pcScreenRect->y = 0; m_pcScreenRect->w = 800; m_pcScreenRect->h = 600; And I get normal results when I uncomment the two lines: /* Screen Rectangle (for clearing) */ m_pcScreenRect = new SDL_Rect; m_pcScreenRect->x = 0; m_pcScreenRect->y = 0; m_pcScreenRect->w = 800; m_pcScreenRect->h = 600; Does this problem something have to do with new or with the datatypes (Uint16, and a normal int). If it is with the datatypes, how to solve it? Thanks would be very appreciated! (Haha!) Thanks, Any help would be very appreciated! Extra Question: I have to define all my variables in C++. But from where do the random numbers come? I'm using g++ and gcc in Linux.
In order to make use of the "default value for an int", you can use value initialization: m_pcScreenRect = new SDL_Rect(); // this will initialize to zeros Otherwise, the values are not defined. To give more details: adding a constructor to this structure would be the best approach, but since it's in a third-party library which you (I suppose) cannot modify, you can either wrap it in your own class that provides a default constructor, or use value-initialization. To quote C++03 8.5/5, To value-initialize an object of type T means: if T is a class type with a user-declared constructor, then the default constructor for T is called if T is a non-union class type without a user-declared constructor, then every non-static data member and base-class component of T is value-initialized; if T is an array type, then each element is value-initialized; otherwise, the object is zero-initialized In your case, SDL_Rect is a non-union class type without a user-declared constructor (second clause in this list), meaning value-initialization is performed for its non-static data memebers, and each of those data members falls under the "otherwise" clause, and is zero-initialized (which is defined as "if T is a scalar type, the object is set to the value of 0 (zero) converted to T;")
3,092,549
3,094,533
What free tiniest flash file system could you advice for embedded system?
I've got DSP tms320vc5509a and NOR flash AT26DF321 on the board and I'm going to store named data on the flash. I don't need directory hierarchy, wear leveling (I hope system will write to flash very few times), but CRC is strongly needed. Thank you
You could look at the ELM-Petit FAT File System Module for an good small file system implementation. Not sure that it has CRC but you can add that to your low-level hardware drivers.
3,092,550
3,328,321
C++ Keywords not Colored in Emacs
I have been using emacs for a while for mainly python programming, and have started C++ coding with it. When I open a c++ file, it opens without problems with c++-mode. The background and foreground colors are normal for the theme I have with color-theme, but keywords and strings are not colored differently. Below is the code in my .emacs to initialize color-theme. (add-to-list 'load-path "D:\\emacs\\color-theme-6.6.0") (require 'color-theme) (color-theme-initialize) (setq color-theme-is-global t) (color-theme-hober) I have not put in any code for c++. Any ideas? Edit: I tried turning off color-theme to see if at least then there would be some coloring, and there was not, even after ensuring font-lock-mode was on. Also, this is GNU Emacs 23.1.1
I finally got syntax highlighting by removing a folder called site-lisp from the folder d:/emacs. My Emacs installation is in d:/emacs/emacs-23.1, and somehow it was reading from these files. So, removing this folder forced Emacs to use the correct ones, I think.
3,092,697
3,093,034
c++ boost compilation catastrophe
I'm writing a DLL plugin for a windows application, after adding the following includes: #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> I get a wonderful compilation error: Error 3 error C2143: syntax error : missing ';' before '__cdecl' c:\program files (x86)\microsoft visual studio 9.0\vc\include\locale.h 111 LeverateMetaTraderServerAPI Help?
someone who isn't really smart added this : #define __declspec(dllexport) __stdcall APIENTRY to one of the API .h files your including
3,092,740
3,092,783
Makefile for compiling a number of .cpp and .h into a lib
I am running Windows 7 with gcc/g++ under Cygwin. What would be the Makefile format (and extension, I think it's .mk?) for compiling a set of .cpp (C++ source) and .h (header) files into a static library (.dll). Say I have a variable set of files: file1.cpp file1.h file2.cpp file2.h file3.cpp file3.h .... What would be the makefile format (and extension) for compiling these into a static library? (I'm very new to makefiles) What would be the fastest way to do this?
The extension would be none at all, and the file is called Makefile (or makefile) if you want GNU Make to find it automatically. GNU Make, at least, lets you rely on certain automatic variables that alone give you control over much of the building process with C/C++ files as input. These variables include CC, CPP, CFLAGS, CPPFLAGS, CXX, CXXFLAGS, and LDFLAGS. These control the switches to the C/C++ preprocessor, compiler, and the linker (the program that in the end assembles your program) that make will use. GNU Make also includes a lot of implicit rules designed to enable it automatically build programs from C/C++ source code, so you don't [always] have to write your own rules. For instance, even without a makefile, if you try to run make foobar, GNU Make will attempt to first build foobar.o from foobar.c or foobar.cpp if it finds either, by invoking appropriate compiler, and then will attempt to build foobar by assembling (incl. linking) its parts from system libraries and foobar.o. In short, GNU Make knows how to build the foobar program even without a makefile being present -- thanks to implicit rules. You can see these rules by invoking make with the -p switch. Some people like to rely on GNU Make's implicit rule database to have lean and short makefiles where only that specific to their project is specified, while some people may go as far as to disable the entire implicit rule database (using the -r switch) and have full control of the building process by specifying everything in their makefile(s). I won't comment on superiority of either strategy, rest assured both do work to some degree.
3,092,763
3,095,792
Is a pointer to a virtual member function valid in the constructor of the base class?
My question is not about calling a virtual member function from a base class constructor, but whether the pointer to a virtual member function is valid in the base class constructor. Given the following class A { void (A::*m_pMember)(); public: A() : m_pMember(&A::vmember) { } virtual void vmember() { printf("In A::vmember()\n"); } void test() { (this->*m_pMember)(); } }; class B : public A { public: virtual void vmember() { printf("In B::vmember()\n"); } }; int main() { B b; b.test(); return 0; } Will this produce "In B::vmember()" for all compliant c++ compilers?
The pointer is valid, however you have to keep in mind that when a virtual function is invoked through a pointer it is always resolved in accordance with the dynamic type of the object used on the left-hand side. This means that when you invoke a virtual function from the constructor, it doesn't matter whether you invoke it directly or whether you invoke it through a pointer. In both cases the call will resolve to the type whose constructor is currently working. That's how virtual functions work, when you invoke them during object construction (or destruction). Note also that pointers to member functions are generally not attached to specific functions at the point of initalization. If the target function is non-virtual, they one can say that the pointer points to a specific function. However, if the target function is virtual, there's no way to say where the pointer is pointing to. For example, the language specification explicitly states that when you compare (for equality) two pointers that happen to point to virtual functions, the result is unspecified.
3,092,856
3,092,882
How to ensure that randomly generated numbers are not being repeated?
Possible Duplicates: Unique (non-repeating) random numbers in O(1)? How do you efficiently generate a list of K non-repeating integers between 0 and an upper bound N I want to generate random number in a certain diapason, and I must be sure, that each new number is not a duplicate of formers. One solution is to store formerly generated numbers in a container and each new number checks aginst the container. If there is such number in the container, then we generate agin, else we use and add it to the container. But with each new number this operation is becoming slower and slower. Is there any better approach, or any rand function that can work faster and ensure uniqueness of the generation? EDIT: Yes, there is a limit (for example from 0 to 1.000.000.000). But I want to generate 100.000 unique numbers! (Would be great if the solution will be by using Qt features.)
Is there a range for the random numbers? If you have a limit for random numbers and you keep generating unique random numbers, then you'll end up with a list of all numbers from x..y in random order, where x-y is the valid range of your random numbers. If this is the case, you might improve speed greatly by simply generating the list of all numbers x..y and shuffling it, instead of generating the numbers.
3,092,928
3,092,948
How to reuse enum operator overloads in C++?
I have several flag-like enumerations, in C++. For example: enum some_state { state_normal = 1 << 0, state_special = 1 << 1, state_somethingelse = 1 << 2, state_none = 0, }; some_state var1; Now on using bit operators like & or |, I get compiler errors. I know I can overload operator | et.al. for enums, but I hate to do that again for each and every enum. Is there a nice way to reuse the operator overloads?
I tried and searched, and I think the best solution is a #define. Based on something I found: #define FLAGS(T) \ inline T operator |(const T s, const T e) { return (T)((unsigned)s | e); } \ inline T &operator |=(T &s, const T e) { return s = s | e; } \ inline T operator &(const T s, const T e) { return (T)((unsigned)s & e); } \ inline T &operator &=(T &s, const T e) { return s = s & e; } \ inline T operator ^(const T s, const T e) { return (T)((unsigned)s ^ e); } \ inline T &operator ^=(T &s, const T e) { return s = s ^ e; } \ inline T operator ~(const T s) { return (T)~(unsigned)s; } This can be used like: enum some_state { state_normal = 1 << 0, state_special = 1 << 1, state_somethingelse = 1 << 2, state_none = 0, }; FLAGS(some_state) some_state var1; For Visual Studio one might need this to silence some warnings: #pragma warning(disable: 4505) // '*' : unreferenced local function has been removed In fact, the Windows SDK has the DEFINE_ENUM_FLAG_OPERATORS macro to do just that. A different approach is a wrapper class like DEF_ENUM_FLAGS_TYPE uses. Or use something like the LLVM_MARK_AS_BITMASK_ENUM macro. You might need a recent compiler though.
3,093,049
3,093,082
Different behavior of compilers with array allocation
I recently found a interesting behaviour of g++ when compared with MSVC++ 2008. Consider this tiny program: #include <cstdlib> const int ARR_LENGTH = 512; void doSomething( int iLen ); int main( int argc, char** argv ) { doSomething( ARR_LENGTH ); return 0; } void doSomething( int iLen ) { int iTest[iLen]; return; } Will it compile? What do you think? According to my knowledge of C (or C++ for that matter), this should NOT compile, since i can call the function doSomething() with any integer i want, so the size of iTest array cannot be determined at compile time. However, when i try to compile this with g++, it works just fine. Now i can understand what probably happened here - the compiler noticed that i call this function only once passing a compile-time constant as a parameter. Some serious optimizations going on here... But when i try to compile this using MSVC++ 2008, i get this: 1>c:\prj\test\test.cpp(15) : error C2057: expected constant expression 1>c:\prj\test\test.cpp(15) : error C2466: cannot allocate an array of constant size 0 1>c:\prj\test\test.cpp(15) : error C2133: 'iTest' : unknown size My question is: how does this comply with the definition of the language (the C standard (C++ standard))? Is it just fine for g++ to do such an optimization (which in this case is easy to see, but the first time i encountered it, it was in a large project and it did not make much sense at first sight).
C99 (the most recent version of the C standard) does allow dynamically sized arrays. However, the feature is not supported by Visual Studio (which only implements C89 support) In C++ it is not, and probably will never be, valid.
3,093,116
3,093,142
How do I pass an array as a parameter?
This is driving me crazy: I have function void gst_init(int *argc, char **argv[]); in the gstreamer api and I want to call it with some parameters I define, like: int argc = 2; char* argv[2] = {"myvalue1", "myvalue2"}; gst_init(&argc, &argv); This code doesn't compile (I get error C2664): error C2664: 'gst_init' : cannot convert parameter 2 from 'char *(*)[2]' to 'char **[]' The question: How do I define the argv value to pass it as a parameter? I've been using C++ for over 5 years, but I haven't used a raw array since ... high-school I think (more than five years ago). Edit: I'm using VS2010 Express.
Try int argc = 2; char* arg1[1] = {"myvalue1"}; char* arg2[1] = {"myvalue2"}; char** argv[2] = { arg1, arg2 }; gst_init(&argc, argv); char **argv[] is an array of char**, which is analogous to an array of char* arrays. OTOH what you tried to pass as parameter is shown as char *(*)[2]: a pointer to an array of char*.
3,093,164
3,109,269
Polygon to Polygon Collision Detection Issue
I have been having a few issues implementing my narrow phase collision detection. Broadphase is working perfectly. I have a group of polygons, that have a stl::vector array of points for their vertices in clockwise order. Every cycle, I check to see whether they're colliding. I have borrowed the following Point in Polygon test from here and changed it using my Point data structures: int InsidePolygon(std::vector <Point> poly, Point p) { int i, j, c = 0; int nvert = poly.size(); for (i = 0, j = nvert-1; i < nvert; j = i++) { if ( ((poly[i].y> p.y) != (poly[j].y> p.y)) && (p.x < (poly[j].x-poly[i].x) * (p.y-poly[i].y) / (poly[j].y-poly[i].y) + poly[i].x) ) c = !c; } return c; } I have extended that to include a PolygonPolygon function, which check all the points of 1 polygon against another and then reverse it to check the other way around. int PolygonPolygon(std::vector <Point> polygon1, std::vector <Point> polygon2) { for(int i=0; i<polygon1.size();i++) { if(InsidePolygon(polygon2, polygon1[i])) { return 1; } } for(int j=0; j<polygon2.size();j++) { if(InsidePolygon(polygon1, polygon2[j])) { return 1; } } return 0; } The strange thing is that my PolygonPolygon function is always returning 1. So I have a few questions: Have I screwed up the logic somewhere? Should I write my PolygonPolygon function differently? Are there any better methods for a PolygonPolygon test, the polygons themselves are not guaranteed to be convex, which is why I went for the point in polygon method. I also hope to determine which point is colliding eventually, if I can get past this bit. Should I be presenting my points in a particular order for the InsidePolygon test?
Thanks for your help guys! But i've managed to sort it out on my own. The importance of translating your vertices to world space and rotating them should not be overlooked, especially if you're colliding them.
3,093,451
3,093,470
Is it safe to pass a vector as an array?
Say I have a function: void someFunc(int *x,int count); which is out of my control, so I can't write it to accept iterators. Is it safe to call it like so (regardless of the specific STL implementation): vector<int> v; /* ... */ someFunc(&v[0],v.size()); Obviously, one counter example is vector<bool>. How about any other type? (assuming I haven't specialized vector in any way).
From section 23.2.4, point 1 of the standard: [...] The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size(). So yes, it is safe. Note: If v is empty v[0] is undefined behavior so you should only do this if v is not empty.
3,093,535
3,094,174
How to debug a buffer overrun in Visual C++ 9?
I have a huge MMC snapin written in Visual C++ 9. Every once in a while when I hit F5 in MMC mmc.exe crashes. If I attach a debugger to it I see the following message: A buffer overrun has occurred in mmc.exe which has corrupted the program's internal state. Press Break to debug the program or Continue to terminate the program. For more details please see Help topic 'How to debug Buffer Overrun Issues'. First of all, there's no How to debug Buffer Overrun Issues topic anywhere. When I inspect the call stack I see that it's likely something with security cookies used to guard against stack-allocated buffer overruns: MySnapin.dll!__crt_debugger_hook() Unknown MySnapin.dll!__report_gsfailure() Line 315 + 0x7 bytes C mssvcr90d.dll!ValidateLocalCookies(void (unsigned int)* CookieCheckFunction=0x1014e2e3, _EH4_SCOPETABLE * ScopeTable=0x10493e48, char * FramePointer=0x0007ebf8) + 0x57 bytes C msvcr90d.dll!_except_handler4_common(unsigned int * CookiePointer=0x104bdcc8, void (unsigned int)* CookieCheckFunction=0x1014e2e3, _EXCEPTION_RECORD * ExceptionRecord=0x0007e764, _EXCEPTION_REGISTRATION_RECORD * EstablisherFrame=0x0007ebe8, _CONTEXT * ContextRecord=0x0007e780, void * DispatcherContext=0x0007e738) + 0x44 bytes C MySnapin.dll!_except_handler4(_EXCEPTION_RECORD * ExceptionRecord=0x0007e764, _EXCEPTION_REGISTRATION_RECORD * EstablisherFrame=0x0007ebe8, _CONTEXT * ContextRecord=0x0007e780, void * DispatcherContext=0x0007e738) + 0x24 bytes C ntdll.dll!7c9032a8() [Frames below may be incorrect and/or missing, no symbols loaded for ntdll.dll] ntdll.dll!7c90327a() ntdll.dll!7c92aa0f() ntdll.dll!7c90e48a() MySnapin.dll!IComponentImpl<CMySnapin>::GetDisplayInfo(_RESULTDATAITEM * pResultDataItem=0x0007edb0) Line 777 + 0x14 bytes C++ // more Win32 libraries functions follow I have lots of code and no idea where the buffer overrun might occur and why. I found this forum discussion and specifically the advise to replace all wcscpy-like functions with more secure versions like wcscpy_s(). I followed the advise and that didn't get me closer to the problem solution. How do I debug my code and find why and where the buffer overrun occurs with Visual Studio 2008?
I assume you aren't able to reproduce this reliably. I've successfully used Rational Purify to hunt down a variety of memory problems in the past, but it costs $ and I'm not sure how it would interact with MMC. Unless there's some sort of built-in memory debugger you may have to try solving this programmatically. Are you able to remove/disable chunks of functionality to see if the problem manifests itself? If you have "guesses" about where the problem occurs you can try disabling/changing that code as well. Even if you changed the copy functions to _s versions, you still need to be able to reliably handle truncated data.
3,093,568
3,093,608
unfamiliar with struct/class declaration with template
while going through some of the mili source code I came across a struct declared like this: template <class T, class Pre, class Pos> struct PrePosCaller<T*, Pre, Pos> (from here) The part I'm unfamiliar with is <T*, Pre, Pos>. I understand what the code does and its purpose in this context but I would like to know where it is documented so I can learn/understand it a bit more.
That is a template specialization. In particular a partial specialization. Somewhere in the code there is a template declared as: template <class T, class Pre, class Pos> struct PrePosCaller { //... }; or something similar. Then they are providing an specialization of that template for the cases where the first argument is a pointer type. That is, this is a template definition for PrePosCaller when the first argument of the template is a pointer.
3,093,632
3,094,774
Why must C/C++ string literal declarations be single-line?
Is there any particular reason that multi-line string literals such as the following are not permitted in C++? string script = " Some Formatted String Literal "; I know that multi-line string literals may be created by putting a backslash before each newline. I am writing a programming language (similar to C) and would like to allow the easy creation of multi-line strings (as in the above example). Is there any technical reason for avoiding this kind of string literal? Otherwise I would have to use a python-like string literal with a triple quote (which I don't want to do): string script = """ Some Formatted String Literal """; Why must C/C++ string literal declarations be single-line?
One has to consider that C was not written to be an "Applications" programming language but a systems programming language. It would not be inaccurate to say it was designed expressly to rewrite Unix. With that in mind, there was no EMACS or VIM and your user interfaces were serial terminals. Multiline string declarations would seem a bit pointless on a system that did not have a multiline text editor. Furthermore, string manipulation would not be a primary concern for someone looking to write an OS at that particular point in time. The traditional set of UNIX scripting tools such as AWK and SED (amongst MANY others) are a testament to the fact they weren't using C to do significant string manipulation. Additional considerations: it was not uncommon in the early 70s (when C was written) to submit your programs on PUNCH CARDS and come back the next day to get them. Would it have eaten up extra processing time to compile a program with multiline strings literals? Not really. It can actually be less work for the compiler. But you were going to come back for it the next day anyhow in most cases. But nobody who was filling out a punch card was going to put large amounts of text that wasn't needed in their programs. In a modern environment, there is probably no reason not to include multiline string literals other than designer's preference. Grammatically speaking, it's probably simpler because you don't have to take linefeeds into consideration when parsing the string literal.
3,093,929
3,093,958
Doesn't C++ IDE Netbeans or Eclipse support class inheritance?
I am using NetBeans IDE 6.8 to create C++ project. While I use class inheritance, however, it seems to me that it does not recognize the derived class. Here is what I have: class A { public: A(vector<double> a, double b) {...} }; class B : public A { public: additionalfunction(...) {...} }; main() { vector<double> c = something; double d = 0; B b=B(c, d); } And the compiler tells me that "B(c,d)" is not declared. I tried Eclipse C++, it told me the same thing. Why is that? Is it because both IDEs do not support C++ inheritance? What should I do? Any reply is appreciated.
I'd suggest implementing the constructor in class B.
3,093,959
3,094,023
Stream extraction within if/else
Assuming the stream extraction won't fail, will this if( !(stream >> token) ) throw runtime_error( "Unexpected end of recipe." ); else if( token == "something" ) // do something else throw runtime_error( "Unknown token" ); Work like this if( !(stream >> token) ) throw std::runtime_error( "Unexpected end of recipe." ); if( token == "something" ) // do something else throw std::runtime_error( "Unknown token" ); (stream = std::stringstream and token = std::string) And the expected result being token contains the next ... token... from the stream? Is there a better way to handle errors? Like cerr << "error whatever" << endl; exit(); or something, or is my std::runtime_error good enough?
Yes, the logic is exactly the same. And I wouldn't ever call exit() - at least in your code the exception can be caught by some other code instead of just killing the app. You never know if you will use this code inside a larger application sometime in the future so it's better to keep your options open ;)
3,094,219
3,094,575
How can I return a copy of a vector containing elements not in a set?
Suppose I have the following two data structures: std::vector<int> all_items; std::set<int> bad_items; The all_items vector contains all known items and the bad_items vector contains a list of bad items. These two data structures are populated entirely independent of one another. What's the proper way to write a method that will return a std::vector<int> contain all elements of all_items not in bad_items? Currently, I have a clunky solution that I think can be done more concisely. My understanding of STL function adapters is lacking. Hence the question. My current solution is: struct is_item_bad { std::set<int> const* bad_items; bool operator() (int const i) const { return bad_items.count(i) > 0; } }; std::vector<int> items() const { is_item_bad iib = { &bad_items; }; std::vector<int> good_items(all_items.size()); std::remove_copy_if(all_items.begin(), all_items.end(), good_items.begin(), is_item_bad); return good_items; } Assume all_items, bad_items, is_item_bad and items() are all a part of some containing class. Is there a way to write them items() getter such that: It doesn't need temporary variables in the method? It doesn't need the custom functor, struct is_item_bad? I had hoped to just use the count method on std::set as a functor, but I haven't been able to divine the right way to express that w/ the remove_copy_if algorithm. EDIT: Fixed the logic error in items(). The actual code didn't have the problem, it was a transcription error. EDIT: I have accepted a solution that doesn't use std::set_difference since it is more general and will work even if the std::vector isn't sorted. I chose to use the C++0x lambda expression syntax in my code. My final items() method looks like this: std::vector<int> items() const { std::vector<int> good_items; good_items.reserve(all_items.size()); std::remove_copy_if(all_items.begin(), all_items.end(), std::back_inserter(good_items), [&bad_items] (int const i) { return bad_items.count(i) == 1; }); } On a vector of about 8 million items the above method runs in 3.1s. I bench marked the std::set_difference approach and it ran in approximately 2.1s. Thanks to everyone who supplied great answers.
Since your function is going to return a vector, you will have to make a new vector (i.e. copy elements) in any case. In which case, std::remove_copy_if is fine, but you should use it correctly: #include <iostream> #include <vector> #include <set> #include <iterator> #include <algorithm> #include <functional> std::vector<int> filter(const std::vector<int>& all, const std::set<int>& bad) { std::vector<int> result; remove_copy_if(all.begin(), all.end(), back_inserter(result), [&bad](int i){return bad.count(i)==1;}); return result; } int main() { std::vector<int> all_items = {4,5,2,3,4,8,7,56,4,2,2,2,3}; std::set<int> bad_items = {2,8,4}; std::vector<int> filtered_items = filter(all_items, bad_items); copy(filtered_items.begin(), filtered_items.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; } To do this in C++98, I guess you could use mem_fun_ref and bind1st to turn set::count into a functor in-line, but there are issues with that (which resulted in deprecation of bind1st in C++0x) which means depending on your compiler, you might end up using std::tr1::bind anyway: remove_copy_if(all.begin(), all.end(), back_inserter(result), bind(&std::set<int>::count, bad, std::tr1::placeholders::_1)); // or std::placeholders in C++0x and in any case, an explicit function object would be more readable, I think: struct IsMemberOf { const std::set<int>& bad; IsMemberOf(const std::set<int>& b) : bad(b) {} bool operator()(int i) const { return bad.count(i)==1;} }; std::vector<int> filter(const std::vector<int>& all, const std::set<int>& bad) { std::vector<int> result; remove_copy_if(all.begin(), all.end(), back_inserter(result), IsMemberOf(bad)); return result; }
3,094,467
3,094,543
Performance Profiling with Visual Studio
How can I get Visual Studio to help me optimize my application, or tell me areas of slowness? Thanks
As another suggestion, I have found the AMD CodeAnalyst a great companion. It integrates with VS2010 very well, and provides detailed breakdown of CPU time on a line-to-line basis. You can zoom in and out to see from a top-level to a function-level. Not to mention it even has in-line disassembly display if you need that extra bit of information! Totally worth a try.
3,094,573
3,094,860
extern "C" DLL: Debug is OK, Release throws Error C2059
I've got a DLL that I've created as a C++ Win32 application. To prevent name mangling in my DLL, I have used the EXPORT definition defined below: #ifndef EXPORT #define EXPORT extern "C" __declspec(dllexport) #endif EXPORT int _stdcall SteadyFor(double Par[], double Inlet[], double Outlet[]); To get this code to compile, I had to go into the project's Properties and set the C/C++ Calling Convention to __stdcall (/Gz) and set Compile As to Compile as C++ Code (/TP). This worked in Debug mode, but Release mode is throwing error C2059: syntax error: 'string' on all of my EXPORT functions - even though I have configured the Release mode settings to be the same as the Debug settings. How do I get Release Mode to compile? Regards, ~Joe (Developing under Visual Studio 2008 Professional) EDIT: A lot of comments about my #define, which does not appear to be causing any problems. To eliminate the confusion, my header file has been rewritten as follows: #ifndef coilmodel_h #define coilmodel_h extern "C" __declspec(dllexport) int _stdcall steadyFor(double Par[], double Inlet[], double Outlet[], char* FileIn, char* FileOut); #endif That is all of it. The error is: Description error C2059: syntax error: 'string' File coilmodel.h Line 4 Again, this error only appears in Release mode, not Debug mode. Project is a C++ Win32 DLL application.
If your source file has a .c extension, the compiler you are using will compile it as C (not C++) and produce that error on the extern "C". If that is the case, then you need to use the /TP switch as you already noted or rename the file to .cpp. The other solution is to put #ifdefs around the extern: #ifdef __cplusplus extern "C" #endif
3,094,758
3,095,031
MessageBox does not work in a catch of an exception
Well I have 2 issues but my main concern right now is my catch exception. Here is the code... int GXRenderManager::Ignite(HINSTANCE * hinst, int * nCmd, GXDEVICE DeviceType, int width, int height) { try { GXRenderManager::hinstance = hinst; GXRenderManager::nCmdShow = nCmd; GXRenderManager::height = height; GXRenderManager::width = width; InitWindows(); switch(DeviceType) { case DIRECTX: GXRenderManager::renderDevice = new GXDX; break; case OPENGL: GXRenderManager::renderDevice = new GXGL; break; default: throw GXException(L"Error Finding Video Device"); } Device()->StartUp(GXRenderManager::mainWindow ,width, height); //Error happens here } catch(GXVideoException &e) { MessageBox(0,e.pReason,L"GXVideoException",1);//Catch happens but no message box return 0; } catch(GXWindowsException &e) { MessageBox(0,e.pReason,L"Windows Error",1); return 0; } catch(GXException &e) { MessageBox(0,e.pReason,L"Error",1); return 0; } return 1; } Here is where the error happens void GXDX::StartUp(HWND* mainWindow,int w, int h) { width = w; height = h; this->mainWindow = mainWindow; ID3D10Texture2D *backBufferSurface; DXGI_SWAP_CHAIN_DESC swapChainDesc; swapChainDesc.BufferCount = 2; swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swapChainDesc.BufferDesc.RefreshRate.Numerator = 60; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; swapChainDesc.BufferDesc.Width = width; swapChainDesc.BufferDesc.Height = height; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.OutputWindow = *mainWindow; swapChainDesc.Windowed = TRUE; D3D10_DRIVER_TYPE driverType = D3D10_DRIVER_TYPE_HARDWARE; HRESULT hr = D3D10CreateDeviceAndSwapChain(NULL,driverType,NULL,0, D3D10_SDK_VERSION, &swapChainDesc,&swapChain,&dxDevice); if(FAILED(hr)) throw GXVideoException(L"Problems retrieving directX device"); } When I do a walk through. the D3D10CreateDeviceAndSwapChain returns a failure, therefore triggering the GXVideoException error. It then catches and returns back to GXRenderManager class as shown below. catch(GXVideoException &e) { MessageBox(0,e.pReason,L"GXVideoException",1); return 0; } At this point in time, If I put my cursor over the &e, I clearly see my message "Problems retrieving directX device". But the message box does not show int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { if(GXRenderManager::Ignite(&hInstance, &nCmdShow,DIRECTX) != 1) return 0; //NEVER REACHES THE RUN METHOD BELOW YET THE MAIN WINDOW REMAINS OPEN GXRenderManager::Run(); return 0; } Another thing I find strange is that my created window remains showing but never reaches the main loop. It is like the application is idle due to the message box, but the message box is not showing... I also would like to add that the static member renderDevice is a interface datatype. GXDX is of course a implemented class of the interface. GXDX class includes the GXException Header so it is able to throw those exceptions so the main GXRenderManager can catch them. [EDIT] Another thing I would like to add is if I remove the Show window method ShowWindow(*GXRenderManager::mainWindow, *GXRenderManager::nCmdShow); It works. So as long as my main application window is not open. My message box appears like its suppose to. [EDIT] Prior to dauphic response which fixed part of the problem, I went on and edited my code. My catch now looks like this catch(GXVideoException &e) { MessageBox(*GXRenderManager::mainWindow,e.pReason,L"GXVideoException",1); return 0; } But now my application opens and then immediately closes without displaying the box. mainWindow is a pointer to my base window. So I had to dereference the pointer. [EDIT] The windows pointer is bad
If a dialog is present, MessageBox should always be passed a handle to it, rather than 0. Only pass MessageBox 0 if no dialog is available. Side note, I don't understand the exact reason for this, so it would be great if someone else could give insight. It's also possible that your message box is being attached to your dialog, and because your dialog isn't active, the message box isn't showing. Pressing alt when it hangs may cause it to show.
3,094,875
3,179,220
What's the standard way of trapping system messages in Qt4?
I've been looking for a way to trap and retrieve system messages in Qt4, specifically the WM_DEVICECHANGE messages among others. I know how to in C# but can find any conclusive text on how to in Qt4. Thanks in advance..
Look into implementing the winEvent() method, say, in your MainWindow subclass. #include "Windows.h" #include "Dbt.h" bool MainWindow::winEvent(MSG *message, long *result) { if (message->message==WM_DEVICECHANGE) { ui->plainTextEdit->appendPlainText("WM_DEVICECHANGE message received"); if (message->wParam==DBT_DEVICEARRIVAL) ui->plainTextEdit->appendPlainText("A new device has arrived"); if (message->wParam==DBT_DEVICEREMOVECOMPLETE) ui->plainTextEdit->appendPlainText("A device has been removed"); } return false; } I just tested the above by inserting my USB video camera into the system and removing it and I did get appropriate looking output into the plaintext edit. You should see further info on the winEvent() method in the Qt docs, of course. (For info on when to return false or true from the function etc)
3,094,917
3,095,043
How does sizeof work? How can I write my own?
I know C++ and know the function sizeof itself but I need to write my own sizeof function so please explain how it works exactly? What does it do with the parameter?
You haven't provided any meaningful details about what it is you want to do, so it is hard to figure out what you need. You can "wrap" sizeof by you own template function like template <typename T> size_t my_sizeof() { return sizeof(T); } and then use it as size_t s = my_sizeof<int>(); From time to time one can come across a request to implement sizeof-like functionality without using sizeof. Requests like that make no practical sense whatsoever, yet sometimes are used as homework assignments. One can probably do it as follows template <typename T> size_t my_sizeof() { T t; return (char *) (&t + 1) - (char *) &t; } which would require a default-constructible T. A less restricting but formally illegal solution (a hack) would be something like template <typename T> size_t my_sizeof() { return (char *) ((T *) NULL + 1) - (char *) (T *) NULL; } The above implementations implement type-based sizeof. An attempt to emulate the functionality of value-based sizeof might look as follows template <typename T> size_t my_sizeof(const T& obj) { return my_sizeof<T>(); } but this will not be even remotely equivalent to the built-in sizeof, at least because the built-in sizeof does not evaluate its argument. Finally, neither of these implementations will produce integral constant expressions (ICE), as the built-in sizeof does. Producing an ICE that way is impossible to achieve in the current version of the language. In any case this all, of course, is totally devoid of any practical value. Just use sizeof when you want to know the size.
3,094,972
3,094,995
When should I use do-while instead of while loops?
Possible Duplicates: Is there ever a need for a “do {…} while ( )” loop? Do your loops test at the top or bottom? While vs. Do While When is a do-while appropriate? I've been having a philosophical debate with a colleague as to whether as a general rule, in C/C++ we should should use while loops rather than do-wile loops. My feeling is that the only time you should use a do-while is if you need to repeatedly test the same thing and you will always want to do so at least once. Generally I always felt that a while loop is more readable. I realise this could be considered a somewhat subjective / personal style thing, but I'd be interested to hear anyone's thoughts as to whether I'm right or mising something here. Concrete examples would be especially welcome.
Use while loops when you want to test a condition before the first iteration of the loop. Use do-while loops when you want to test a condition after running the first iteration of the loop. For example, if you find yourself doing something like either of these snippets: func(); while (condition) { func(); } //or: while (true){ func(); if (!condition) break; } You should rewrite it as: do{ func(); } while(condition);
3,094,977
3,095,028
How to use Enum with strings in a function?
Basically, I have a Linked List which implements a display()function that simply loops throught he elements and prints out their values. I wanted to do it like this: void List::display( std::string type ) { switch(type) { // Do stuff... The compiler immediately complained. My teacher said this would be because the string is not known at compile-time, resulting in an error. That explanation sounds a little iffy, but he suggested that I use enums. So I researched it and it says that explicit string to enums doesn't work. Something like class List { enum type { HORIZONTAL = "inline" VERTICAL = "normal" } and then, I really don't know. The enum type is a part of the List class, as well as the function display(). This again looks like a really crappy solution. Nevertheless, I want to know if this approach is possible. How could I set the enum in the main function at the same time I call display()? Like so int main( void ) { display("normal"); Of course, easier approaches are very welcome. In general, how do I declare/pass an enum to a function, if possible?
Switch, in current C++, only works with integral types. You could define your enum, switch on it, and write an auxiliary function that maps the enum to string values if needed. Example enum E { A, B }; string E_to_string( E e ) { switch(e) { case A: return "apple"; case B: return "banana"; } } void display( E e ) { std::cout << "displaying an " << E_to_string(e) << std::endl; switch(e) { case A: // stuff displaying A; case B: // stuff displaying B; } }
3,095,000
3,095,208
How to monitor/show progress during a C++ sort
I'm planning to write an interactive C++ geometry processing plug-in that will frequently sort large amounts of data. Although preliminary indications are that the sort will take only a second or two, I'd prefer to show progress during that time - i.e I'd like to update a progress indicator a few times per second. This would be preferable to turning on a wait cursor and leaving the user with a program that freezes for an indeterminate length of time (even if that's just a few seconds). If I were to use something like std::sort, I could use the comparison function to update the progress indicator every now and then, but I'd have no idea of 'percentage complete'. I could also break the sort down into sub-sorts, updating progress between sub-sorts, and then merging. My best bet may be to write own sort method, although I don't know how much effort it would require to get performance as good as std::sort (and ensure correctness). In any case, that sort method would occasionally send a "percentage complete" to a callback method. I was wondering whether other people have encountered and solved this problem - I'm hoping that maybe there's a sort method in a standard library that does what I want, or some other technique that I haven't thought of. Update: Thanks for the great answers so far. There have been a few very good suggestions, and I'm going to hold off on choosing the accepted answer until I've had a chance to test out the ideas in my upcoming project. Update 2: I completed my project, and this turned out to be a non-issue (at least for the customer. Since they will be selling the software, they may still get feedback from their customers that will change their minds about this). Choosing an accepted answer was difficult because there were many good answers, but in the end the one I chose pointed to a wiki article on Merge Sort that had a very evocative animation. So that's the first strategy I would have pursued had I needed to go ahead with this).
Since std::sort is template based, the source should be available in a header. You can make a copy of it and insert your progress callback. The big problem will be predicting how close you are to completion - most sort functions will be based on Quicksort, which doesn't always do the same number of comparisons. Writing your own Merge sort would be a possibility; the algorithm is easy and the number of steps are well defined.
3,095,062
3,096,580
How to add a QAction to specific position in a QToolBar
QToolBar::insertWidget allows to add a QWidget after a specific QAction. Is there any way to add a QAction at a specific position? Removing all actions and then re-adding them again after is my last hope !
You can use the insertAction() method, inherited from QWidget, to insert your QAction before a given QAction.
3,095,549
3,095,620
min and perfect forwarding
The min algorithm is normally expressed like this: template <typename T> const T& min(const T& x, const T& y) { return y < x ? y : x; } However, this does not allow constructs of the form min(a, b) = 0. You can achieve that with an additional overload: template <typename T> T& min(T& x, T& y) { return y < x ? y : x; } What I would like to do is unify these two overloads via perfect forwarding: template <typename T> T&& min(T&& x, T&& y) { return y < x ? std::forward<T>(y) : std::forward<T>(x); } However, g++ 4.5.0 spits out a warning for min(2, 4) that I return a reference to a temporary. Did I do something wrong? Okay, I get it. The problem is with the conditional operator. In my first solution, if I call min(2, 4) the conditional operator sees an xvalue and thus moves from the forwarded x to produce a temporary object. Of course it would be dangerous to return that by reference! If I forward the whole expression instead of x and y seperately, the compiler does not complain anymore: template <typename T> T&& min(T&& x, T&& y) { return std::forward<T>(y < x ? y : x); } Okay, I got rid of the references for arithmetic types :) #include <type_traits> template <typename T> typename std::enable_if<std::is_arithmetic<T>::value, T>::type min(T x, T y) { return y < x ? y : x; } template <typename T> typename std::enable_if<!std::is_arithmetic<T>::value, T&&>::type min(T&& x, T&& y) { return std::forward<T>(y < x ? y : x); }
It looks to me like you're trying to oversimplify the problem. Unfortunately, getting it entirely correct is decidedly non-trivial. If you haven't read N2199, now would be a good time to do so. Rvalue references continue to evolve, so its reference implementation of min and max probably isn't exactly right anymore, but it should at least be a pretty decent starting point. Warning: the reference implementation is a lot more complex than you're going to like!
3,095,658
3,095,947
I have some circularities in my template class definitions
I have a matrix class that takes the row and column reference type that can be used to access it as template parameters. Meanwhile, the row and column types are passed the matrix type that they are representing. Is there any way to break this circularity? Here are some demonstrative code snippets: #include "MatrixConcreteType.h" template <class MatrixType> class rowType <MatrixType> {...} And in the matrix file: #include "VectorTypes.h" template <class row_t, class col_t> class Matrix {...} I suppose I could try a well placed extern?
If I am understanding your question correctly, you are trying to define Matrix as a template taking a row type and a column type, and then the rowType (and i assume also columnType) as templates of a matrix type. My big question is: where is the actual data? At some point, I presume this Matrix should actually break down to a structured group of ints, or doubles, or chars, or reverse iterators of pointers to bools, or something. Where is that? your circularity seems to be a symptom of trying to make too much architecture. Figure out which class you want to actually store the data in, make the template parameter of that class the type of that data, then make the template parameter of all other related classes either the main class, or the data type as well. for example: template <class DataType> class Matrix{ //store the data in here: a DataType [], or vector<DataType>, or something } and: template <class MatrixType> class Row{ //has something which refers back to the original matrix of type MatrixType } or template <class DataType> class Row{ //has something which refers back to the original matrix of type Matrix<DataType> } I would suggest using the second of the above alternatives, as it makes is easier to refer to the Row class in the Matrix class, such as: template <class DataType> Row<DataType> Matrix::getRow(int index){ //return an instance of Row<DataType> containing the appropriate row }
3,095,856
3,098,480
preventing unaligned data on the heap
I am building a class hierarchy that uses SSE intrinsics functions and thus some of the members of the class need to be 16-byte aligned. For stack instances I can use __declspec(align(#)), like so: typedef __declspec(align(16)) float Vector[4]; class MyClass{ ... private: Vector v; }; Now, since __declspec(align(#)) is a compilation directive, the following code may result in an unaligned instance of Vector on the heap: MyClass *myclass = new MyClass; This too, I know I can easily solve by overloading the new and delete operators to use _aligned_malloc and _aligned_free accordingly. Like so: //inside MyClass: public: void* operator new (size_t size) throw (std::bad_alloc){ void * p = _aligned_malloc(size, 16); if (p == 0) throw std::bad_alloc() return p; } void operator delete (void *p){ MyClass* pc = static_cast<MyClass*>(p); _aligned_free(p); } ... So far so good.. but here is my problem. Consider the following code: class NotMyClass{ //Not my code, which I have little or no influence over ... MyClass myclass; ... }; int main(){ ... NotMyClass *nmc = new NotMyClass; ... } Since the myclass instance of MyClass is created statically on a dynamic instance of NotMyClass, myclass WILL be 16-byte aligned relatively to the beginning of nmc because of Vector's __declspec(align(16)) directive. But this is worthless, since nmc is dynamically allocated on the heap with NotMyClass's new operator, which doesn't nesessarily ensure (and definitely probably NOT) 16-byte alignment. So far, I can only think of 2 approaches on how to deal with this problem: Preventing MyClass users from being able to compile the following code: MyClass myclass; meaning, instances of MyClass can only be created dynamically, using the new operator, thus ensuring that all instances of MyClass are truly dynamically allocatted with MyClass's overloaded new. I have consulted on another thread on how to accomplish this and got a few great answers: C++, preventing class instance from being created on the stack (during compiltaion) Revert from having Vector members in my Class and only have pointers to Vector as members, which I will allocate and deallocate using _aligned_malloc and _aligned_free in the ctor and dtor respectively. This methos seems crude and prone to error, since I am not the only programmer writing these Classes (MyClass derives from a Base class and many of these classes use SSE). However, since both solutions have been frowned upon in my team, I come to you for suggestions of a different solution.
If you're set against heap allocation, another idea is to over allocate on the stack and manually align (manual alignment is discussed in this SO post). The idea is to allocate byte data (unsigned char) with a size guaranteed to contain an aligned region of the necessary size (+15), then find the aligned position by rounding down from the most-shifted region (x+15 - (x+15) % 16, or x+15 & ~0x0F). I posted a working example of this approach with vector operations on codepad (for g++ -O2 -msse2). Here are the important bits: class MyClass{ ... unsigned char dPtr[sizeof(float)*4+15]; //over-allocated data float* vPtr; //float ptr to be aligned public: MyClass(void) : vPtr( reinterpret_cast<float*>( (reinterpret_cast<uintptr_t>(dPtr)+15) & ~ 0x0F ) ) {} ... }; ... The constructor ensures that vPtr is aligned (note the order of members in the class declaration is important). This approach works (heap/stack allocation of containing classes is irrelevant to alignment), is portabl-ish (I think most compilers provide a pointer sized uint uintptr_t), and will not leak memory. But its not particularly safe (being sure to keep the aligned pointer valid under copy, etc), wastes (nearly) as much memory as it uses, and some may find the reinterpret_casts distasteful. The risks of aligned operation/unaligned data problems could be mostly eliminated by encapsulating this logic in a Vector object, thereby controlling access to the aligned pointer and ensuring that it gets aligned at construction and stays valid.
3,096,042
3,096,245
Check if string contains a range of numbers
I'd like to test a std::string for containing numbers of any range e.g 5 to 35 in a std::string s = "XDGHYH20YFYFFY" would there be function or I would have to convert a number to string and then use a loop to find each one?
I'd probably use a locale that treated everything except digits as white-space, and read the numbers from a stringstream imbued with that locale and check if they're in range: #include <iostream> #include <algorithm> #include <locale> #include <vector> #include <sstream> struct digits_only: std::ctype<char> { digits_only(): std::ctype<char>(get_table()) {} static std::ctype_base::mask const* get_table() { static std::vector<std::ctype_base::mask> rc(std::ctype<char>::table_size,std::ctype_base::space); std::fill(&rc['0'], &rc['9'], std::ctype_base::digit); return &rc[0]; } }; bool in_range(int lower, int upper, std::string const &input) { std::istringstream buffer(input); buffer.imbue(std::locale(std::locale(), new digits_only())); int n; while (buffer>>n) if (n < lower || upper < n) return false; return true; } int main() { std::cout << std::boolalpha << in_range(5, 35, "XDGHYH20YFYFFY"); return 0; }
3,096,262
3,096,341
Social networking APIs and C/C++
Folks, Note sure if this is the best place to ask this one, but I doubt there'd be a better place. I see that github, stackoverflow, facebook, twitter, linkedin etc. have been providing developer API to slice and dice user information. Couple of questions on the general nature of these API: 1) Are these open-source? 2) Is there any general feedback on which specific programming language works best with these kind of 'social' APIs? In particular, any comments on whether C/C++ are suited for such work? 3) Is there any recommended C/C++ open source package for 'mashups' across social networks?
An API is a specification, not code, to "open-source" doesn't really apply though each might have licensing restrictions on how you use their API that might affect how suitable they were to your code being open-source. The language will be dictated (or suggested) primarily based on what you're doing with the data, not how/where you obtain the data. You might find the networking part a bit simpler with something like Python or Perl, and do only the heavy computation (if any) in C++. I doubt there's one that's universally recommended. The usual suspects (e.g., Boost::ASIO, ACE, POCO) will probably work reasonably well for this as they do with other networking.
3,096,453
3,096,556
Options for granting access to class data members (C++)
This is a basic question about what options are available for defining the scope of some parameters. I'd particularly like to have a sense of the tradeoffs in speed, memory, code clarity, ease of implementation, and code safety. My programming experience is clearly modest, and I have little formal training. I suspect one or two options will be obvious 'right' answers. I have a simulation encapsulated in its own class called Simulation. Some of the parameters used in the simulation are read in from a set of files when the Simulation is initialized, and these parameters are currently stored in a few two-dimensional arrays. These arrays, demPMFs and serotypePars, are currently both private members of Simulation: // Simulation.h class Simulation { Simulation( int simID ); ~Simulation(); public: // ...[code snipped]... private: double demPMFs[ NUM_SOCIODEM_FILES ][ INIT_NUM_AGE_CATS ]; double serotypePars[ NUM_EPID_FILES ][ INIT_NUM_STYPES ]; // ...[code snipped]... }; The simulations mostly involve modifying instances of class Host. Member functions of class Host frequently need access to parameter values stored in serotypePars. Previously, I had all the data now in serotypePars stored as const numerics interpreted at compile time, but now that these parameters are read from a file, things are a little more complicated (for me, anyway). What is the fastest and safest way for me to grant all members of class Host 'read-only' access to serotypePars? Fastest deserves priority: There are no other classes in my program, so global is a (crude) potential solution; all simulations will run from identical parameter sets. I'm reluctant to pass the array to individual functions that act on Host members, since there are probably a dozen and some are quite nested. (For example, I have intermediate wrapper structs that cannot take two-dimensional arrays as arguments, and I'm unsure what syntactical work-arounds there might be. I would like to stick with arrays for speed purposes, and my non-uniform prng generators all expect arrays.) I would greatly appreciate knowing what would require the least modification of the existing code while not introducing huge dangers. Thanks for any insight you can offer. A related challenge I have is not knowing exactly how to access Simulation members from the Host class, unless these members are passed to the Host function. Here's basically what happens: // main.cpp int main() { for ( int s = 1; s < NUM_SIMS+1; s++ ) { Simulation thisSim(s); thisSim.runDemSim(); thisSim.runEpidSim(); // ... code snipped ... } } Function Simulation::runDemSim() and Simulation::runEpidSim() create, modify, and destroy many instances of class Host. Pointers to these instances are stored in a Boost MultiIndex container, which is where the intermediate wrapper functions come in. One of the many modifications involves ultimately calling Host::calcRecovery, which needs access to serotypePars: // Host.cpp // ... code snipped ... double Host::calcRecovery( int s, double currentTime, double infectionTime, boost::mt19937& rng ) { // ...code snipped... effectiveMean = serotypePars[ MEAN_DURATION_INDEX ][ s ] * currentInfections * pastInfections; double rt = rgamma( effectiveMean, serotypePars[ VAR_DURATION_INDEX ][ s ], rng ); } (Apologies if TMI.) Simply declaring serotypePars public in the Simulation class definition resulted in a "serotypePars was not declared in this scope" error in Host.cpp. Solution summary GMan's suggestion that I package all the simulation parameters in a private class, e.g., SimulationPars, seems like the most elegant and extensible route. An instance of SimulationPars could belong in every Simulation, and a pointer to SimulationPars can be passed to the constructor of every Host within a given Simulation. Thanks to everyone for the thoughtful discussions.
This is normal: class Simulation { public: // typedef's should be used liberally, it's easier to read typedef double pmf_type[NUM_SOCIODEM_FILES][INIT_NUM_AGE_CATS]; typedef double sero_type[NUM_EPID_FILES][INIT_NUM_STYPES]; // accessors const pmf_type& get_pmf(void) const { return demPMFs; } const sero_type& get_sero(void) const { return serotypePars; } private: pmf_type demPMFs; sero_type serotypePars; };
3,096,617
3,096,634
Usage of this pointer
I have a question relating to the usage of "this". Suppose I have two classes A & B; their rough outline is as follows: class A { public: ... void AddB( B* b ) { // inserts B into the vector v } private: std::vector<B*> v; }; class B { public: ... void foo( void ) { ... // Adds itself to the queue held in A a.AddB( this ); } }; Is using "this" in this way generally bad practice? Thank you for your help.
No, there's nothing wrong with that, as long as you are careful about ownership and deletion.
3,096,642
3,097,179
LINK : fatal error LNK1104: cannot open file '..\json_spirit\Debug\json_spirit_lib.lib'
Can someone point me in the right direction? I'm not a C++ or VS developer but I'm trying to compile a project and I'm getting the above error. I don't have any clue why the compiler is looking for that file or what the Debug folder is about (though I could guess). Can somebody explain the issue in other words for me and give me some pointers on how to fix?
This page http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx speaks of two methods to link with the Json spirit library from c++. I imagine your problem is that one or more of the header files includes a #pragma to automatically link certain libraries, the compiler can't find one of these libraries, namely json_spirit_lib.lib This might be because of compiler level set up (default library directories); project set up (linker input and libray directories) or simply that you don't have the required .lib files in the source directories.
3,096,671
3,096,712
OSX, static variable sharing same address
In OSX I have the following code. Using gcc 4.0.1. I'm new to OSX development so I'm not sure what other system information would be useful here... static int textstrArgs[] = { 1, 1, 1 }; void func() { static int first = 1; if (first) { first = 0; // stuff } /* other stuff */ } where func() is declared as 'extern' and is called from another library. The problem is that the address of 'texstrArgs[2]' and 'first' is the same. That is, when the application loads it's putting both of these variables at the same spot in memory. When func() is called the first = 0 is clobbering the value in the static textstrArgs array. Would could I be doing that would cause this to occur? Thanks for any help anyone can give.
Just a hunch - try changing: static int textstrArgs[] = { 1, 1, 1 }; to static int textstrArgs[3] = { 1, 1, 1 }; One other thing - are you actually referencing textstrArgs anywhere ? If not then it may be that it's getting optimised away.
3,096,758
3,097,542
How should I profile visual c++ express?
I've read a lot of the posts here giving profiling advice but I need to ask this. From what I can tell, Visual C++ Express doesn't generate a debugging file that is used by profiler programs. I tried AMD Codeanalyst and it seemed to work fine except none of the routines in my program were identified -- just a lot of "unidentified modules". I'm new to C++. I'm used to the simple profiler used by Python. Simple, I assume, because the language is interpreted. I appreciate any insights. P.S.: Is the rotation of the steering wheel the derivative of the rotation of the car?
First, the polar angular velocity of the car should be proportional to the speed of the car and to the angular position of the steering wheel (to a first approximation). Second, there's hardly a professor or blogger or book author who will tell you this, but if you want to see what the code is doing and optimize it, the hands-down simplest way is this. Added: Programmers have a strong tendency to assume that any automated profiling tool will do a better job than the manual technique, but that depends on the details of exactly what they do. Most of them implement what's popular rather than what is most effective. The result is some performance problems being missed, putting a cap on the speedup you can get. Here is a list of common misconceptions that result in failing to find performance problems. Some profilers do get it nearly right, including RotateRight/Zoom and LTProf.
3,096,813
3,096,839
C++ Builder onResize event after exit
I wrote some program in C++ Builder 6 (don't ask me why). I do some actions with on-form components after formResize event occurs. But it occurs right after I close my program, and looks like all components on form where deleted, so I've got exception and everything crashes. There is my code: void __fastcall TForm3::FormResize(TObject *Sender) { Image1->Picture->Graphic->Width = Image1->Width; Image1->Picture->Graphic->Height = Image1->Height; } What can I do with that?
You could check to make sure the objects haven't been deleted: void __fastcall TForm3::FormResize(TObject *Sender) { if (Image1) { Image1->Picture->Graphic->Width = Image1->Width; Image1->Picture->Graphic->Height = Image1->Height; } } But that assumes you always set pointers back to NULL when you delete them. UPDATE: Or you could do this: void __fastcall TForm3::FormResize(TObject *Sender) { if (this->Visible) { Image1->Picture->Graphic->Width = Image1->Width; Image1->Picture->Graphic->Height = Image1->Height; } }
3,096,823
3,097,183
Get USB serial number c++
I'm looking to retrieve the serial number from a USB memory stick on windows in c++. I have found plenty of C# examples, and c++ for linux but none for c++ and windows. Edit C++/CLI is not an option unfortunately. I am looking for the serial number of the device not the file system. OR "Device Instance Path" AKA "InstanceID"
If C++ is a requirement then you'll have to write COM code. A bit unjoyful compared to VB.NET code, but there are very good examples available in the MSDN library, you just need to adapt the query. Beware that the example you linked to does not return a serial number of the device itself, just the file system on the device. Which is as good as it is going to get it, USB devices don't have serial numbers. File system serial numbers are trivial to duplicate, in case you are contemplating this to write some kind of licensing enforcement scheme. If that's important then you should use a USB device that was designed for that purpose. A dongle. Impossible to crack. And C++ code to verify the license will be available from the manufacturer.
3,097,229
3,102,601
Protocol Buffer and UTF16 Unicode
How do you use Google Protocol Buffer with UTF16 Unicode?
Basically I will convert UTF16 to UTF8. Searching SO, I think your answer is in this question
3,097,264
3,097,279
How can I make a std::list of arrays?
I would like to make an std::list of arrays. specifically, I want a list of arrays of Borland Code Builders AnsiStrings. the real kicker being that I would like the arrays to be allocated dynamically. How do I define the list? Im so lost here i dont know were to begin. std::list<???> myList; What am I putting inside the angle brackets? nothing i have tried will work.
typedef std::vector<char> char_array; typedef std::list<char_array> char_array_list; Or more appropriately: typedef std::list<std::string> string_list;
3,097,445
3,097,555
vector of double[2] error
why this error: #include <vector> typedef double point[2]; int main() { std::vector<point> x; } /usr/include/c++/4.3/bits/stl_construct.h: In function ‘void std::_Destroy(_Tp*) [with _Tp = double [2]]’: /usr/include/c++/4.3/bits/stl_construct.h:103: instantiated from ‘void std::_Destroy(_ForwardIterator, _ForwardIterator) [with _ForwardIterator = double (*)[2]]’ /usr/include/c++/4.3/bits/stl_construct.h:128: instantiated from ‘void std::_Destroy(_ForwardIterator, _ForwardIterator, std::allocator&) [with _ForwardIterator = double (*)[2], _Tp = double [2]]’ /usr/include/c++/4.3/bits/stl_vector.h:300: instantiated from ‘std::vector::~vector() [with _Tp = double [2], _Alloc = std::allocator]’ prova.cpp:8: instantiated from here /usr/include/c++/4.3/bits/stl_construct.h:88: error: request for member ‘~double [2]’ in ‘* __pointer’, which is of non-class type ‘double [2]’ how to solve?
You can't do that. As mentioned, arrays are not copyable or assignable which are requirements for std::vector. I would recommend this: #include <vector> struct point { double x; double y; }; int main() { std::vector<point> v; } It will read better anyway since you can do things like: put(v[0].x, v[0].y, value); which makes it more obvious this the vector contains points (coordinates?)
3,097,548
3,097,666
Exporting global variables from DLL
I'm trying to export a global variable from a DLL. Foo.h class Foo { public: Foo() {} }; #ifdef PROJECT_EXPORTS #define API __declspec(dllexport) #else #define API __declspec(dllimport) #endif API const Foo foo; Foo.cpp #include "Foo.h" const Foo foo; When I compile the above code, Visual Studio complains: foo.cpp(3) : error C2370: 'foo' : redefinition; different storage class 1> foo.h(14) : see declaration of 'foo' If I use: external const Foo foo; in Foo.h the compiler is happy but then the DLL does not export the symbol. I've managed to export functions with problems, but variables don't seem to work the same way... Any ideas?
In your header: API extern const Foo foo; In your source file: API const Foo foo; If you don't have the extern keyword, your C compiler assumes you mean to declare a local variable. (It doesn't care that you happened to have included the definition from a header file.) You also need to tell the compiler that you're planning on exporting the variable when you actually declare it in your source file.
3,097,593
3,097,611
What happens when C++ reference leaves its scope?
If I interpret C++ references correctly, they are like pointers, but with guaranteed data integrity (no NULL, no (int*) 0x12345). But what happens when scope of referenced object is leaved? If there are no magic involved (and probably it is not), referenced object will be destroyed behind my back. I wrote a piece of code to check this: #include <iostream> using namespace std; class A { public: A(int k) { _k = k; }; int get() { return _k; }; int _k; }; class B { public: B(A& a) : _a(a) {} void b() { cout << _a.get(); } A& _a; }; B* f() { A a(10); return new B(a); } int main() { f()->b(); } The _k instance variable was put in to check stack frame existence. It surprisingly does not segfault and instead prints '10' correctly, while I suppose that A is allocated on stack and that stack frame of f() will be overwritten by at least cout<< call.
this is undefined behavior and you were simply lucky that the memory for a hadn't been used for anything else yet. In a more complex scenario you would almost certainly get garbage. On my machine I get random garbage with this code. For me, this is likely because I am using a 64-bit machine which uses a register calling convention. Registers get re-used much more often than main memory (ideally...). So to answer your question of "what happens". Well in this scenario, the reference is likely little more than a limited pointer with friendlier syntax :-). Under the hood the address of a is stored. Later the a object goes out of scope, but the B object's reference to that a will not be "auto-magically" updated to reflect this. Hence you have an invalid reference now. Using this invalid reference will yield just about anything, sometimes crashes, sometimes just bunk data. EDIT: Thanks to Omnifarious, I've been thinking about this. There is a rule in c++ that basically says that if you have a const reference to a temporary, then the lifetime of the temporary is at least as long as the const reference. Which introduced a new question. EDIT: Moved to separate question for those interested (const reference to temporary oddity)
3,097,626
3,097,671
strange error in g++
My program has a class with a vector of Level objects named levels. In a member function there is this line: levels.push_back(level::Level()); I made several changes to my program today, and that line of code started segfaulting: 0x0804d248 in void std::vector<yarl::level::Level, std::allocator<yarl::level::Level> >::emplace_back<yarl::level::Level>(yarl::level::Level&&) (this=0x0, __args#0=...) at /usr/include/c++/4.4/bits/vector.tcc:93 93 if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage) I thought that the Level object may have somehow become corrupt, so I declared it outside the function call so I could inspect it in gdb, like this: level::Level foo(); levels.push_back(foo); Turns out this doesn't compile. It g++ gives two errors I haven't seen before: error: invalid conversion from 'level::Level (*)()' to 'int' error: initializing argument 1 of 'level::Level::Level(int, int, int)' Now, Level's constructor takes three integer parameters, each with default values. I thought it might have been complaining that I hadn't passed those three parameters, even though they have defaults, so I changed the first line to pass the value of the defaults: level::Level foo(1, 100, 100); This now compiles, and still segfaults, but does so at a different spot (although an identical test): 0x0804c699 in std::vector<yarl::level::Level, std::allocator<yarl::level::Level> >::push_back (this=0x0, __x=...) at /usr/include/c++/4.4/bits/stl_vector.h:735 735 if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage) I realize this is too little code to expect you guys to be able to solve my problem, but perhaps someone could tell me a little more about what these errors mean? Those g++ errors especially; I don't know why it wouldn't accept an empty Level constructor given that all its parameters are default, and I have no idea what the (*)() part of the error means (it makes the error a very frustrating one to google).
level::Level foo(); That declares a function named foo that takes no arguments and returns a level::Level. This is known as the most vexing parse. This creates a level::Level using the default constructor: level::Level foo; As for your original problem, you appear to have a null this pointer: ... ::push_back (this=0x0, __x=...) ... This could happen if levels is a reference to null. Did you create the reference by dereferencing a null pointer?
3,097,655
3,181,548
Compilation errors when inheriting PortableServer::RefCountServantBase
I am working on a corba application where in create_servant() method we are creating new servant and returning it to the callee. To make the memory management easier, I am inheriting PortableServer::RefCountServantBase class to the implementation class. I get the below compilation errors. "simples.cpp", line 108: Error: Cannot create a variable for abstract class Simple_i. "simples.cpp", line 108: Error: PortableServer::ServantBase::invoke(CORBA::ServerRequest*) has not been overridden. "simples.cpp", line 108: Error: PortableServer::ServantBase::_primary_interface(const PortableServer::ObjectId&, PortableServer::POA*) has not been overridden. 3 Error(s) detected. If I don't inherit RefCountServantBase I don't get any compilation errors. In samples.cpp, which is not shown here we are creating an instance of sample_i and returning it. Here is the sample code: // sample_i.h #include "simple_s.h" extern char* generate_unique_id(); // Generate unique uuids class Simple_i : public virtual POA_Simple , virtual public PortableServer::RefCountServantBase { public: virtual char* to_lower(const char* val); virtual void to_upper(char*& val); virtual char* to_print(const char* val); }; class SimpleFactory_i : public virtual POA_SimpleFactory // , virtual public PortableServer::RefCountServantBase { public: virtual Simple_ptr find_simple(); // To make simpapp scalable have the SimpleFactory use the user // supplied identifier in the Simple object reference it creates. }; ================================================================================ // sample_s.h #include <string.h> #include "orbminor.h" #include <Tobj_ServantBase.h> #include "simple_c.h" class POA_Simple : public Tobj_ServantBase { public: virtual ::CORBA::Char * to_lower ( const char * str) = 0; virtual void to_upper ( ::CORBA::Char *& str) = 0; virtual ::CORBA::Char * to_print ( const char * str) = 0; ::Simple_ptr _this(); void invoke (::CORBA::ServerRequest_ptr _nasreq); ::CORBA::RepositoryId _primary_interface ( const PortableServer::ObjectId &, PortableServer::POA_ptr); protected: virtual ~POA_Simple(){ } private: OBBArgument *getparams (::CORBA::Short, OBB::ServerRequest * SrvReq, ::CORBA::ULong & ArgCnt); }; class POA_SimpleFactory : public Tobj_ServantBase { public: virtual ::Simple_ptr find_simple () = 0; ::SimpleFactory_ptr _this(); void invoke (::CORBA::ServerRequest_ptr _nasreq); ::CORBA::RepositoryId _primary_interface ( const PortableServer::ObjectId &, PortableServer::POA_ptr); protected: virtual ~POA_SimpleFactory(){ } private: OBBArgument *getparams (::CORBA::Short, OBB::ServerRequest * SrvReq, ::CORBA::ULong & ArgCnt); }; #endif Update: I changed the inheritance and did not inherit PortableServer::RefCountServantBase, since RefCountServantBase itself is getting inherited by Tobj_ServantBase. Now, I have the code as below. Is this fine? Do I need to care about memory management here ? Or am I missing something? Tobj_Servant Server::create_servant(const char* intf_repos_id) { Tobj_Servant servant = NULL; if (!strcmp(intf_repos_id, _tc_SimpleFactory->id())) { servant = new SimpleFactory_i(); } if (!strcmp(intf_repos_id, _tc_Simple->id())) { servant = new Simple_i(); } servant->_add_ref(); return servant; // unknown interface }
In newer versions of CORBA, RefCountServantBase is deprecated. You no longer need to inherit from it because the auto-generated C++ servants now provide the same functionality. You should verify that the ORB you are using has implemented this change. As to the part of your question about your create_servant() function. It should be fine from the servant creation aspect. However it looks strange that you can assign multiple things to your servant variable. If this happened you would leak. I also can't say about _tc_SimpleFactory->id() or _tc_Simple->id() because I'm not familiar with those functions. If they return CORBA strings then you are leaking memory.
3,097,684
3,097,709
how to call a method with string& parameter by using char*?
I have a C++ dll from other company. there is a method with a string& msg parameter, void methodA(string& msg); What I have now is a char* with length which is big enough to take the msg from methodA. I want to call methodA to get message back from methodA. Can I do it? how? thanks,
#include <algorithm> void foo(char* buffer) { std::string str; methodA(str); std::copy(str.begin(), str.end(), buffer); buffer[str.size()] = 0; }
3,097,779
3,097,803
decltype and parentheses
I don't understand the last line of the example on page 148 of the FCD (§7.6.1.2/4): const int&& foo(); int i; struct A { double x; }; const A* a = new A(); decltype(foo()) x1 = i; // type is const int&& decltype(i) x2; // type is int decltype(a->x) x3; // type is double decltype((a->x)) x4 = x3; // type is const double& Why do the parentheses make a difference here? Shouldn't it simply be double like in the line above?
Just above that example, it says if e is an unparenthesized id-expression or a class member access (5.2.5), decltype(e) is the type of the entity named by e. if e is an lvalue, decltype(e) is T&, where T is the type of e; I think decltype(a->x) is an example of the "class member access" and decltype((a->x)) is an example of lvalue.
3,097,806
3,097,861
const reference to temporary oddity
We all know that things like this are valid in c++: const T &x = T(); while: T &x = T(); is not. In a recent question the conversation lead to this rule. The OP had posted some code which clearly evokes UB. But I would have expect a modified version of it to work (This is the modified version): #include <iostream> using namespace std; class A { public: A(int k) { _k = k; }; int get() const { return _k; }; int _k; }; class B { public: B(const A& a) : _a(a) {} void b() { cout << _a.get(); } const A& _a; }; B* f() { return new B(A(10)); } int main() { f()->b(); } This prints garbage on some machines, 10 on others... sounds like UB to me :-). But then I thought, well A is basically a glorified int all it does it initialize one and read it. Why not just call A an int and see what happens: #include <iostream> using namespace std; typedef int A; class B { public: B(const A& a) : _a(a) {} void b() { cout << _a; } const A& _a; }; B* f() { return new B(A(10)); } int main() { f()->b(); } It prints 10 every time. It at least seems like the const reference rule is in effect for the int version, but not for the class version. Are they both simply UB due to the use of the heap? Am I just lucky with the int version because the compile saw through all consts and just directly printed out a 10? Which aspect of the rule am I missing?
It simply demonstrates that analyzing language behavior by "trying it in the compiler" doesn't normally produce any useful results. Both of your examples are invalid for the very same reason. The lifetime of the temporary is only extended when you use that temporary as the direct initializer for a const reference - only that will establish a "lifetime" link between the reference and the temporary. Trying to pass a temporary as a constructor's argument and attaching a const reference inside the constructor will not establish the aforementioned link and will not extend the lifetime of the temporary. Also, in accordance with C++ standard, if you do this struct S { const int &r; S() : r(5) { cout << r; // OK } }; the lifetime of the temporary is only extended to the end of the constructor. Once the constructor is finished, the temporary dies, meaning that this S s; cout << s.r; // Invalid is invalid. Your experiment with int simply "appears to work", purely by accident.
3,097,868
3,097,892
Where to place file in order to read?
Hey, where do I place a text file that I'm trying to read using fstream? In this tutorial, http://www.gamedev.net/reference/articles/article1127.asp, they say ifstream fin("input.txt"); where would "input.txt" be located? Before I tried directing a path to the file by doing this "C:\Users\XXXXXXX\Documents\test.in". This however does not seem to work, Incorrect data input with fstream. I'm using CodeBlocks. Thanks in advance.
input.txt should be in the working directory. Usually the working directory is the directory containing the executable. In the case of Visual Studio, the working directory when run in the debugger can be set in the Debug options.
3,097,882
3,098,089
find most often seen string from a log file
I want to find most often seen string in a huge log file. Can someone help me how to do this. one way to do this is to hash each and every string and count the maximum value but its not efficient. Are there any better ways to do this. Thanks & Regards, Mousey.
If performance is critical you may want to look at a trie or a Radix tree. If you're just interested to know if one of the strings appears more than 50% of the times (let's call that string the majority string) you can do something like this (see if I can get this right): get the first string and assume it's the majority string and set it's occurrence count to 1; get the next string if it's the same as the current majority candidate increment it's occurrence count otherwise decrement the occurrence count if the occurrence count reaches 0 replace the majority candidate with the current string repeat from 2 as long as you have strings to read if at the end the occurrence count is greater than 0 rescan the log and count the actual number of occurrences of the candidate to check if it really is the majority string. So you'll have to go through the log twice. Note: This is from a problem used in an ACM programming contest a while ago, available here.
3,097,949
3,098,338
How can I determine the statistical randomness of a binary string?
How can I determine the statistical randomness of a binary string? Ergo, how can I code my own test, and return a single value that corresponds to the statistical randomness, a value between 0 and 1.0 (0 being not random, 1.0 being random)? The test would need to work on binary strings of any size. When you do it with pen and paper, you might explore strings like this:   0 (arbitrary randomness, the only other choice is 1)   00 (not random, its a repeat and matches the size)   01 (better, two different values)   010 (less random, palindrome)   011 (less random, more 1's, still acceptable)   0101 (less random, pattern)   0100 (better, less ones, but any other distribution causes patterns) Case examples: Size: 1, Possibilities: 2   0: 1.0 (random)   1: 1.0 (random) Size: 2, P:4   00: ?   01: 1.0 (random)   10: 1.0 (random)   11: ? S:3, P:8   000: ? non-random   001: 1.0 (random)   010: ? less random   011: 1.0 (random)   100: 1.0 (random)   101: ? less random   110 1.0 (random)   111: ? non-random And so on. I feel that this may play a lot into breaking the string into all possible substrings and comparing frequencies, but it seems like this sort of groundwork should already have been done in the early days of computer science.
This will give you an entropy count from 0 to 1.0: You might want to try looking into the Shannon Entropy, which is a measure of entropy as applied to data and information. In fact, it is actually almost a direct analogue of Physical formula for entropy as defined by the most accepted interpretations of Thermodynamics. More specifically, in your case, with a binary string, you can see the Binary Entropy Function, which is a special case involving randomness in binary bits of data. This is calculated by H(p) = -p*log(p) - (1-p)*log(1-p) (logarithms in base 2; assume 0*log(0) is 0) Where p is your percentage of 1's (or of 0's; the graph is symmetrical, so your answer is the same either way) Here is what the function yields: As you can see, if p is 0.5 (same amount of 1's as 0's), your entropy is at the maximum (1.0). If p is 0 or 1.0, the entropy is 0. This appears to be just what you want, right? The only exception is your Size 1 cases, which could just be put as an exception. However, 100% 0's and 100% 1's don't seem too entropic to me. But implement them as you'd like. Also, this does not take into account any "ordering" of the bits. Only the sum total of them. So, repetition/palindromes won't get any boost. You might want to add an extra heuristic for this. Here are your other case examples: 00: -0*log(0) - (1-0)*log(1-0) = 0.0 01: -0.5*log(0.5) - (1-0.5)*log(1-0.5) = 1.0 010: -(1/3)*log(1/3) - (2/3)*log(2/3) = 0.92 0100: -0.25*log(0.25) - (1-0.25)*log(1-0.25) = 0.81
3,098,010
3,098,036
Cannot find default constructor
My error occurs on line 191 and 156. For some reason it is saying it cant find the default constructor when I have supplied the right amount of parameters. The error it is giving me is "Cannot find default constructor to initialize base class" code: http://pastebin.com/WLMvBMyy If anyone could offer any input it would be greatly appreciated
HField(int row, int column, int length, const char *s = NULL, void (*h)(void*) = NULL) { SField(row, column, length, s); ptrFunc = h; } This is not how you call base class constructors. The syntax you are looking for is: HField(int row, int column, int length, const char *s = NULL, void (*h)(void*) = NULL) : SField(row, column, length, s) { ptrFunc = h; }
3,098,085
3,098,124
Efficient method of passing callback member function
I'm designing a method for an input handler class. Here is some pseudo code... void InputHandler::ScanEvents( boost::function1< void, std::string& > &func ) { // Scan keys, determining string to pass // If string found, call func with string as its argument on object tied to func } I'm not exactly sure how to implement this, or if it is even possible, since the whole point of a function is to separate it from its caller. The idea is that an object has a private member function and a boost::function member that holds it. Whenever it calls ScanEvents on its InputHandler, it passes that function, so the ScanEvents can "activate it" whenever an appropriate event is found. Efficiency is a concern, as this is in a domain where performance is important, and this function is called frequently. P.S. I swear I remember reading an example like this in one of Scott Meyer's books, but I can't find it for the life of me. Maybe it was in Modern C++ Design...looking....
Something along the lines of class Thingy { public: Thingy() : callback(bind(&Thingy::Callback, this, _1)) {} void DoStuff() { handler.ScanEvents(callback); } private: InputHandler handler; function<void(string)> callback; void Callback(string s) { cout << "Called with " << s << endl; } }; ought to do what you describe. But it would probably be more efficient for the callback to take the string by reference.
3,098,209
3,098,215
How to find the no of elements in an string array (the string is passed to a function)
#include<iostream> #include<string> using namespace std; class Prerequisites { public: void orderClasses(string* Input); }; void Prerequisites::orderClasses(string* Input) { // Need to find the length of the array Input } int main() { Prerequisites A; string classes[]={"CSE121: CSE110", "CSE110:", "MATH122:" }; A.orderClasses(classes); } I need to find the length of the array classes[] in the methos orderClasses. I cannot alter the signature of the method orderClasses ! That is a requirement.
You should pass the number of elements in the array to orderClasses(). Since that is not an option, consider some alternatives: Add another member function to Prerequisites to inform it how large the array will be when you do call orderClasses(). Use a sentinel value for the last string in the array so that when you see that value in the function, you know you have reached the end. Make the first string in the array a string containing the number of elements in the array. None of these are good solutions to the problem: the best option while still using an array, of course, is just to pass the array size to the function. In most scenarios, it would be even better not to use an array at all and just pass a std::vector<std::string> containing the strings.
3,098,281
3,098,334
Can someone help clarify how header files work?
I've been working with C++ for a good couple of weeks now, but the mechanism behind header files (or the linker I suppose?) confuses the heck out of me. I've gotten in the habit of creating a "main.h" to group my other header files and keep the main.cpp tidy, but sometimes those header files complain about not being able to find a different header file (even though it's declared in the "main.h"). I'm probably not explaining it very well so here's an abridged version of what I'm trying to do: //main.cpp #include "main.h" int main() { return 0; } - //main.h #include "player.h" #include "health.h" #include "custvector.h" - //player.h #include "main.h" class Player { private: Vector playerPos; public: Health playerHealth; }; - //custvector.h struct Vector { int X; int Y; int Z; }; - //health.h class Health { private: int curHealth; int maxHealth; public: int getHealth() const; void setHealth(int inH); void modHealth(int inHM); }; I won't include health.cpp because it's a bit lengthy (but does work), it does have #include "health.h". Anyways, the compiler (Code::Blocks) complains that "player.h" can't find the types 'Health' or 'Vector'. I thought that if I used #include "main.h" into "player.h" it would be able to find the definitions for Health and Vector sense they're included in "main.h". I figured they would they would sort of tunnel their way though (player.h -> main.h -> health.h). But that didn't work too well. Is there some kind of a diagram or video that could clarify how this should be set up? Google wasn't much help (nor my book).
The other answers here have effectively explained the way header files and the preprocessor work. The biggest problem you have is the circular dependencies, which from experience, I know can be a royal pain. Also, when that starts happening, the compiler starts to behave in very odd ways and throw error messages that aren't super helpful. The method I was taught by a C++ guru in college was to start each file (a header file for instance) with //very beginning of the file #ifndef HEADER_FILE_H //use a name that is unique though!! #define HEADER_FILE_H ... //code goes here ... #endif //very end of the file This uses preprocessor directives to automatically prevent circular dependencies. Basically, I always use an all uppercase version of the file name. custom-vector.h becomes #ifndef CUSTOM_VECTOR_H #define CUSTOM_VECTOR_H This allows you to include files willie-nillie without creating circular dependencies because if a file is included multiple times, its preprocessor variable is already defined, so the preprocessor skips the file. It also makes it easier later on to work with the code because you don't have to sift through your old header files to make sure you haven't already included something. I'll repeat again though, make sure the variable names you use in your #define statements are unique for you otherwise you could run into problems where something doesn't get included properly ;-). Good luck!
3,098,347
3,098,369
Nested type as function argument
I have the following template class: template<class T> class C { typedef C_traits<T> traits; typedef typename traits::some_type type; //... // use 'traits' and 'type' a lot //... }; where C_traits is a template struct that has a typedef for some_type that is different for each specialization of the type X. I am trying to write a function that receives a reference to a variable of type as defined above, i.e.: template<class T> //void f(const C_traits<T>::some_type& c) <-- this does not work either void f(const C<T>::type& c) { //... } I'm getting an "expected unqualified-id before '&' token" error on the line where f is defined. I think I understand why I am getting this error, but I'd like to know if there is any way to accomplish what I'm trying to do here. Put another way, I'd like to do something like this: template<class T> void f(typename const C<T>::type& c) { //... } which is not allowed. Any thoughs?
template <typename T> void f(const typename C<T>::type& c) { } This is allowed, but a qualified type is one of the non-deduced contexts. That is, template argument deduction won't work for this, so you'll have to call the function like so: f(42); // won't work f<int>(42); // works If you don't want to supply the type argument explicitly, one option is to have the function just take a T: template <typename T> void f(const typename T& c) { }
3,098,607
3,098,653
Type of UTF-16 encoding, using wofstream in Windows
Recently, I want to write a text file in unicode (UTF-16) under Windows. By refering to http://www.codeproject.com/KB/stl/upgradingstlappstounicode.aspx, here is the code I am applying. When I use Notepad to open up the document, here is the display. Newline seems disappear!!! (source: google.com) When I use Firefox with UTF-16 encoding selected, here is the display. (source: google.com) I try to open under JEdit, using the following encoding UTF-16 - Nope. Rubbish display. UTF-16BE - Nope. Rubbish display. UTF-16LE - Fine. Able to show multiple lines. My guess is that, I need to provide additional byte ordering information? But how? My objective is to get this UTF-16 document able to display well under Notepad, as my customer just love to use Notepad. P/S PLEASE! Don't ever suggest me using UTF-8. Thank you. #include <iostream> #include <fstream> #include <iomanip> #include <locale> #include <windows.h> #include <tchar.h> // For StringCchLengthW. #include <Strsafe.h> #include <cassert> using namespace std; // appearing in the NullCodecvtBase typedef. using std::codecvt ; typedef codecvt < wchar_t , char , mbstate_t > NullCodecvtBase ; class NullCodecvt : public NullCodecvtBase { public: typedef wchar_t _E ; typedef char _To ; typedef mbstate_t _St ; explicit NullCodecvt( size_t _R=0 ) : NullCodecvtBase(_R) { } protected: virtual result do_in( _St& _State , const _To* _F1 , const _To* _L1 , const _To*& _Mid1 , _E* F2 , _E* _L2 , _E*& _Mid2 ) const { return noconv ; } virtual result do_out( _St& _State , const _E* _F1 , const _E* _L1 , const _E*& _Mid1 , _To* F2, _E* _L2 , _To*& _Mid2 ) const { return noconv ; } virtual result do_unshift( _St& _State , _To* _F2 , _To* _L2 , _To*& _Mid2 ) const { return noconv ; } virtual int do_length( _St& _State , const _To* _F1 , const _To* _L1 , size_t _N2 ) const _THROW0() { return (_N2 < (size_t)(_L1 - _F1)) ? _N2 : _L1 - _F1 ; } virtual bool do_always_noconv() const _THROW0() { return true ; } virtual int do_max_length() const _THROW0() { return 2 ; } virtual int do_encoding() const _THROW0() { return 2 ; } } ; #define IMBUE_NULL_CODECVT( outputFile ) \ { \ (outputFile).imbue( std::locale(locale::classic(), new NullCodecvt )) ; \ } int main() { std::wofstream file; IMBUE_NULL_CODECVT( file ) ; file.open(L"C:\\可以爱我吗.TXT", ios::out | ios::binary); file << L"ABC" << std::endl; file << L"我爱你" << std::endl; file << L"Bye bye" << std::endl; printf("done\n"); getchar(); }
When you do ios::binary, the file is opened in binary mode which means newlines aren't converted to the correct \r\n encoding on Windows. If you write "\r\n" instead of std::endl, it should work in Notepad. I'm not sure if this is the best solution.
3,098,718
22,864,560
Installing C++ Armadillo library on Mac OS X
I am trying to use the C++ armadillo library (armadillo-0.9.10) on a Mac Pro. I follow the manual installation instruction in the README.txt file. I have modified the config.hpp file to indicate that I have LAPACK and BLAS installed. I then try to compile the examples. I successfully compile and run example1.cpp, but when I try to run example2.cpp it reports that I need to have ATLAS or LAPACK installed. I added the #include header to example2.cpp and use the -framework Accelerate flag to compile in the makefile. However, it is still not working. What gives? I should have LAPACK and BLAS installed by default with Xcode, no? Any help here would be wonderful. Thank you, thank you!
I am not sure if You are still trying to figure this out or now but to answer your original question, you can easily download and setup Armadillo from the website: http://arma.sourceforge.net/download.html I would rather use home brew instead: brew install armadillo
3,098,753
3,098,776
Sometimes my windows handle is good, sometimes it bad
I am confused. Sometimes when I initiate my window, the Handle returned is good. and sometimes its not. Here is my code void GXRenderManager::InitWindows() { WNDCLASSEX wndcex; wndcex.cbSize = sizeof(WNDCLASSEX); wndcex.style = CS_HREDRAW | CS_VREDRAW; wndcex.lpfnWndProc = GXRenderManager::WndProc; wndcex.cbClsExtra = 0; wndcex.cbWndExtra = 0; wndcex.hInstance = *GXRenderManager::hinstance; wndcex.hIcon = LoadIcon(NULL,IDI_APPLICATION); wndcex.hCursor = LoadCursor(NULL,IDC_ARROW); wndcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wndcex.lpszMenuName = NULL; wndcex.lpszClassName = L"GXRenderClass"; wndcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION); if(!RegisterClassEx(&wndcex)) throw GXWindowsException(L"Failed To Register Window"); //EDIT AREA: This is a static size for window. Needs to be changed for dynamic size RECT rectangle = {0,0,GXRenderManager::width,GXRenderManager::height}; AdjustWindowRect(&rectangle, WS_OVERLAPPEDWINDOW, FALSE); HWND tempWin; tempWin = CreateWindowEx(WS_EX_CLIENTEDGE,L"GXRenderClass",L"GXRender Engine", WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,CW_USEDEFAULT, (rectangle.right - rectangle.left), (rectangle.bottom - rectangle.top), NULL, NULL,*GXRenderManager::hinstance, NULL); if(!tempWin) GXWindowsException(L"GX had an issue creating a window."); GXRenderManager::mainWindow = &tempWin; ShowWindow(*GXRenderManager::mainWindow, *GXRenderManager::nCmdShow); } Sometimes GXRenderManager::mainWindow returns a number, but most of the time it returns a "expression can not be evaluated. Any takers ?? [edit] the header #ifndef GXRM #define GXRM #include <windows.h> #include "DeviceEnum.h" #include "GXRenderDevice.h" #include "GXExceptions.h" class GXRenderManager { public: static int Ignite(HINSTANCE*, int*, GXDEVICE , int w = 800, int h = 600); static GXRenderer* Device(); static void InitWindows(); static LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); static int Run(); private: bool running; static GXRenderer *renderDevice; protected: static HINSTANCE * hinstance; static int *nCmdShow; static HWND mainWindow; static int width; static int height; }; #endif .cpp GXRenderManager::mainWindow is a static member . Prior to the responses below. I updated the code to the following... void GXRenderManager::InitWindows() { WNDCLASSEX wndcex; wndcex.cbSize = sizeof(WNDCLASSEX); wndcex.style = CS_HREDRAW | CS_VREDRAW; wndcex.lpfnWndProc = GXRenderManager::WndProc; wndcex.cbClsExtra = 0; wndcex.cbWndExtra = 0; wndcex.hInstance = *GXRenderManager::hinstance; wndcex.hIcon = LoadIcon(NULL,IDI_APPLICATION); wndcex.hCursor = LoadCursor(NULL,IDC_ARROW); wndcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wndcex.lpszMenuName = NULL; wndcex.lpszClassName = L"GXRenderClass"; wndcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION); if(!RegisterClassEx(&wndcex)) throw GXWindowsException(L"Failed To Register Window"); //EDIT AREA: This is a static size for window. Needs to be changed for dynamic size RECT rectangle = {0,0,GXRenderManager::width,GXRenderManager::height}; AdjustWindowRect(&rectangle, WS_OVERLAPPEDWINDOW, FALSE); HWND tempWin; tempWin = CreateWindowEx(WS_EX_CLIENTEDGE,L"GXRenderClass",L"GXRender Engine", WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,CW_USEDEFAULT, (rectangle.right - rectangle.left), (rectangle.bottom - rectangle.top), NULL, NULL,*GXRenderManager::hinstance, NULL); if(!tempWin) GXWindowsException(L"GX had an issue creating a window."); GXRenderManager::mainWindow = tempWin; ShowWindow(GXRenderManager::mainWindow, *GXRenderManager::nCmdShow); } Still I see the same issue.
You are saving a pointer to a local variable (tempWin) and expecting that will be valid after you return from the InitWindows() function. Instead of making GXRenderManager::mainWindow a pointer, declare it as an actual data member. So: class GXRenderManager { ... HWND mainWindow; // not a pointer ... }; GXRenderManager::mainWindow = tempWin; ShowWindow(GXRenderManager::mainWindow, *GXRenderManager::nCmdShow); I suspect you might have a similar problem with nCmdShow, but you haven't shown enough of your code to tell.
3,098,767
3,223,783
Creating a menu strip with WinAPI
In .Net there is something called a menu strip. These are more customizable than HMENU's. How could I create one of these in unmanaged C++? Thanks
They aren't more customizable than HMENUs, they're just easier to customize. If you don't want to use MFC C++ WinAPI wrapper, what do you want to customize ?
3,098,940
3,099,235
Calculating both weighted and unweighted statistics with the same boost::accumulator_set?
With Boost's accumulators I can easily calculate statistical quantities for weighted or unweighted input sets. I wonder if it is possible to mix weighted and unweighted quantities inside the same accumulator. Looking at the docs it doesn't seem that way. This compiles fine but produces another result than I would have liked: using namespace boost::accumulators; const double a[] = {1, 1, 1, 1, 1, 2, 2, 2, 2}; const double w[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; accumulator_set<double, features<tag::sum, tag::weighted_sum>, double> stats; for (size_t i=0; i<9; ++i) stats(a[i], weight = w[i]); std::cout << sum(stats) <<" "<< weighted_sum(stats) << std::endl; // outputs "75 75" instead of "13 75" Also, with a third template parameter to accumulator_set I always seems to get weighted quantities, even when using an "unweighted" feature and extractor: accumulator_set<double, features<tag::sum>, double> stats; for (size_t i=0; i<9; ++i) stats(a[i], weight = w[i]); std::cout << sum(stats) << std::endl; // outputs "75" instead of 13 Do I always have to use two different accumulators if I want to calculate both weighted and unweighted quantities? EDIT I just use sum as an example, in reality I am interested in multiple, more complicated quantities.
It does say in the documentation that When you specify a weight, all the accumulators in the set are replaced with their weighted equivalents. There are probably better ways to do it but you can try something like this (basically swapping the meaning of the value with that of the weight): accumulator_set< double, stats< tag::sum, tag::sum_of_weights >, double > acc; const double a[] = {1, 1, 1, 1, 1, 2, 2, 2, 2}; const double w[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; for( int i = 0; i < sizeof( a ) / sizeof( a[ 0 ] ); i++ ) acc( w[ i ], weight = a[ i ] ); std::cout << extract_result< tag::sum >( acc ) << std::endl; // weighted sum, prints 75 std::cout << extract_result< tag::sum_of_weights >( acc ) << std::endl; // sum, prints 13
3,098,983
3,099,032
C++ template specialization of templated types
I'm looking to help users of some of my templated code by using BOOST_STATIC_ASSERT to let them know that they've used an incompatible type with a simpler compile error message than the monster than is currently produced with an incompatible type. The example is a bit too complex to reproduce here, but hopefully this will capture the essence of what I want: My question is how to format that last line, a "template template"? template <typename P1, int P2, typename P3> class InterestingType { } template<typename T> struct is_interesting_type{ static const bool value = false; }; template<template<typename,int,typename> typename InterestingType> //No idea how to format this.. struct is_interesting_type{ static const bool value = true; };
Change the code to template <typename P1, int P2, typename P3> struct is_interesting_type<InterestingType<P1, P2, P3> >{ static const bool value = true; };
3,099,039
3,141,301
How to detect and remove guide lines from a scanned image/document efficiently?
For my project i am writing an image pre processing library for scanned documents. As of now I am stuck with line removal feature. Problem Description: A sample scanned form: Name* : ______________________________ Age* : ______________________________ Email-ID: |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| Note: Following are the further conditions: The scanned document may contain many more vertical and horizontal guiding lines. Thickness of the lines may exceed 1px The document itself is not printed properly and might have noise in the form of ink bloating or uneven thickness The document might have colored background or lines Now what I am trying to do is to detect these lines and remove them. And while doing so the hand written content should not be lost. Solution so for: The current solution is implemented in Java. Detected these lines by using a combination of canny/sobel edge detectors and a threshold filter(to make image bitonal). From the previous action I get a black and white array of pixels. Traverse the array and check whether lumanicity of that pixel falls below a specified bin value. And if I found 30 (minimum line length in pixels) such pixels, I remove them. I repeat the same for vertical lines but considering the fact there will be cuts due to horizontal line removal. Although the solution seems to work. But there are problems like, Removal of overlapping characters If characters in the image are not properly spaced then it is also considered as a line. The output image from edge detection is in black and white. A bit slow. Normally takes around 40 seconds for image of 2480*3508. Kindly guide how to do it properly and efficiently. And if there is an opensource library then please direct. Thanks
First, I want to mention that I know nothing about image processing in general, and about OCR in particular. Still, a very simple heuristic comes to my mind: Separate the pixels in the image to connected components. For each connected component decide if it is a line or not using one or more of the following heuristics: Is it longer that the average letters length? Does it appear near other letters? (To remove ink bloats or artifacts). Does its X gradient and Y gradient large enough? This could make sure that this connected component contains more than just horizontal line. The only problem I can see is, if somebody writes letters on a horizontal line, like so: /\ ___ / \ / \ |__| |___/ -|--|---|---|------------------ | | \__/ In that case the line would remain, but you have to handle this case anyhow. As I mentioned, I'm by no means an image processing expert, but sometimes very simple tricks work.