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
2,276,840
2,388,351
easing c++ to objective-c/cocoa bridging via metaprogramming?
In a pure C++ world we can generate interfacing or glue code between different components or interfaces at compile time, using a combination of template-based compile-time and runtime-techniques (to e.g. mostly automatically marshall to/from calls using legacy types). When having to interface C++ applications with Objective-C/Cocoa for GUI, system integration or IPC though, things become harder due to the less strict typing - yet often not more then a flat repitive interface layer is needed: thin bridging delegates have to be defined or conversion code to language bridging calls has to be written. If you have to deal with interfaces of non-trivial size and want to avoid script-based code generation this quickly becomes cumbersome and is just a pain every time refactorings have to take place. Using a combination of (template) metaprogramming and the Objective-C runtime library, it should be possible to reduce the amount of code considerably... Before i go to reinvent the wheel (and possibly waste time), does anyone know about techniques, best-practices or examples in that direction? As for an example, lets say we need a delegate that supports this informal protocol: - (NSString*)concatString:(NSString*)s1 withString:(NSString*)s2; - (NSNumber*) indexOf:(CustomClass*)obj; Instead of implementing an Obj-C class now that explicitly bridges to a C++-instance, i'd like to do something like this instead: class CppObj { ObjcDelegate m_del; public: CppObj() : m_del(this) { m_del.addHandler <NSString* (NSString*, NSString*)> ("concatString", &CppObj::concat); m_del.addHandler <NSNumber* (CustomClass*)> ("indexOf", &CppObj::indexOf); } std::string concat(const std::string& s1, const std::string& s2) { return s1.append(s2); } size_t indexOf(const ConvertedCustomClass& obj) { return 42; } }; All that should be needed from the user to support additional types would be to specialize a conversion template function: template<class To, class From> To convert(const From&); template<> NSString* convert<NSString*, std::string>(const std::string& s) { // ... } // ... The example above of course does ignore support for formal protocols etc. but should get the point across. Also, due to the type-information for Objc-runtime-types being mostly decayed into some-native-types or class-type i don't think the explicit specification of parameter and return types for the delegate-methods can be avoided.
I didn't find anything satisfactory and came up with a prototype that, given the following informal protocol: - (NSString*)concatString:(NSString*)s1 withString:(NSString*)s2; and this C++ code: struct CppClass { std::string concatStrings(const std::string& s1, const std::string& s2) const { return s1+s2; } }; std::string concatStrings(const std::string& s1, const std::string& s2) { return s1+s2; } allows creating and passing a delegate: CppClass cpp; og::ObjcClass objc("MyGlueClass"); objc.add_handler<NSString* (NSString*, NSString*)> ("concatString:withString:", &cpp, &CppClass::concatStrings); // or using a free function: objc.add_handler<NSString* (NSString*, NSString*)> ("concatString:withString:", &concatStrings); [someInstance setDelegate:objc.get_instance()]; which can then be used: NSString* result = [delegate concatString:@"abc" withString:@"def"]; assert([result compare:@"abcdef"] == NSOrderedSame); Boost.Function objects can also be passed, which means Boost.Bind can easily be used as well. While the basic idea works, this is still a prototype. I did a short blog post on the subject and the prototype source is available via bitbucket. Constructive input and ideas welcome.
2,276,901
2,277,010
Fully specialised templates and dllexport
Microsoft says: “Templates cannot be used with functions declared with __declspec (dllimport) or __declspec (dllexport).” (link). What does this mean? Can I export a function which has a fully specialized template class reference as an argument?
That isn't a dllexport/dllimport-specific problem, its a general issue with templates - only one compiler currently implements the means to export templates, see Comeaus template FAQ for details. Fully specialized templates however are distinct and concrete types and basically usable with the __declspec extension, but there are limitations besides the entry you linked. Personally i'd mainly avoid templates in the interface here and only use them internally - i don't see the what big benefits the time invested in working around the limitations give you.
2,277,015
2,277,177
Writing a C++ version of the algebra game 24
I am trying to write a C++ program that works like the game 24. For those who don't know how it is played, basically you try to find any way that 4 numbers can total 24 through the four algebraic operators of +, -, /, *, and parenthesis. As an example, say someone inputs 2,3,1,5 ((2+3)*5) - 1 = 24 It was relatively simple to code the function to determine if three numbers can make 24 because of the limited number of positions for parenthesis, but I can not figure how code it efficiently when four variables are entered. I have some permutations working now but I still cannot enumerate all cases because I don't know how to code for the cases where the operations are the same. Also, what is the easiest way to calculate the RPN? I came across many pages such as this one: http://www.dreamincode.net/forums/index.php?showtopic=15406 but as a beginner, I am not sure how to implement it. #include <iostream> #include <vector> #include <algorithm> using namespace std; bool MakeSum(int num1, int num2, int num3, int num4) { vector<int> vi; vi.push_back(num1); vi.push_back(num2); vi.push_back(num3); vi.push_back(num4); sort(vi.begin(),vi.end()); char a1 = '+'; char a2 = '-'; char a3 = '*'; char a4 = '/'; vector<char> va; va.push_back(a1); va.push_back(a2); va.push_back(a3); va.push_back(a4); sort(va.begin(),va.end()); while(next_permutation(vi.begin(),vi.end())) { while(next_permutation(va.begin(),va.end())) { cout<<vi[0]<<vi[1]<<vi[2]<<vi[3]<< va[0]<<va[1]<<va[2]<<endl; cout<<vi[0]<<vi[1]<<vi[2]<<va[0]<< vi[3]<<va[1]<<va[2]<<endl; cout<<vi[0]<<vi[1]<<vi[2]<<va[0]<< va[1]<<vi[3]<<va[2]<<endl; cout<<vi[0]<<vi[1]<<va[0]<<vi[2]<< vi[3]<<va[1]<<va[2]<<endl; cout<<vi[0]<<vi[1]<<va[0]<<vi[2]<< va[1]<<vi[3]<<va[2]<<endl; } } return 0; } int main() { MakeSum(5,7,2,1); return 0; }
So, the simple way is to permute through all possible combinations. This is slightly tricky, the order of the numbers can be important, and certainly the order of operations is. One observation is that you are trying to generate all possible expression trees with certain properties. One property is that the tree will always have exactly 4 leaves. This means the tree will also always have exactly 3 internal nodes. There are only 3 possible shapes for such a tree: A / \ N A / \ (and the mirror image) N A / \ N N A / \ N A / \ A N (and the mirror image) / \ N N A /` `\ A A / \ / \ N N N N In each spot for A you can have any one of the 4 operations. In each spot for N you can have any one of the numbers. But each number can only appear for one N. Coding this as a brute force search shouldn't be too hard, and I think that after you have things done this way it will become easier to think about optimizations. For example, + and * are commutative. This means that mirrors that flip the left and right children of those operations will have no effect. It might be possible to cut down searching through all such flips. Someone else mentioned RPN notation. The trees directly map to this. Here is a list of all possible trees in RPN: N N N N A A A N N N A N A A N N N A A N A N N A N N A A N N A N A N A That's 4*3*2 = 24 possibilities for numbers, 4*4*4 = 64 possibilities for operations, 24 * 64 * 5 = 7680 total possibilities for a given set of 4 numbers. Easily countable and can be evaluated in a tiny fraction of a second on a modern system. Heck, even in basic on my old Atari 8 bit I bet this problem would only take minutes for a given group of 4 numbers.
2,277,018
2,277,729
Wrapping a pure virtual method with arguments using Boost::Python
I'm currently trying to expose a c++ Interface (pure virtual class) to Python using Boost::Python. The c++ interface is: Agent.hpp #include "Tab.hpp" class Agent { virtual void start(const Tab& t) = 0; virtual void stop() = 0; }; And, by reading the "official" tutorial, I managed to write and build the next Python wrapper: Agent.cpp #include <boost/python.hpp> #include <Tabl.hpp> #include <Agent.hpp> using namespace boost::python; struct AgentWrapper: Agent, wrapper<Agent> { public: void start(const Tab& t) { this->get_override("start")(); } void stop() { this->get_override("stop")(); } }; BOOST_PYTHON_MODULE(PythonWrapper) { class_<AgentWrapper, boost::noncopyable>("Agent") .def("start", pure_virtual(&Agent::start) ) .def("stop", pure_virtual(&Agent::stop) ) ; } Note that I have no problems while building it. What concerns me, though, is that as you can see AgentWrapper::start doesn't seem to pass any argument to Agent::start in: void start(const Tab& t) { this->get_override("start")(); } How will the python wrapper know "start" recieves one argument? How can i do so?
The get_override functions returns an an object of type override which has a number of overloads for differing number of arguments. So you should be able to just do this: void start(const Tab& t) { this->get_override("start")(t); } Did you try this?
2,277,154
2,277,174
debugging loop c++ undefined variable, what type? Hoglund
I have been reading one of the Hoglund titles and I though, reading great, but can I make it work? Why do they provide non-working examples in books? #include "stdafx.h" #include <cstdio> #include <windows.h> #include <winbase.h> #include <tlhelp32.h> int _tmain(int argc, _TCHAR* argv[]) { HANDLE hProcess; DEBUG_EVENT dbg_evt; int aPID; if(argc != 2) { printf("wrong number of params\nusage %s<pid>\n", argv[0]); return 0; } //load the ptr to fDebugSetProcessKillOnExit fDebugSetProcessKillOnExit = (DEBUGSETPROCESSKILLONEXIT) GetProcAddress(GetModuleHandle("kernel32.dll"), "DebugSetProcessKillOnExit"); if(!fDebugSetProcessKillOnExit) { printf("[!] failed to get fDebugSetProcessKillOnExit function!\n"); } aPID = atoi(argv[1]); } I am getting two error messages: fDebugSetProcessKillOnExit is an undeclared identifier What type should it be? "Error 4 error C2664: 'GetModuleHandleW' : cannot convert parameter 1 from 'const char [13]' to 'LPCWSTR' What type should the fDebug... be? Why doesn't the aPid = atoi... line work? Should the project be compiled in C instead of C++, as this is exactly as it is in the book? Thanks, R.
Taking this from MSDN: BOOL WINAPI DebugSetProcessKillOnExit(__in BOOL KillOnExit); you can declare the function pointer as: BOOL (*fDebugSetProcessKillOnExit)(BOOL) = /* ... */; or ease your eyes by using typedef: typedef BOOL (*DebugKillPtr)(BOOL); DebugKillPtr fDebugSetProcessKillOnExit = /* ... */; Function pointers can be somewhat confusing, InformITs guide on them should help with that. Additionally, you are using a Unicode build. You can either use GetModuleHandle(L"Kernel32.dll") or _T() etc. or set your project to use the multi-byte-character-set (project properties -> configuration -> general -> character set). The unicode-character-set is also the reason why the atoi() statement can't work: argv is an array of _TCHAR*s, and _TCHAR is wchar_t for unicode-builds. atoi() however expects a const char* argument and you are handing it a wchar_t*. So you can either again use a multi-byte-character set, convert the string or use Microsofts _wtoi()/_ttoi(). To ease switching between character sets and stick with the style of the book, prefer the _T* and _t* versions.
2,277,224
2,277,270
C++ figure out CPU/Memory usage
I have a C++ app called ./blah (to which I have the source code) when I run ./blah I can run "top" and see how much memory & cpu "./blah" is using. Now, is there anyway for "./blah" to access that information itself? I.e. when I run ./blah, I want it to every second dump out it's CPU & Memory usage. What library should I be using to do this? I'm on MacOSX; but I'd prefer a solution that works on Linux too. Thanks!
You want getrusage(). From the man page: int getrusage(int who, struct rusage *r_usage); getrusage() returns information describing the resources utilized by the current process, or all its terminated child processes. The who parameter is either RUSAGE_SELF or RUSAGE_CHILDREN. The buffer to which r_usage points will be filled in with the following structure: struct rusage { struct timeval ru_utime; /* user time used */ struct timeval ru_stime; /* system time used */ long ru_maxrss; /* integral max resident set size */ long ru_ixrss; /* integral shared text memory size */ long ru_idrss; /* integral unshared data size */ long ru_isrss; /* integral unshared stack size */ long ru_minflt; /* page reclaims */ long ru_majflt; /* page faults */ long ru_nswap; /* swaps */ long ru_inblock; /* block input operations */ long ru_oublock; /* block output operations */ long ru_msgsnd; /* messages sent */ long ru_msgrcv; /* messages received */ long ru_nsignals; /* signals received */ long ru_nvcsw; /* voluntary context switches */ long ru_nivcsw; /* involuntary context switches */ };
2,277,252
2,279,672
How do I install hardware driver using C++ on Win32?
How do I install a hardware driver (inf file) using C++? Platform : Win32
The process is usually called pre-installation. (The normal install process is triggered by the arrival of an hardware device.) The relevant functions can be found in <DIFxAPI.h> from the DDK. You probably want to call DriverPackageInstall(). The expected return value is ERROR_NO_SUCH_DEVINST [sic] as there won't be such a device yet. There's some 64 bit funkyness: you can't install a 64 bits driver from a Win32 app (at least not in XP/Vista/Windows7/2003/2008). Hence, your Win32 installer must check if DriverPackageInstall() returns ERROR_IN_WOW64 and then call CreateProcess to start your 64 bits installer.
2,277,385
2,277,477
Why can I not define a member function in a class if that function is to be linked from another translation unit?
I am a bit of a newbie in C++, but I just stumbled on the following. If I have these files: myclass.hpp: class myclass { public: myclass(); void barf(); }; mymain.cpp: #include "myclass.hpp" int main() { myclass m; m.barf(); return 0; } And I use this implementation of myclass: myclassA.cpp: #include <iostream> using namespace std; class myclass { // or include myclass.hpp, it both works fine public: myclass(); void barf(); }; myclass::myclass() { } //empty void myclass::barf() { cout << "barfing\n"; } then everything is OK. But if I use this implementation of myclass, which is exactly the same except the members are defined inside the class definition, I get a linking error: myclassB.cpp: #include <iostream> using namespace std; class myclass { public: myclass() { } void barf() { cout << "barfing\n"; } }; The error I get: $ g++ myclassB.cpp mymain.cpp /tmp/cc4DTnDl.o: In function `main': mymain.cpp:(.text+0xd): undefined reference to `myclass::myclass()' mymain.cpp:(.text+0x16): undefined reference to `myclass::barf()' collect2: ld returned 1 exit status Apparently the object file built from myclassB.cpp doesn't export the member functions. Why aren't both of these implementations behaving te same? Is there some gotcha rule in C++ that says member definitions inside class definitions are not globally visible, but they are if they are defined outside of the class?
standard that says that there must be a unique definition of a class, template, etc., is phrased in a somewhat more complicated and subtle manner. This rule is commonly referred to as ‘‘the one definition rule,’’ the ODR. That is, two definitions of a class, template, or inline function are accepted as examples of the same unique definition if and only if [1] they appear in different translation units, and [2] they are tokenfortoken identical, and [3] the meanings of those tokens are the same in both translation units. For example (valid): // file1.c: struct S { int a ; char b ; }; void f(S* p){ } // file2.c: struct S { int a ; char b ; }; void f(S* p){ } Examples that violate ODR: file1.c: struct S 1 { int a ; char b ; }; struct S 1 { int a ; char b ; }; // error: double definition This is an error because a struct may not be defined twice in a single translation unit. // file1.c: struct S 2 { int a ; char b ; }; // file2.c: struct S 2 { int a ; char b b ; }; // error. This is an error because S2 is used to name classes that differ in a member name. // file1.c: typedef int X ; struct S 3 { X a ; char b ; }; // file2.c: typedef char X ; struct S 3 { X a ; char b ; }; // error. Here the two definitions of S3 are token for token identical, but the example is an error because the meaning of the name X has sneakily been made to differ in the two files.
2,277,497
2,277,538
Struct with the function parameters
Can I suppose that, from the call stack point view, it's the same to call a function like function1 int function1(T1 t1, T2 t2); than to another like function2? struct parameters_t { Wide<T1>::type t1; Wide<T2>::type t2; } int function2(parameters_t p); Where, Wide template wide T to the processor word length. For example, for 32-bit processors: template<typename T, bool b = sizeof(T) >=4 > struct Wide { typedef T type; }; template<typename T> struct Wide<T,false> { typedef unsigned int type; }; I need to do something like this: typedef int (*function_t)(parameters_t); function_t function = (function_t) &function1; parameters_t params; // initialize params function(params); Thanks!
Question 1. No the two function calls aren't necessarily the same -- calling conventions that push parameters right to left and left to right are both in wide use. It sounds like you want to create a function that takes a variable number of a variable type of parameters. To do that, I'd have it take something like an std::vector<boost:any> as its parameter.
2,277,508
2,277,539
Some problem using pointers to enter a string
I'm a beginner and i need to ask a question.. I wrote this small code that accepts a string from the user and prints it..very simple. #include <iostream> using namespace std; int main() { int i; char *p = new char[1]; for(i = 0 ; *(p+i) ; i++) *(p+i) = getchar(); *(p+i) = 0; for(i = 0 ; *(p+i) ; i++) putchar(*(p+i)); return 0; } when i enter any string..like "stack overflow" for example..it will print "sta" and drop the rest of the string. I know it's an easy one to solve but since I've just started i can't understand what's wrong here . Thanks in advance .
There are several problems with this code. First, you have a buffer overflow, because char *p = new char[1] allocates only one character for storage. This is exceeded when i > 0. Next, your first loop will keep going until it reaches a point in unallocated memory (undefined behavior) that has a value of zero. This just happens to be after the third value in your case. You probably wanted something more like *(p+i-1) == 0 to give "the last character read meets some condition." Finally, you're allocating memory with new[] and not properly deallocating it with a matching delete[]. Consider using std::cin and std::string for much safer and correct code: #include <iostream> #include <string> int main(int, char**) { std::string s; std::cout << "Enter a string: "; std::cin >> s; std::cout << s << std::endl; }
2,277,658
2,277,682
Invalid use of incomplete type on g++
I have two classes that depend on each other: class Foo; //forward declaration template <typename T> class Bar { public: Foo* foo_ptr; void DoSomething() { foo_ptr->DoSomething(); } }; class Foo { public: Bar<Foo>* bar_ptr; void DoSomething() { bar_ptr->DoSomething(); } }; When I compile it in g++, it was giving error of "Invalid use of incomplete type", but it was compiled nicely in MSVC 10. Is it possible to solve this problem while keeping the declaration and definition in one header file? (no cpp files) If this is not allowed in the standard, so is this one of the MSVC "bug" or "feature"?
Yes, just move the method definitions out of the class definition: class Foo; //forward declaration template <typename T> class Bar { public: Foo* foo_ptr; void DoSomething(); }; class Foo { public: Bar<Foo>* bar_ptr; void DoSomething() { bar_ptr->DoSomething(); } }; // Don't forget to make the function inline or you'll end up // with multiple definitions template <typename T> inline void Bar<T>::DoSomething() { foo_ptr->DoSomething(); }
2,277,865
2,277,894
Are there any low-level languages that can be used in place of scripts?
I am a "high-level" scripting guy. All my code is Class-based PHP or JavaScript. However, I want to know if there is any form of useful interpreter projects for "low-level" compiled languages like C or C++ (strange sounding huh?). This all came about when I stumbled upon http://g-wan.com/ and was fascinated by the fact that you could setup C code to run as server scripts. However, that project is all but useless because it is run by one guy and is closed source. So, is there anything out there for "low-level" languages that would enable them to be easier to run by compiling them at runtime. OR is this just a bad accident waiting to happen which explains why that was the only project I could find about this? Being able to dump PHP/Ruby/Python for C scripts would really speed up our sites.
I recently stumbled upon something called BinaryPHP in which you code normally in php and then convert the script into C++ to be compiled on your favorite tool. That should be a nice learning curve for someone already in touch with php.
2,277,918
2,277,958
Simple Linked List Implementation in C++
I'm a programming student in my first C++ class, and recently we covered linked lists, and we were given an assignment to implement a simple one. I have coded everything but my pop_back() function, which is supossed to return a pointer to the Node that needs to be deleted in Main(). No Node deletion is to be done in the actual function. So my question is: Would you be willing to help point me in the right direction for my pop_back() function? Also, if you notice anything else that I'm doing wrong, let me know. Also, this linked list is just to work with strings. In this case, a grocery list, so one string for the quantity of the item(1,2), and one string for the item type. (Milk, Eggs, etc.) Below I've included my List & Node class implementations, so you can get an idea of what I've done so far. Node.cpp Node::Node(void) { descrip = " "; quantity = " "; previous = NULL; next = NULL; } Node::Node(string q, string d) { descrip = d; quantity = q; previous = NULL; next = NULL; } Node* Node::GetNext() { return next; } Node* Node::GetPrevious() { return previous; } void Node::SetNext(Node * setter) { next = setter; } void Node::SetPrevious(Node * setter) { previous = setter; } List.cpp List::List(void) { first = NULL; last = NULL; numNodes = 0; } Node* List::GetFirst() { return first; } Node* List::GetLast() { return last; } void List::SetFirst(Node* setter) { first = setter; } void List::SetLast(Node* setter) { last = setter; } int List::GetNumNodes() { return numNodes; } void List::push_front(Node* item) { if (first == NULL) { first = item; last = item; } else { Node* pFirst = first; item->SetNext(pFirst); first = item; numNodes++; } } void List::push_back(Node * item) { if (last == NULL) { first = item; last = item; } else { last->SetNext(item); last = item; numNodes++; } } Node* List::pop_front() { Node* temp = first; first = first->GetNext(); if (first == NULL) { temp = first->GetNext(); first = p; } if (first == NULL) { last = NULL; } if (numNodes > 0) { numNodes--; } return temp; } Node* List::pop_back() // this whole function may be wrong, this is just my attempt at it { Node* temp; temp = first; while((temp->GetNext()) != NULL) // im stuck here }
So if I understand this right you just want to run through your linked list until you get to the last node in the linked list and return the pointer to it? I'm pretty sure what you have there will do it except Node* List::pop_back() // this whole function may be wrong, this is just my attempt at it { Node* temp; temp = first; while(temp->GetNext() != NULL) { temp = temp->GetNext(); } return temp; } So if I read it right, there it will continually loop around until it gets to the node with none in the line behind it, then return it.
2,277,937
2,277,983
Compare shared_ptr with object created on stack
I have a situation where I would like to compare an object encapsulated by a shared_ptr with the same type of object created on a stack. Currently, I'm getting the raw pointer and dereferencing it to do the comparison eg: Object A; std::shared_ptr<Object> B; // assume class Object has its comparison operators overloaded if ( *B.get() < A ) // do stuff here Is there a better way to do this? That is assuming that when both objects meet to be compared with each other, one is a shared_ptr and the other is not.
shared_ptr overloads operator*() so that it acts just like a pointer, so just write: if ( *B < A ) { docs: http://www.boost.org/doc/libs/1_42_0/libs/smart_ptr/shared_ptr.htm#indirection
2,277,986
2,278,072
Can I programatically deduce the calling convention used by a C++ dll?
Imagine you'd like to write a program that tests functions in a c++ dll file. You should enable the user to select a dll (we assume we are talking about c++ dlls). He should be able to obtain a list of all functions exported by the dll. Then, the user should be able to select a function name from the list, manually input a list of arguments ( the arguments are all basic types, like int, double, bool or char arrays (e.g. c-type strings) ) and attempt to run the selected function with the specified arguments. He'd like to know if the function runs with the specified arguments, or do they cause it to crash ( because they don't match the signature for example ). The main problem is that C++, being a strongly typed language, requires you to know the number and type of the arguments for a function call at compile time.And in my case, I simply don't know what these arguments are, until the user selects them at runtime. The only solution I came up with, was to use assembly to manually push the arguments on the call stack. However, I've come to understand that if I want to mess with assembly, I'd better make damn sure that I know which calling convention are the functions in the dll using. So (finally:) here's my question: can I deduce the calling convention programmaticaly? Dependency Walker won't help me, and I've no idea how to manually read PE format.
The answer is maybe. If the functions names are C++ decorated, then you can determine the argument count and types from the name decoration, this is your best case scenario, and fairly likely if MSVC was used to write the code in the first place. If the exported functions are stdcall calling convention (the default for windows api), you can determine the number of bytes to be pushed, but not the types of the arguments. The bad news is that for C calling convention, there isn't any way to tell by looking at the symbol names. You would need to have access to the source code or the debug info. http://en.wikipedia.org/wiki/X86_calling_conventions The name that a function is given as an export is not required to have any relationship with the name that the linker sees, but most of the time, the exported name and the symbol name that the linker sees are the same.
2,278,003
2,278,037
SFML Releasing Resources
I've recently started using SFML and noticed that there aren't any kinds of "FreeResource" methods provided. For example, sf::Font has a function called LoadFromFile, but no functions to release the resource. I thought this was very odd. Am I missing something? Is my only option to create an sf::Font pointer and dynamically allocate and delete it?
sf::Font stores its font data in a std::map called myGlyphs (see the source). When Font's destructor is called, everything in that map will be freed automatically (by the std::map destructor).
2,278,006
2,282,389
Does Lazy C++ (lzz) play nice with Doxygen?
Has anyone tried embedding Doxygen comments within Lazy C++ source files? Any problems? Where do the Doxygen comments go after generating the header/source files?
I went ahead and downloaded Lazy C++ to try it out, and it seems that it does not play nice with Doxygen. My Doxygen comments did not appear at all in the generated header/source files. I then tried making Doxygen parse my lzz file, which had a special #hdr preprocessor command. Doxygen simply ignored that special preprocessor command and the generated documentation seems fine. So the moral of the story is to simply make Doxygen parse the *.lzz files and not the generated *.h / *.cpp files. :-)
2,278,228
2,278,331
OpenCV Image Processing -- C++ vs C vs Python
I was thinking of trying OpenCV for a project and noticed that it had C, C++ and Python. I am trying to figure out whether I should use C++, C or Python -- and would like to use whatever has the best OpenCV support. Just from looking at the index page for the various documentation it looks like the C++ bindings might have more features than the others? Is this true? If C++ has more bindings, it seems that would be a more obvious choice for me, but I was just curious if it really has more features, etc than the others? Thanks!
The Python interface is still being developed whereas the C++ interface (especially with the new Mat class) is quite mature. If you're comfortable in C++, I would highly recommend using it - else, you can start using Python and contribute back any features you think OpenCV needs :)
2,278,274
2,278,290
Is it possible to treat datatypes as an input stream?
int main(int argc, char *argv[]) { Move move; ifstream inf("eof.txt"); inf >> move; return 0; } istream& operator>> (istream &is, Move &move) { is >> move.c; // c = char c[2]; cout << move.c << endl; return is; } eof.txt has lines of 2 chars, so if it had "9r", "9r" would be stored in move's data member (I made it public just for ease). To make sure this works I output the data of move and sure enough it works What I'm trying to do is use this same operator, but instead of getting input from say a file or stdin, I will have a datamember that holds the desired input. Thus in main, if I have a char array with "1d", I need to be able to use the same function (without modifying it) to do the same thing. Is this possible? Any help appreciated.
You can use a stringstream: #include <sstream> int main() { char foo[] = "1d"; std::stringstream ss(foo); Move move; ss >> move; return 0; }
2,278,275
2,278,423
When/why should heapmin be used?
A customer has some memory usage requirements of our application. They note that while our committed memory is reasonable, the reserved memory is high. They suspect this is because the CRT heap grows as we allocate memory, but the CRT isn't returning pages to the OS when the memory is deallocated. We are just using built-in operator new/delete/new[]/delete[] - along with a little usage of malloc/free. They ask, "Does your memory manager call _heapmin at some point to compact the heap?" ummm, we don't explicitly call _heapmin. Should we? Are there any rules of thumb for its use?
As you are using the CRT memory manager there is no need to call it explicitly the OS will manage this.
2,278,291
2,278,312
Linker Errors - Unresolved external symbol
Howdy. I am working on a C++ assignment for my class. I am almost done but can't seem to figure out these errors: error LNK2001: unresolved external symbol "public: virtual void __thiscall HasQuarterState::dispense(void)const " (?dispense@HasQuarterState@@UBEXXZ) gumball.obj Gumball error LNK2001: unresolved external symbol "public: virtual void __thiscall SoldState::turnCrank(void)const " (?turnCrank@SoldState@@UBEXXZ) gumball.obj Gumball fatal error LNK1120: 2 unresolved externals C:\School Work\CS 492\Gumball\Debug\Gumball.exe Gumball I went to MSDN and looked up LNK2001 error, but was provided with an overwhelming amount of info, and am afraid I can't figure out what is wrong given my limited experience with C++ from looking at the MSDN page. But I do believe that the problems come from the way I have structured my program. My teacher said we may use one .cpp file if we wanted too, but I guess in the end I didn't know enough about Visual Studios/C++ to make this work. Ultimately I ran into some other problems that I had to solve that came from using one .cpp file. The code/file in question is here: http://codepad.org/LpBeJT2Y Its a big ole mess but this is what I have done: Declare a class named GumballMachine (no definition) Define a class named State (which in turn has a pointer to a GumballMachine) Defined several other state classes which inherit from State Define class GumballMachine Defined several functions that were excluded from the original definitions of the other state classes. This is because these functions relied on defined functions of GumbballMachine and wouldn't work until the GumballMachine functions were defined. void main() As far as I can tell (with my limited knowledge of VS/C++), the code looks to be fine. Maybe there is something someone with more experience would catch. Any pointers on how to knock out this problem? Thanks for the help.
You've declared dispense in HasQuarterState but have not defined it. The function has no body. Likewise with turnCrank in SoldState.
2,278,370
2,278,417
c++ singleton initialization order
I have class Foo class Bar Now, I want Foo* Foo::singleton = new Foo(); Bar* Bar::singleton = new Bar(); to both initialize before int main() is called. Furthermore, I want Foo::singleton to initialize before Bar::singleton Is there anyway I can ensure that? Thanks!
See also Static variables initialisation order For gcc use init_priority: http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html Works across different translation units. So your code would read: Foo* Foo::singleton __attribute__ ((init_priority (2000))) = new Foo(); Bar* Bar::singleton __attribute__ ((init_priority (3000))) = new Bar(); I don't have gcc handy right now so I can't verify this, but I have used it before. The other simpler and more portable solution is to avoid static initialization, and explicitly create the singletons in order at some well defined place within main. // Nothing in static area void main(void) { // Init singletons in explicit order { Foo* Foo::singleton = new Foo(); Bar* Bar::singleton = new Bar(); } // Start program execution ... } Remember, things will get just as gnarly with singletons on the way out of the program as well, so its often better to make it explicit.
2,278,414
2,278,430
Rotating an image in C/C++
I need code for rotating an image in C++ which functions like imrotate function of matlab. Please suggest a good link. Or if someone can provide the code for imrotate. Or at least please explain the algorithm. Its not a homework. I need this code for my project. And we can use any external library or code.
OpenCV2.0 has several computer vision and image processing tools. Specifically warpAffine (by defining the rotation matrix) will solve your problem with rotating an image. The 2x3 transformation matrix mentioned in the documentation is as follows: where θ is the angle of rotation and tx and ty is the translation along the x and y axes respectively. You can get the source code here. Also, OpenCV2.0 has many MATLAB-esque functions like imread, etc.
2,278,490
2,278,510
Can somebody explain this C++ typedef?
I've just started working with C++ after not having worked with it for quite a while. While most of it makes sense, there are some bits that I'm finding a bit confuddling. For example, could somebody please explain what this line does: typedef bool (OptionManager::* OptionHandler)(const ABString& value);
It defines the type OptionHandler to be a pointer to a member function of the class OptionManager, and where this member function takes a parameter of type const ABString& and returns bool.
2,278,635
2,278,807
Using STL algorithms (specifically std::sort) from within a templated class
I've declared a template class MyContainer as bellow, then created an instance of it of type DataType1. The DataType1 class provides a friend function "DataSpecificComparison" which is used by std::sort to compare DataType1 objects. The program compiled and sorted correctly. I then defined a class called DataType2, gave it a friend implementation of "DataSpecificComparison" and used it to create another instance of MyContainer. I am now unable to compile the program as a "C2914: 'std::sort' : cannot deduce template argument as function argument is ambiguous" compile time error is reported. How can a developer specify that the DataSpecificComparison binary predicate is to take arguments of template type T*? Or is there another way around this issue? template <class T> class MyContainer { private: vector<T*> m_vMyContainerObjects; .... public: .... void SortMyContainerObjects() { std::sort(m_vMyContainerObjects.begin(), m_vMyContainerObjects.end(), DataSpecificComparison) } } class DataType1 { .... friend bool DataSpecificComparison(const DataType1 * lhs, const DataType1 * rhs) } class DataType2 { .... friend bool DataSpecificComparison(const DataType2* lhs, const DataType2* rhs) }
You can use a temporary local function pointer variable of the required type to select the correct overload of DataSpecificComparison: void SortMyContainerObjects() { typedef bool (*comparer_t)(const T*, const T*); comparer_t cmp = &DataSpecificComparison; std::sort(m_vMyContainerObjects.begin(), m_vMyContainerObjects.end(), cmp); } Here the compiler can deduce that you want to use the DataSpecificComparison overload that matches the comparer_t type, which resolves the ambiguity.
2,278,710
2,281,370
terminate called after thowing an instance of '__gnu_cxx::recursive_init'
I've googled for the error above; no use. This error comes form the following line of code: void Thread::join(void** status) { pthread_join(thread, status); } Anyone has any idea what it means? (Google brings up other ppl complainig about the error, but no explaingion of it).
Ref http://www.opensource.apple.com/source/libstdcxx/libstdcxx-5.1/libstdcxx/libstdc++-v3/libsupc++/guard.cc: namespace __gnu_cxx { // 6.7[stmt.dcl]/4: If control re-enters the declaration (recursively) // while the object is being initialized, the behavior is undefined. // Since we already have a library function to handle locking, we might // as well check for this situation and throw an exception. // We use the second byte of the guard variable to remember that we're // in the middle of an initialization. class recursive_init: public std::exception .... static int acquire_1 (__guard *g) { if (_GLIBCXX_GUARD_TEST (g)) return 0; if (recursion_push (g)) { #ifdef __EXCEPTIONS throw __gnu_cxx::recursive_init(); ... Please check if there is some static variables that need themselves to be initialized first.
2,278,732
2,278,755
Unsticky a cout modifier?
cout << hex << 11 << endl; cout << 12 << endl; will print : a b If I cout 13, it will be printed as 'c'. How do I remove the hex modifier from now on so it would just print 13? This is probably simple but I tried looking for the answer elsewhere. Thanks.
Write in your code: cout << dec << 13
2,278,966
2,279,001
Adding boost::ptr_vector to deque, typeid mismatch
I'm trying to add a boost::ptr_vector to a std::deque, using push_back(). When I do, I get a BOOST::ASSERT for the typeid mismatch. In "boost_ptr_container_clone_allocator" T* res = new T( r ); BOOST_ASSERT( typeid(r) == typeid(*res) && "Default new_clone() sliced object!" ); return res; From TotalView, res and r: Function "boost::new_clone<diagnostic_database_loader::DiagnosticDBClass>": r: (diagnostic_database_loader::DiagnosticDBClass const &) Local variables: res: 0x082534f8 -> (diagnostic_database_loader::DiagnosticDBClass) They look the same to me. The ptr_vector I'm trying to add has instances of diagnostic_database_loader::JointDiagnosticDBClass, which is derived from the diagnostic_database_loader::DiagnosticDBClass above. I printed out the typeid of the elements in the ptr_vector boost::ptr_vector<DiagnosticDBClass> items(loader->getData()); >>> N26diagnostic_database_loader22JointDiagnosticDBClassE I tried to reproduce this with a simple test program, but I'm not having the same problem. #include "iostream" #include <boost/ptr_container/ptr_vector.hpp> #include <deque> class Item { public: int my_val; Item() : my_val(1) { } int getMyVal() { return my_val; } }; class SmallItem : public Item { public: SmallItem() : Item() { my_val = 2; } }; class TinyItem : public SmallItem { public: TinyItem() : SmallItem() { my_val = 3; } }; class MyClass { private: boost::ptr_vector<SmallItem> items_; public: MyClass() { for (int i = 0; i < 10; ++i) { SmallItem *it = new TinyItem(); items_.push_back(it); } } std::auto_ptr<boost::ptr_vector<SmallItem> > getData() { return items_.release(); } }; std::deque<boost::ptr_vector<SmallItem> > Buffer; int totalItems(boost::ptr_vector<SmallItem> &items) { int total = 0; boost::ptr_vector<SmallItem>::iterator it; for (it = items.begin(); it != items.end(); ++it) total += (*it).getMyVal(); return total; } int main(int argc, char **argv) { MyClass cls; boost::ptr_vector<SmallItem> items(cls.getData()); std::cout << "SmallItem typeid " << typeid(items[0]).name() << std::endl; fprintf(stdout, "I found %d total!\n", totalItems(items)); Buffer.push_back(items); fprintf(stdout, "I pushed back into the deque!\n"); boost::ptr_vector<SmallItem> items2 = Buffer.front(); Buffer.pop_front(); fprintf(stdout, "I still found %d total in the new vector!\n", totalItems(items2)); items2.release(); fprintf(stdout, "I found %d total after I released!\n", totalItems(items2)); return 0; } The test program works fine. Does anyone know how to * Reproduce the problem in the test code? * Fix the problem in the real program? If anyone wants the full code: https://code.ros.org/svn/wg-ros-pkg/trunk/sandbox/diagnostic_database_loader
You should specialize the new_clone and delete_clone functions as described in the documentation. Alternatively you could specify your own clone allocator as the second argument of ptr_vector: class Item { public: int my_val; Item() : my_val(1) { } Item* clone() const { Item* item = do_clone(); BOOST_ASSERT(typeid(*this) == typeid(*item) && "do_clone() sliced object!"); return item; } int getMyVal() { return my_val; } private: // new virtual member function, overload in all derived classes. virtual Item* do_clone() const { return new Item(*this); } }; class SmallItem : public Item { public: SmallItem() : Item() { my_val = 2; } private: virtual Item* do_clone() const { return new SmallItem(*this); } }; struct ItemCloner { static Item* allocate_clone(const Item& item) { return item.clone(); } static void deallocate_clone(const Item* item) { delete item; } }; int main() { boost::ptr_vector<Item, ItemCloner> items; // and so on... }
2,279,007
2,279,042
How do you "break" out of a function?
Given a function that returns a value, is it possible to exit the function given a certain condition without returning anything? If so, how can you accomplish this? Example: int getNumber () { . . . } So say you are in this function. Is there a way to exit it without it doing anything?
You have two options: return something or throw. int getNumber() { return 3; } int getNumber() { throw string("Some Var"); } If you throw, you have to catch the type you threw. int maint(int argc, char ** argc) { try { getNumber(); } catch(string std) { //Your code will execute here if you throw } }
2,279,147
2,279,179
Calculate height of a tree
I am trying to calculate the height of a tree. I am doing it with the code written below. #include<iostream.h> struct tree { int data; struct tree * left; struct tree * right; }; typedef struct tree tree; class Tree { private: int n; int data; int l,r; public: tree * Root; Tree(int x) { n=x; l=0; r=0; Root=NULL; } void create(); int height(tree * Height); }; void Tree::create() { //Creting the tree structure } int Tree::height(tree * Height) { if(Height->left==NULL && Height->right==NULL) {return 0; } else { l=height(Height->left); r=height(Height->right); if (l>r) {l=l+1; return l; } else { r=r+1; return r; } } } int main() { Tree A(10);//Initializing 10 node Tree object A.create();//Creating a 10 node tree cout<<"The height of tree"<<A.height(A.Root);*/ } It gives me the correct result. But in some posts(googled page) it was suggested to do a Postorder traversal and use this height method to calculate the height. Any specific reason?
But isn't a postorder traversal precisely what you are doing? Assuming left and right are both non-null, you first do height(left), then height(right), and then some processing in the current node. That's postorder traversal according to me. But I would write it like this: int Tree::height(tree *node) { if (!node) return -1; return 1 + max(height(node->left), height(node->right)); } Edit: depending on how you define tree height, the base case (for an empty tree) should be 0 or -1.
2,279,180
2,279,205
Does C++ have "with" keyword like Pascal?
with keyword in Pascal can be use to quick access the field of a record. Anybody knows if C++ has anything similar to that? Ex: I have a pointer with many fields and i don't want to type like this: if (pointer->field1) && (pointer->field2) && ... (pointer->fieldn) what I really want is something like this in C++: with (pointer) { if (field1) && (field2) && .......(fieldn) }
In C++, you can put code in a method of the class being reference by pointer. There you can directly reference the members without using the pointer. Make it inline and you pretty much get what you want.
2,279,436
2,279,528
c++ namespace export
Is there a way in C++ to create an anonymous namespace, and only export a single function out of it? I want something like: namespace { void Bar() {} void Foo() { Bar(); } } Now, I want to somehow access to Foo() yet make sure there's no way to touch Bar() Thanks!
Since you want Foo() to have external linkage, you should declare it in a header file: #ifndef FOO_H #define FOO_H void Foo(); #endif Now everyone can see and call Foo() But in Foo.cpp: #include "Foo.h" namespace { void Bar(){ } } void Foo(){ Bar(); } Now, as long as you control the source file Foo.cpp, no one can change access to Bar()
2,279,603
2,279,834
Using STL inside ATL
I need to use tree structure inside a ATL COM server. I thought of using stl::map<> for this purpose as follows. BaseMap[k1,NextLevelMap[k2, NextLevelMap[k3, Value]]] But I need to know, whether using such a structure inside ATL is safe and possibility of debugging support with maps. Thank you
C++ standard library classes are safe to use with ATL - ATL even includes a couple of classes specifically designed to interface with containers following standard library conventions: ICollectionOnSTLImpl and CComEnumOnSTL. Debugging is also fine - the Visual Studio debugger hides the implementation of the standard containers and instead shows a logical view of what they contain.
2,280,462
2,281,405
Linker fails to link my application (XXXX already defined in XXXX.obj)
When I try to build my application the linker gives loads of errors like this one: modlauch.obj : error LNK2005: "public: virtual __thiscall lolbutton::~lolbutton(void)" (??1lolbutton@@UAE@XZ) already defined in lolbutton.obj I suspect it has something to do with misconfigured compiler but I don't know how to fix it. My class is only included once so I don't think it has anything to do with the code. I have tried rebuilding and cleaning the project but it didn't help. Can someone suggest a solution to this problem? My platform is Win32(C++) and I'm using MFC.
You'll get the linker error when you wrote the class like this: lolbutton.h: class lolbutton { public: virtual ~lolbutton(); }; lolbutton::~lolbutton() { // something... } You won't get it when you write it like this: class lolbutton { public: virtual ~lolbutton() { // inlined something... } }; Fix the linker error by moving the destructor definition from the .h file to a .cpp file. This ensures there is only one definition of the destructor.
2,280,499
2,280,555
Vkontakte UserAPI examples on C++
Say me please, where i can find examples on C++ with using UserAPI Vkontakte?
libvkext on google code seems to be one, you can also try to search google codebase for more...
2,280,630
2,280,729
c++ threadsafe static constructor
Given: void getBlah() { static Blah* blah = new Blah(); return blah; } In a multi threaded setting, is it possible that new Blah() is called more than once? Thanks!
The C++ standard makes no guarantee about the thread safety of static initializations - you should treat the static initialization as requiring explicit synchronisation. The quote Alexander Gessler gives: If control enters the declaration concurrently while the object is being initialized, the concurrent execution shall wait for completion of the initialization is from the C++0x draft, and doesn't reflect the current C++ standard or the behaviour of many C++ compilers. In the current C++ standard, that passage reads: If control re-enters the declaration (recursively) while the object is being initialized, the behaviour is undefined
2,280,639
2,280,687
Is .NET "all COM underneath"?
I've been an admirer of Juval Lowy's teaching and guidance in .NET development for a number of years. He's also written one of my favorite books: Programming .NET Components. However on a recent DotNet Rocks podcast (Jan 2010) in discussing WCF/COM and .NET, he made some comments that greatly surprised me: Juval Löwy: ..... in .NET, lo and behold, every class here is a COM object. We know that. In fact, it's much more than COM because we've got the git compiling, we've got garbage collection, we've got the Security Stack.... Carl Franklin: Well, you should clarify that though. I mean, every object is not a COM object. Every object has the capabilities that a COM object does, but the .NET Framework isn't a COM library. Juval Löwy: No, no. First of all .NET is actually built on top of COM. It's all COM underneath. Then, after Carl Franklin asks for clarification on this comment: Carl Franklin: Yeah, I get that. My question was is .NET built on COM? Juval Löwy: Of course, it all COM underneath. Carl Franklin: No. I know it's intertwined and it's required, but when you new up a .NET object you're not creating a COM object. Juval Löwy: You're creating a .NET object, but all I'm saying is that .NET is built underneath. It's all C++ and COM. Carl Franklin: It is C++ but you're not registering a COM object through the COM interface. It isn't all that stuff unless you specifically do that. Juval Löwy: But some of the stuff is using COM underneath, but that's beside the point. Forget about how it's made. How do you read these comments? While I understand (and have confirmed) that some of the System assemblies are written in unmanaged C++, is it also valid to say that they are "all COM underneath"? I was under the assumption it is perfectly possible to write .NET CLI compliant C++ assemblies that have absolutely nothing to do with COM / ATL / ActiveX? Here is the PDF transcript for the podcast in question. See Page 7.
It's almost as if Löwy is intentionally attempting to be unclear in what he says. I've not listened to the podcast, but judging by the umlauts, I reckon English is not his first language. Some objects that you use in .NET really are wrappers for COM objects. And a .NET object you create does a lot of what COM is supposed to do and more, without COM's nasty annoyances. I don't think the statement "it's all COM underneath" is accurate or clear. I wish the interview had been with Jeff Richter. ;-)
2,280,688
2,281,928
Taking the address of a temporary object
§5.3.1 Unary operators, Section 3 The result of the unary & operator is a pointer to its operand. The operand shall be an lvalue or a qualified-id. What exactly does "shall be" mean in this context? Does it mean it's an error to take the address of a temporary? I was just wondering, because g++ only gives me a warning, whereas comeau refuses to compile the following program: #include <string> int main() { &std::string("test"); } g++ warning: taking address of temporary comeau error: expression must be an lvalue or a function designator Does anyone have a Microsoft compiler or other compilers and can test this program, please?
The word "shall" in the standard language means a strict requirement. So, yes, your code is ill-formed (it is an error) because it attempts to apply address-of operator to a non-lvalue. However, the problem here is not an attempt of taking address of a temporary. The problem is, again, taking address of a non-lvalue. Temporary object can be lvalue or non-lvalue depending on the expression that produces that temporary or provides access to that temporary. In your case you have std::string("test") - a functional style cast to a non-reference type, which by definition produces a non-lvalue. Hence the error. If you wished to take address of a temporary object, you could have worked around the restriction by doing this, for example const std::string &r = std::string("test"); &r; // this expression produces address of a temporary whith the resultant pointer remaining valid as long as the temporary exists. There are other ways to legally obtain address of a temporary object. It is just that your specific method happens to be illegal.
2,280,965
2,280,996
how can i check file write permissions in C++ code?
In my C++ program, I want to make sure i can write info to a file. How can I perform this check?
You use the stat() system call, which the purists will tell you doesn't exist unless you change the tags on your question.
2,281,168
2,281,279
quick vector initialization c++
Possible Duplicates: C++: Easiest way to initialize an STL vector with hardcoded elements Using STL Allocator with STL Vectors out of curiosity i want to know quick ways of initializing vectors i only know this double inputar[]={1,0,0,0}; vector<double> input(inputar,inputar+4);
This is IMHO one of the failings of the current C++ standard. Vector makes a great replacement for C arrays, but initializing one is much more of a PITA. The best I have heard of is the Boost assignment package. According to the docs, you can do this with it: #include <boost/assign/std/vector.hpp> // for 'operator+=()' #include <boost/assert.hpp>; using namespace std; using namespace boost::assign; // bring 'operator+=()' into scope { vector<int> values; values += 1,2,3,4,5,6,7,8,9; // insert values at the end of the container BOOST_ASSERT( values.size() == 9 ); BOOST_ASSERT( values[0] == 1 ); BOOST_ASSERT( values[8] == 9 ); }
2,281,420
2,281,473
C++ Inserting a class into a map container
I have a map in C++ and I wish to input my class as the value, and a string as the key. When I try to, I get an error 'Scene_Branding' : illegal use of this type as an expression I get an illegal use of this type as an expression, and I can't seem to find out why. Here is some code. string CurrentScene = "Scene_Branding"; map<string, Scene> Scenes; Scenes.insert(std::make_pair("Scene_Branding", Scene_Branding)); //<-- Illegal Error parameter 2 and here is Scene Branding header.. #ifndef Scene_Branding_H #define Scene_Branding_H #include "Scene.h" #include <iostream> #include <string> class Scene_Branding : Scene { public: Scene_Branding(); ~Scene_Branding(); void Draw(); }; #endif and here is Scene header.. #ifndef Scene_H #define Scene_H #include <iostream> #include <string> class Scene { public: Scene(); ~Scene(); virtual void Draw(); }; #endif and here is there cpp files. Scene cpp. #include "Scene.h" Scene::Scene() { } Scene::~Scene() { } void Scene::Draw(){ std::cout << "Hey"; } Scene_Branding cpp #include "Scene_Branding.h" Scene_Branding::Scene_Branding() { } Scene_Branding::~Scene_Branding() { } void Scene_Branding::Draw() { std::cout << "Drawing from Scene_branding"; }
First, don't store objects themselves in the map, store pointers to your objects. Second, you need to give an instance of Scene_Branding to std::make_pair, not the class itself. EDIT: Here's how you go about storing pointers: string CurrentScene = "Scene_Branding"; map<string, Scene*> Scenes; Scenes.insert(std::make_pair("Scene_Branding", new Scene_Branding())); But, since you asked this type of question, i recommend you read a good c++ book for further grasping of concepts like pointers.
2,281,425
2,281,457
Read and parse line in C/C++; put tokens in an array or vector or similar structure
I have to submit code to one of the problems in ACM IPC and, as you may know, the time counts a lot. So, I have to read efficiently an input like this: The first line will contain the sequence of integer values associated and the second line will contain the sequence of integer values associated with another sequence. E.g.: 3 2 1 4 5 7 6 3 1 2 5 6 7 4 7 8 11 3 5 16 12 18 8 3 11 7 16 18 12 5 255 255 I have to put the 1st line in an array and the second in another and pass both in a function. How do I read and put these in C/C++? I was thinking in a C way, but my approach would have 2 while's... I have preference reading with scanf, but the parsing can be done as you want. Please , help this newb!
Read the lines using std::getline(). Then use a std::stringstream to parse each line. As this is for a competition, you won't be wanting actual code.
2,281,532
2,281,907
VS2008: Can I build a project with 2 CPP files of the same name in different folders?
Here is my folder structure: / | -- program.cpp -- utility.h -- utility.cpp | -- module/ | -- utility.h -- utility.cpp // Note that I have two files named utility.h and two named utility.cpp On building the project, I get a link error (LNK2028: unresolved token and so on...) saying that some symbols aren't defined. I have confirmed that all symbols are defined and that all declared functions have a corresponding definition. I have a feeling that on compiling my project, the utility.cpp files from both folders are compiled into the same utility.obj in the output folder. As a result, one overwrites the other. Is this expected behaviour? How do I build a C++ binary which has two files with the same name (though in different folders)?
Right click both/either .cpp files > properties > C/C++ > Output Files > Object File Name > set a custom name. e.g. if both files are named MyFile.cpp in folder A and another in folder B, you can set the output to be AMyFile and BMyFile. Alternatively, you can also use a macro to prefix the object names with the immediate parent folder name (i.e. using $(IntDir)\$(SafeParentName)$(SafeInputName)). If this is not enough (e.g. you have A/B/MyFile.cpp and C/B/MyFile.cpp) and you don't mind having some object files cluttering your source tree, you can also use $(InputDir)\ which will put the object files in the same folder as the source file. the cpp files will then be compiled into two different object files.. enjoy! Update for VS2010: There is a better solution in VS2010, check it out here. Thanks to n1ck's comment btw, if the contents have the same name, do you separate them using different namespaces? namespace A { // in folder A class CMyFile {}; }; namespace B{ // in folder B class CMyFile {}; }; // client.cpp #include "A/MyFile.h" #include "B/MyFile.h" int main() { A::CMyFile aMyFile; B::CMyFile bMyFile; return 0; } I don't know if it matters but it's definitely clearer to human : D
2,281,739
2,291,426
Automatically adding Enter/Exit Function Logs to a Project
I have a 3rd party source code that I have to investigate. I want to see in what order the functions are called but I don't want to waste my time typing: printf("Entered into %s", __FUNCTION__) and printf("Exited from %s", __FUNCTION__) for each function, nor do I want to touch any source file. Do you have any suggestions? Is there a compiler flag that automagically does this for me? Clarifications to the comments: I will cross-compile the source to run it on ARM. I will compile it with gcc. I don't want to analyze the static code. I want to trace the runtime. So doxygen will not make my life easier. I have the source and I can compile it. I don't want to use Aspect Oriented Programming. EDIT: I found that 'frame' command in the gdb prompt prints the current frame (or, function name, you could say) at that point in time. Perhaps, it is possible (using gdb scripts) to call 'frame' command everytime a function is called. What do you think?
Besides the usual debugger and aspect-oriented programming techniques, you can also inject your own instrumentation functions using gcc's -finstrument-functions command line options. You'll have to implement your own __cyg_profile_func_enter() and __cyg_profile_func_exit() functions (declare these as extern "C" in C++). They provide a means to track what function was called from where. However, the interface is a bit difficult to use since the address of the function being called and its call site are passed instead of a function name, for example. You could log the addresses, and then pull the corresponding names from the symbol table using something like objdump --syms or nm, assuming of course the symbols haven't been stripped from the binaries in question. It may just be easier to use gdb. YMMV. :)
2,281,819
2,281,837
Pointer allocation vs normal declaration
sometimes I see in various C++ programs, objects declared and used like so: object *obj = new object; obj->action(); obj->moreAction(); //etc... Is there any benefit of doing that, instead of simply doing: object obj; obj.action(); obj.moreAction(); //etc
Yes - you can store the pointer in a container or return it from the function and the object will not get destroyed when the pointer goes out of scope. Pointers are used to avoid unnecessary copying of object, to facilitate optional object creation, for custom object lifetime management, for creating complex graph-like structures, for the combinations of the above. This doesn't come for free - you need to destroy the object manually (delete) when you no longer need it and deciding when this moment comes is not always easy, plus you might just forget to code it.
2,281,836
2,281,887
stl hash_map - modifying key
I have a hash map defined as class KeyType { int key; mutable bool flag; KeyType(int key) : key(key), flag(false) {} void setFlag() const { flag = true; } }; struct KeyType_hasher { size_t operator()(const KeyType& s) const { return static_cast<size_t> key; } }; struct KeyType_equal { size_t operator()(const KeyType& s1, const KeyType& s2) const { return s1.key == s2.key; } }; typedef hash_map<KeyType , ValueType, KeyType_hasher, KeyType_equal > KeyValueMap; Later on in the code I have a place where I have to loop though the map and apply a function to each value I find. Based on the function's outcome, I have to modify the key at the iterator as well. KeyValueMap theMap; // theMap[key1] = value1; // theMap[key2] = value2; // theMap[key3] = value3; for(KeyValueMap::iterator i = theMap.begin(); i != theMap.end(); ++i) { if(true == ValueFunction(i->second)) i->first.setFlag(); } My question is, would that be the right way of modifying the key, if I have to? Does it have any bad side effects?
You'd have to remove the element from the container and re-add it with the new key. None of the C++ associative containers support changing the key in a significant way (where significant means the change alters the results of the hash in a hashed container or the comparrsion in an ordered container). If you did modify the key (by circumventing the const correctness system in some way) you'd get unpredictable results from lookups.
2,281,899
2,284,459
Stencil Buffer Read/Write mask
In Direct3D10 the Stencil Read/Write mask is a byte (from 0x00 to 0xFF) In Direct3D9 the Stencil Read/Write mask is a int (from 0x00000000 to 0xFFFFFFFF) The question is : How the stencil read/write mask in Direct3D10 relate to the Direct3D9 one? Direct3D10 | 0x00FFFFFF or Direct3D10 | 0xFFFFFF00 ? And another question : Why the Direct3D9 one is a 32 bit integer when the stencil buffer can be max 8 bit? o.O Thanks.
Direct3D10 | 0xFFFFFF00 The least significant bits are the relevant ones in D3D9, the docs describe the stencil operations in terms of DWORDs but ultimately the stencil buffer only stores a single byte so it is only the least significant byte of the mask that is important. The reason D3D9 uses a DWORD is that the value is set through SetRenderState which takes two parameters, a D3DRENDERSTATETYPE enum specifying the state to change and a DWORD value. All render states must therefore use a DWORD value regardless of how they are ultimately used. In some cases this means doing a reinterpret_cast on a floating point number. For the stencil mask it means passing a 32 bit value where only the least significant 8 bits are really needed. D3D10 sets states through typed structures and so avoids this issue.
2,281,983
2,281,998
Class definition and memory allocation
If definition stands for assigning memory. How come a class definition in C++ has no memory assigned until an object is instantiated.
C++ Class definitions do not assign memory. class is like typedef and struct. Where did you get the idea that "definition stands for assigning memory"? Can you provide a quote or reference? C++ Object creation (via new) assigns memory.
2,282,287
2,286,090
Threaded rendering with NSOpenGLView
I have an old AGL-based OpenGL windowing system that I am updating to use NSOpenGLView. The engine using it needs to run in its own loop in a separate thread and I am having trouble getting that to work. With AGL, I created the context in the loop thread, so there was no issue, but I'm a little bit confused about the way to do that with NSOpenGLView. I'd like to be able to instantiate it in the nib, so I don't want to create the whole thing in the loop thread. Is it even possible otherwise? Hope it makes sense.
Your separate thread can attach the NSOpenGLContext it creates to an existing NSOpenGLView by using the setOpenGLContext: method.
2,282,323
2,282,520
Problem with x64 application and ActiveX control
I have a small unmanaged c++ application, I'm trying to use CoCreateInstance(...) to create an instance of the "Adobe SVG PLayer" which is installed as an ActiveX control. When I compile and run my application under 32-bit configuration, it works fine, but when I compile under 64-bit configuration, my application fails to create the instance of the Adove SVG Player, although I know it is installed. This is the code that I'm using for doing this: const CLSID CLSID_SVGCtl = {0x377b5106,0x3b4e,0x4a2d,{0x85,0x20,0x87,0x67,0x59,0x0c,0xac,0x86}}; BOOL CheckSVGPresented() { BOOL bResult = FALSE; try { IUnknown* pSvgCtrl = NULL; if (FAILED(::CoCreateInstance(CLSID_SVGCtl, NULL, CLSCTX_INPROC_SERVER, IID_IUnknown, (LPVOID*)&pSvgCtrl)) || (NULL == pSvgCtrl)) throw 1; bResult = TRUE; pSvgCtrl->Release(); } catch (...) { bResult = FALSE; } return bResult; } My guess is that probably I have an issue because I have a 64 bits host (my application) trying to create a 32-bits instance of an ActiveX dll (The SVG player). I'm testing on Windows 7, x64 bits version. So if you have any clue about this I will appreciate the help.
I'm assuming that the ActiveX DLL you are trying to load is 32-bit only. Since ActiveX components are typically InProc, and 64 bit apps can't load in 32 bit DLLs, then you are correct about your guess. http://thermous.spaces.live.com/blog/cns!8DC85127F8CE2F12!161.entry
2,282,349
2,282,377
Specialization of 'template<class _Tp> struct std::less' in different namespace
I am specializing the 'less' (predicate) for a data type. The code looks like this: template<> struct std::less<DateTimeKey> { bool operator()(const DateTimeKey& k1, const DateTimeKey& k2) const { // Some code ... } }; When compiling (g++ 4.4.1 on Ubuntu 9.10), I get the error: Specialization of 'template struct std::less' in different namespace I did some research and found that there was a 'workaround' which involved wrapping the specialization in a std namespace - i.e. changing the code to: namespace std { template<> struct less<DateTimeKey> { bool operator()(const DateTimeKey& k1, const DateTimeKey& k2) const { // Some code ... } }; } which indeed, shuts the compiler up. However, that solution was from a post 5 years old (By the 'great' Victor Bazarof no less [pun unintended]). Is this fix still the way to go, or is there a better way of resolving this, or is the "old way" still valid?
This is still the way to do it. Unfortunately you cannot declare or define functions within a namespace like you would do with a class: you need to actually wrap them in a namespace block.
2,282,427
2,282,589
Interesting Problem (Currency arbitrage)
Arbitrage is the process of using discrepancies in currency exchange values to earn profit. Consider a person who starts with some amount of currency X, goes through a series of exchanges and finally ends up with more amount of X(than he initially had). Given n currencies and a table (nxn) of exchange rates, devise an algorithm that a person should use to avail maximum profit assuming that he doesn't perform one exchange more than once. I have thought of a solution like this: Use modified Dijkstra's algorithm to find single source longest product path. This gives longest product path from source currency to each other currency. Now, iterate over each other currency and multiply to the maximum product so far, w(curr,source)(weight of edge to source). Select the maximum of all such paths. While this appears good, i still doubt of correctness of this algorithm and the completeness of the problem.(i.e Is the problem NP-Complete?) as it somewhat resembles the traveling salesman problem. Looking for your comments and better solutions(if any) for this problem. Thanks. EDIT: Google search for this topic took me to this here, where arbitrage detection has been addressed but the exchanges for maximum arbitrage is not.This may serve a reference.
Dijkstra's cannot be used here because there is no way to modify Dijkstra's to return the longest path, rather than the shortest. In general, the longest path problem is in fact NP-complete as you suspected, and is related to the Travelling Salesman Problem as you suggested. What you are looking for (as you know) is a cycle whose product of edge weights is greater than 1, i.e. w1 * w2 * w3 * ... > 1. We can reimagine this problem to change it to a sum instead of a product if we take the logs of both sides: log (w1 * w2 * w3 ... ) > log(1) => log(w1) + log(w2) + log(w3) ... > 0 And if we take the negative log... => -log(w1) - log(w2) - log(w3) ... < 0 (note the inequality flipped) So we are now just looking for a negative cycle in the graph, which can be solved using the Bellman-Ford algorithm (or, if you don't need the know the path, the Floyd-Warshall algorihtm) First, we transform the graph: for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) w[i][j] = -log(w[i][j]); Then we perform a standard Bellman-Ford double dis[N], pre[N]; for (int i = 0; i < N; ++i) dis[i] = INF, pre[i] = -1; dis[source] = 0; for (int k = 0; k < N; ++k) for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) if (dis[i] + w[i][j] < dis[j]) dis[j] = dis[i] + w[i][j], pre[j] = i; Now we check for negative cycles: for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) if (dis[i] + w[i][j] < dis[j]) // Node j is part of a negative cycle You can then use the pre array to find the negative cycles. Start with pre[source] and work your way back.
2,282,450
2,283,042
stable sorting QTreeWidgetItems in QTreeWidget?
I have a list of QTreeWidgetItems (with children) in a QTreeWidget. I do not use a model for my data. From another window in my application the user can navigate thru the same set of data (viewed differently) and the QTreeWidget in the first window then highlights that specific row by setting the background colour. However, when the QTreeWidget is sorted on a column where some of the items have the same value it is undefined which item is first. When I then navigate using the other window and the background colour of the item is set, the equal items swaps place in the view automatically. This looks very strange. I suspect this is due to the sorting algorithm of QTreeWidget, but does anyone know a possible workaround to this?
Are you using QItemSelectionModel to do this, or did you write it yourself? If you wrote it yourself I would suggest using QItemSelectionModel. If you didn't, it sounds like you want a custom sorting algorithm which would require creating a derived QTreeWidget, if you are doing that, you might as well just use QTreeView and a custom QAbstractItemModel. Also, if you have two views of the same data, I would HIGHLY recommended using the Model/View framework and a QTreeView.
2,282,549
2,283,038
C++: Getting incorrect file size
I'm using Linux and C++. I have a binary file with a size of 210732 bytes, but the size reported with seekg/tellg is 210728. I get the following information from ls-la, i.e., 210732 bytes: -rw-rw-r-- 1 pjs pjs 210732 Feb 17 10:25 output.osr And with the following code snippet, I get 210728: std::ifstream handle; handle.open("output.osr", std::ios::binary | std::ios::in); handle.seekg(0, std::ios::end); std::cout << "file size:" << static_cast<unsigned int>(handle.tellg()) << std::endl; So my code is off by 4 bytes. I have confirmed that the size of the file is correct with a hex editor. So why am I not getting the correct size? My answer: I think the problem was caused by having multiple open fstreams to the file. At least that seems to have sorted it out for me. Thanks to everyone who helped.
At least for me with G++ 4.1 and 4.4 on 64-bit CentOS 5, the code below works as expected, i.e. the length the program prints out is the same as that returned by the stat() call. #include <iostream> #include <fstream> using namespace std; int main () { int length; ifstream is; is.open ("test.txt", ios::binary | std::ios::in); // get length of file: is.seekg (0, ios::end); length = is.tellg(); is.seekg (0, ios::beg); cout << "Length: " << length << "\nThe following should be zero: " << is.tellg() << "\n"; return 0; }
2,282,702
2,282,736
What code should be written to accept Lower and Upper case choices?
I'm beginner to c++ and writing a program that accepts user choices and acts according to it...my only problem is when the user enters Uppercase choice...the program treats it as it's a wrong choice...like if 'e' was a choice for entering a number..if the user entered 'E' the program won't display the "enter the number" message..how can i fix it ? i tried my best but i can't get it working.. Oh , and how can i add the Uppercase in Switch cases ? This is the part of the code that's responsible of taking user's choice and act according to it. #include <iostream> #include <cstring> using namespace std; int main(){ char choice ; for(;;){ do{ cout << endl ; cout << "(e)nter." << endl ; cout << "(d)isplay." << endl; cout << "(u)pdate." << endl ; cout << "(r)eset. " << endl; cout << "(q)uit." << endl; cout << endl; cout << "Choose one : " ; cin >> choice ; if( !strchr("edurq",choice) && (choice>=97&&choice<=122) ){ cout << "Enter e,d,u or q " << endl;} else if( !strchr("EDURQ",choice) && (choice<97&&choice>122) ){ cout << "Enter E,D,U or Q " << endl;} }while( !strchr("edurqEDURQ",choice) ); switch (choice) { case 'e' : enter(); break ; case 'd' : display(); break ; case 'u': update() ; break ; case 'r' : reset() ;break; case 'q' : return 0; } } }
If you don't break for a case in a switch statement that matches it will continue on to the next one. If you put the capital cases before each lower case choice it will fall through. switch (choice) { case 'E' : case 'e' : enter(); break ; case 'D' : case 'd' : display(); break ; case 'U' : case 'u': update() ; break ; case 'R' : case 'r' : reset() ;break; case 'Q' : case 'q' : return 0; } The other option is to apply a string function to the user input to change it to lower case, in which case your existing switch statement would work.
2,282,725
2,282,774
C++ : what is :: for?
If you go to the accepted answer of this post Could someone please elaborate on why he uses: double temp = ::atof(num.c_str()); and not simply double temp = atof(num.c_str()); Also, is it considered a good practice to use that syntax when you use "pure" global functions?
It says use the global version, not one declared in local scope. So if someone's declared an atof in your class, this'll be sure to use the global one. Have a look at Wikipedia on this subject: #include <iostream> using namespace std; int n = 12; // A global variable int main() { int n = 13; // A local variable cout << ::n << endl; // Print the global variable: 12 cout << n << endl; // Print the local variable: 13 }
2,282,735
2,283,932
DirectX9, DirectDraw, Optimization?
First off, I'm programming a game. Currently in the render function there are two calls to two different functions. One renders some text, one renders sprites. On my computer (AMD Phenom(tm) II X4 955 Processor (4 CPUs), ~3.2GHz, 4096MB RAM DDR2, NVIDIA GeForce GTX 285) I have a render speed of ~2200 FPS when rendering around 200 sprites and about 100 FPS when rendering about 14,500. I'm using a vector to store the information of each object I'm rendering and using one sprite with many draw calls. VS2008 release mode with full optimization for C++. I know I've heard left and right don't optimize prematurely, but at this point, it's running great for me, but not so well on certain computers. I can't imagine changing vectors out for arrays since I'm pushing and pulling things from the vector every frame, in an indeterminable method. Nearly randomly. I've tried floats and doubles and the speed is no different. Would it be different using DirectDraw rather than DirectX and the Sprite Render method? Since I've no idea the differences between DirectDraw and DirectX, I'm not 100% what I should be thinking about that. The game runs fine on average computers, but what I'm comparing my game to is Touhou. Touhou runs at 60 FPS on the weakest computer I've tried, but my game won't run faster than 36~42 FPS. I can't imagine what I'm doing wrong, being so new to DirectX and C++. Any assistance in this matter would be great, unfortunately I won't be around for awhile to add information or answers questions.
You need a profiler. There's some good performance advice in the responses, but it doesn't matter. Trying to optimize a program without a profiler is like trying to write a program without a compiler. Do not guess, measure. Now with that said, profiling graphics code is an infamous pain in the neck, and there aren't (to my knowledge) any good, free tools to help with it. So never mind that for now: start with an ordinary CPU profiler, and find out which of your calls is really taking up all your time.
2,282,802
2,282,851
Building RAPI.h in VS 2005, fail on open include file
this may sound too simple, but I'm missing something. I need to write a RAPI Windows Console app using C++. I'm currently using VS2005. I've created a brand new empty Windows Consol app "MyTestRAPI" from documentation, I know I need the include of the "RAPI.H" file. So, I've tried as #include <rapi.h> and also by #include "rapi.h" I compile and get the following fatal error C1083: Cannot open include file: 'rapi.h': No such file or directory So, I then go to menu for "Project", "Properties". On the treeview for "Common Properties" -> "References", I go to the lower right and click on "Add Path", and include the explicit path where the rapi.h file and other .h files are located... in this case "C:\Program Files\Windows CE Tools\wce500\Windows Mobile 5.0 Pocket PC SDK\Activesync\Inc" which include 14 .h files Save / build the project, and still compile error... So, I change the #include to #include "C:\Program Files\Windows CE Tools\wce500\Windows Mobile 5.0 Pocket PC SDK\Activesync\Inc\rapi.h" This time, it finds THIS include, but fails on finding the #includes within the rapi.h which also reside in the same folder. What is it that I'm missing that appears to elude me. Thanks
The "Common Properties" -> "References" field refers to .NET assembly references. To add a path to the C++ #include search path, you need to use "Configuration Properties" -> "C/C++" -> "General" -> "Additional Include Directories".
2,282,928
2,285,524
Schliemann's method of programming language learning
Background: 19th-century German archeologist Heinrich Schliemann was of course famous for his successful quest to find and excavate the city of Troy (an actual archeological site for the Troy of Homer's Iliad). However, he is just as famous for being an astonishing learner of languages - within the space of two years, he taught himself fluent Dutch, English, French, Spanish, Italian and Portuguese, and later went on to learn seven more, including both modern and ancient Greek. One of the methods he famously used was comparison of a known text, e.g. take a book in a language one is fluent in, take a good translation of a book in a language you wish to learn, and go over them in parallel. (various sources cited the book used by Schliemann to be the Bible, or, as the link above states, a novel). Now, for the actual question. Has anyone used (or heard of) an equivalent of Schliemann's method for learning a new programming language? E.g. instead of basing the leaning on references and tutorials, take a somewhat comprehensive set of programs known to have high-quality code in both languages implementing similar/identical algorithms and learn by comparing them? I'm curious about either personal experiences of applying such an approach, or references to something published, or existance of codebases which could be used for such an approach? What got me thinking about the idea was Project Euler and some code snippets I saw on SO, in C++, Perl and Lisp.
Rosetta Code may be useful. To quote the site:- Rosetta Code is a programming chrestomathy site. The idea is to present solutions to the same task in as many different languages as possible, to demonstrate how languages are similar and different, and to aid a person with a grounding in one approach to a problem in learning another. Rosetta Code currently has 372 tasks, and covers 197 languages, though we do not (and cannot) have solutions to every task in every language.
2,283,428
2,303,670
WM_MOUSELEAVE not being generated when left mouse button is held
In my Win32 app, I don't get WM_MOUSELEAVE messages when I hold down the left mouse button and quickly move the mouse pointer out of the window. But If I, holding down the left mouse button, start from the inside of the window and move slowly past the window edge, it'll generate a WM_MOUSELEAVE. If I don't hold the left mouse button, I get WM_MOUSELEAVE messages every time no matter how fast the mouse pointer moves off the window. What's the difference? What can I do to handle both cases properly? EDIT: If I left click and hold, move out of the window and then let go of the left mouse button I get the WM_MOUSELEAVE message. But it's way too late.
WM_MOUSELEAVE is so that you can detect the mouse leaving your window when you don't have capture. When you have capture, you are responsible for detecting that yourself (if you care). so It doesn't make any sense to SetCapture AND TrackMouseEvent at the same time, you would use one or the other. Now, if it would be more convenient for you to see the WM_MOUSELEAVE messages while you have capture, it's a relatively simple matter to do that by yourself in your message pump. You would just add code that looks something like this between the GetMessage() and the DispatchMessage() calls in your message pump. GetMessage(pmsg, ...); ..... if ((IS_WITHIN(pmsg->message, WM_MOUSEFIRST, WM_MOUSELAST) || IS_WITHIN(pmsg->message, WM_NCMOUSEMOVE, WM_NCMBUTTONDBLCLK)) && MyMouseLeaveDetection(pmsg, g_hwndNotifyMouseLeave)) { MSG msg = *pmsg; msg.message = WM_MOUSELEAVE; msg.hwnd = g_hwndNotifyMouseLeave; // window that want's msg.lParam = 0xFFFFFFFF; g_hwndNotifyMouseLeave = NULL; DispatchMessage (&msg); } ..... TranslateMessage(pmsg); DispatchMessage(pmsg);
2,283,490
2,283,971
Is there a limit to how big an xml file can be for tinyxml to parse it?
I have an xml file that is about 42k in size. Shouldn't tinyxml be able to parse a file of this size. Looking at the tinyxml source code, it appears to just read the entire file in as a char *. When I reduce the xml file in size to 7k, tinyxml works just fine. Is there a definitive limit to the # of bytes that tinyxml will parse?
If there's a limit, it's a lot bigger than that -- I've used it successfully on files over 100 megabytes.
2,283,508
2,283,548
Saving image as JPG -library?
I'd like to find a JPEG-writing library that can be statically linked (so there are no DLL dependencies). No JPEG-reading ability is required. Edit: I got LibGD working, but it had one problem described here: LibGD library is not working: crash when saving image
Have you looked at LibGD? I can't seem to find the license, but neither did you specify a requirement.
2,283,712
2,283,778
What header should I include for memcpy and realloc?
I am porting a project to the iPhone and it uses realloc and memcpy which are not found. What is the header to include? It's a project mixing Objective C and C++ and I am starting to be lost. Thanks in advance for your help!
In C: #include <string.h> // memcpy #include <stdlib.h> //realloc In C++, remove the .h and prefix with a c. In C++, they will be placed in the std namespace, but are also global.
2,283,828
2,284,165
c++ templates in an iPhone project
I am porting a project to the iPhone system and I am facing the following problem: I have an header containing c++ templates If I rename it to .mm, it does not compile (because it should be an header) and if I keep it as .h, it is interpreted as an objective C header Do you have a workaround to fix this issue? Thanks in advance! Regards, edit: add error message and code template <typename T> class CML_Matrix { public: //rest of teh template }; error message is "cannot find protocol declaration for typename"
Wrap it in #ifdef __cplusplus //templates here #endif This way, the templates will be silently ignored when the file is included in a C or Objective C (.m) source. You can also have some Objective C-only constructs wrapped in #ifdef __OBJC__ EDIT: you can, alternatively, rename your sources (not the header!) to .mm. Since it's a mixed ObjC/C++ project, you'll probably have to instantiate/call C++ classes at some point; for that, you'll need Objective C++ anyway. Never tried this, though.
2,283,845
2,283,966
Which is the best data-structure for iterating through arrangements of a string?
Lets say, we have string "ABCAD", now we need to iterate through all possible arrangement of this string in both clockwise and counter-clockwise direction. My ugly implementation looks like this: string s = "ABCAD"; string t =""; for(int i = 0; i < sz(s); i++){ t = s[i]; for(int j = i+1; ; j++){ if((j) == sz(s)){ j = 0; } if(j == i){ break; } t+= s[j]; } cout<<t<<" "; } reverse(all(s)); for(int i = 0; i < sz(s); i++){ t = s[i]; for(int j = i+1; ; j++){ if((j) == sz(s)){ j = 0; } if(j == i){ break; } t+= s[j]; } cout<<t<<" "; } Output: AHSAU HSAUA SAUAH AUAHS UAHSA UASHA ASHAU SHAUA HAUAS AUASH I know that too naive,AFAIK a circular list would be a better choice, could somebody implement the same thing more efficiently using STL ?
In pseudocode, I'd go this route: function rearrange (string s) { string t = s + s; for (int i = 0; i < length(s); ++i) print t.substring(i, length(s)); } input = "ABCAD" rearrange(input); rearrange(reverse(input)); There's probably a way to rewrite rearrange() using functors, but my STL-fu is rusty.
2,284,051
2,284,174
Qt installation error
i got an error when am trying to configure Qt. Erro : execute: File or path is not found (nmake) execute: File or path is not found (nmake) Cleaning qmake failed, return code -1 // installion files. InterBase...............no Sources are in..............E:\xampp\Qt\4.6 Build is done in............E:\xampp\Qt\4.6 Install prefix..............E:\xampp\Qt\4.6 Headers installed to........E:\xampp\Qt\4.6\include Libraries installed to......E:\xampp\Qt\4.6\lib Plugins installed to........E:\xampp\Qt\4.6\plugins Binaries installed to.......E:\xampp\Qt\4.6\bin Docs installed to...........E:\xampp\Qt\4.6\doc Data installed to...........E:\xampp\Qt\4.6 Translations installed to...E:\xampp\Qt\4.6\translations Examples installed to.......E:\xampp\Qt\4.6\examples Demos installed to..........E:\xampp\Qt\4.6\demos Creating qmake... execute: File or path is not found (nmake) execute: File or path is not found (nmake) Cleaning qmake failed, return code -1 E:\xampp\Qt\4.6>
If you are trying to build Qt with a Visual Studio enviroment, you have to make sure that nmake and cl are in the PATH. The easiest way to do that is to simply use the Visual Studio Command Prompt (found e.g. in the start menu).
2,284,086
2,284,124
Is there an automated way to merge C++ implementation(.cpp) and header (.h) files
I am trying to create a unit test framework using CPPUnit for a large code base. I need to be able to test individual modules, all of which are part of a module tree that begins with a specific root module. Due to a non-technical reason, I cannot touch the production file (my original approach involved adding an ifdef to the root module). So I thought of another approach, which is to have create copies of the root module headers as well as copies of headers belonging to modules in the intermediate inheritance hierarchy. Because of the number of number of modules involved as well as the size of each module's source. I'm looking for a way to automatically do that merging for me. So for foo.h, and foo.cpp, I'm looking for a some kind of a tool that'll output fooTest.h, where fooTest.h contains the declaration AND definition of everything that is in foo.cpp/foo.h EDIT: Thanks for the answers, one thing I forgot to mention is that, the contents of fooTest.h is not supposed to be the merged result of foo.cpp and foo.h . I need to make minor changes to the root fooTest.h in order to make it a suitable mock-module for testing. Thus, simply using includes won't work. I'll look into concatenating the files and see if that solves my problem.
This isn't a C++ question - you are asking how to manipulate files in some sort of script. The immediate answer that comes to mind is: cat foo.h foo.cpp > fooTest.h
2,284,112
2,284,163
Easiest way for a simple 3d app
A friend of mine asked for a simple program. Input: Coordinates of some points, spheres, planes etc. ( from an excel document (strictly) ) Output: A 3D view of the input which the user can move the camera. The questions is, how can I do that easiest way. I have experience in C++, C#, Flash (AS), Java
Input: Coordinates of some points, spheres, planes etc. ( from an excel document (strictly) ) This is going to be your major problem, reading an excel document from Flash is not an easy task. You will either have to process it on a server side script with XML/JSON/AMF output to the client, or simply give up on the format. Output: A 3D view of the input which the user can move the camera. Displaying 3D objects in flash is easy using one of Papervision3D or Away3D.
2,284,275
2,284,308
C++ Array and Vector are hold values or references?
In C++ we have value type (int, long, float, ...) and reference type (class, struct, ...). For value type, Array and Vector hold the actual values; For reference type, Array and Vector only hold the references to these objects; So when we put reference type into Array and Vector, we need to make sure those objects will exist long enough (valid during the entire process) to avoid exception/error; My above statements are correct or not? please correct me if I am wrong.
No. Any type can be passed by value or by reference (also any type can be created on the stack or on the heap, though you didn't ask that). For any type Arrays and Vectors hold the actual values. Because of this any type stored in a vector needs to be copy-constructible. See 2. Nope. That's only the case if you explicitly create a vector of pointers and then store a pointer to your object.
2,284,428
2,284,548
In C++ networking, using select do I first have to listen() and accept()?
I'm trying to allow multiple clients to connect to a host using select. Will I have to connect each one, tell them to move to a different port, and then reconnect on a new port? Or will select allow me to connect multiple clients to the same port? This is the client code: int rv; int sockfd, numbytes; if ((rv = getaddrinfo(hostName, hostPort, &hints, &servinfo)) != 0) { cout << "Could not get server address.\n"; exit(1); } // loop through all the results and connect to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("Client: no socket"); continue; } if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("Client: connect"); continue; } break; } if (p == NULL) { fprintf(stderr, "Unable to connect to server.\n"); exit(2); } FD_SET(sockfd, &masterSet); This is the server code: int rv = getaddrinfo(NULL, port, &hints, &res); int yes = 1;//Not sure what this is for, found it in Beej's if(rv != 0){ cout<< "Error, nothing matches criteria for file descriptor.\n"; exit(1); } int fdInit; for(temp = res; temp != NULL; temp = temp->ai_next){ if((fdInit = socket(temp->ai_family, temp->ai_socktype, temp->ai_protocol)) == -1){ cout << "This is not the fd you're looking for. Move along.\n"; continue; //This is not the fd you're looking for, move along. } if(setsockopt(fdInit, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1){ cout << "Doom has fallen upon this set socket.\n"; perror("setsockopt"); exit(1); //Unable to set socket, exit program with code 1 } if(bind(fdInit, temp->ai_addr, temp->ai_addrlen) == -1){ cout << "Could not bind fd\n"; close(fdInit); continue; //Could not bind fd, continue looking for valid fd } break; //If a valid fd has been found, stop checking the list } if(temp==NULL){ cout<<"Server failed to bind a socket\n"; exit(2); } cout << fdInit << endl; //Setup the file descriptor for initial connections on specified port freeaddrinfo(res); FD_SET(fdInit, &masterSet); Any help would be excellent! Thanks.
TCP connections are identified by the IP address and port number of both ends of the connection. So it's fine to have lots of clients (which will generally have randomly assigned port numbers) to connect to a single server port. You create a socket and bind() it to a port on which to listen(), and then wait for clients to come knocking on it. If you don't mind blocking you can just call accept() on it directly, but you won't get to do any timeout looping or anything. Otherwise you can select() on the listening socket, which will become readable when a client is attempting to connect, and then call accept(). accept() will return a newly created socket, which is the actual socket to talk to the client on. The original listening socket continues to listen, and more connections can be accepted on it. It's typical to use a select() loop to look for readability on the listening socket and any of the connected sockets. Then when select() returns you simply check whether the listening socket was readable, and if so, accept(); otherwise look for a readable connected socket and handle it. fd_set fds; int max = 0, reuse = 1; struct timeval tv; int server; std::vector<int> connected; // create server listening socket server = socket(PF_INET, SOCK_STREAM, getprotobyname("tcp")->p_proto); setsockopt(server, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(int)); // optional, but recommended if (bind(server, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) { // error, could not bind server socket } if (listen(server, 8) < 0) { // error, could not listen on server port } // loop looking for connections / data to handle while (running) { FD_ZERO(&fds); FD_SET(server, &fds); if (server >= max) max = server + 1; for (std::vector<int>::iterator it = connected.begin(); it != connected.end(); ++it) { FD_SET(*it, &fds); if (*it >= max) max = *it + 1; } tv.tv_sec = 2; tv.tv_usec = 0; if (select(max, &fds, NULL, NULL, &tv) > 0) { // something is readable if (FD_ISSET(server, &fds)) { // it's the listener connected.push_back(accept(server, (struct sockaddr *)&addr)); } for (std::vector<int>::iterator it = connected.begin(); it != connected.end(); ++it) { if (FD_ISSET(*it, &fds)) { // handle data on this connection } } } }
2,284,610
2,284,616
What is __declspec and when do I need to use it?
I have seen instances of __declspec in the code that I am reading. What is it? And when would I need to use this construct?
This is a Microsoft specific extension to the C++ language which allows you to attribute a type or function with storage class information. Documentation __declspec (C++)
2,284,648
2,303,074
DLL and fully-specialized template class
Environment: Visual Studio 9, C++ without managed extensions. I've got a third-party library which exports a fully-specialized template class MyClass<42> defined in MyClass.h. It gets compiled into a helper loader .lib and a .dll file. The .lib file contains compiled code for this specialization, and necessary symbols. The MyClass.h looks like this: template<UInt D> class MyClass { public: MyClass() {...}; virtual ~MyClass() {}; } Now I'd like to use this library. If I include the MyClass.h in a Client.cpp and then compile it, I'll get second copy of these symbols in the Client.obj file. I can get rid of these symbols by defining all the member of that specialization as "extern". My Client.cpp looks like this: #include <ThirdParty/MyClass.h> extern template class MyClass<42>; extern template MyClass<42>::MyClass<42>(); extern template MyClass<42>::~MyClass<42>(); void MyFunction(MyClass<42>& obj) {...} The problem is that I cannot get rid of the virtual destructor this way. For the virtual destructor I get an almost standard LNK2005 error: ThirdPartyd.lib(ThirdPartyd.dll) : error LNK2005: "public: virtual __thiscall MyClass<42>::~MyClass<42>(void)" (??1?$MyClass@$01@@@UAE@XZ) already defined in Client.obj What should I do?
It seems that for virtual methods it is necessary to define them as both extern and __declspec(dllimport) at the same time: extern template __declspec(dllimport) MyClass<42>::~MyClass<42>(); This made my linker happy enough to link my code properly. I would be very glad if some expert described why is so, or at least pointed to some article explaining this case.
2,284,707
2,287,711
DAO large query lockup on Win7 multicore
I have a C++ app that uses a Jet database through DAO. Large queries work well up through Vista but lockup under Win7 on a multicore machine. I have tried both jet 3.5 and 4.0. Both fail. I have tried disabling threads in calling prog (my app) - still fails.
Calling SetProcessAffinityMask(1<<GetCurrentProcessorNumber()) is a rather brute-force way of restricting yourself to the current core only. But it's of course better to use a debugger to determine why it locks up. Which two threads deadlock?
2,284,775
2,284,805
C++ can I reuse fstream to open and write multiple files?
I have 10 files need to be open for write in sequence. Can I have one fstream to do this? Do I need to do anything special (except flush()) in between each file or just call open(file1, fstream::out | std::ofstream::app) for a each file and close the stream at the end of all 10 files are written.
You will need to close it first, because calling open on an already open stream fails. (Which means the failbit flag is set to true). Note close() flushes, so you don't need to worry about that: std::ofstream file("1"); // ... file.close(); file.clear(); // clear flags file.open("2"); // ... // and so on Also note, you don't need to close() it the last time; the destructor does that for you (and therefore also flush()'s). This may make a nice utility function: template <typename Stream> void reopen(Stream& pStream, const char * pFile, std::ios_base::openmode pMode = ios_base::out) { pStream.close(); pStream.clear(); pStream.open(pFile, pMode); } And you get: std::ofstream file("1"); // ... reopen(file, "2") // ... // and so on
2,284,872
2,285,580
Parsing XML using libxml
I've got a small problem with parsing XML. I cannot get the name of a child node. Here's my XML code: <?xml version="1.1" encoding='UTF-8'?> <SceneObject> <ParticleSystem> </ParticleSystem> </SceneObject> Here's how I parse the XML file: SceneObject::SceneObject(const char *_loadFromXMLFile, const char *_childType) { xmlNodePtr cur; pXMLDocument = xmlParseFile( getPathForResource(_loadFromXMLFile, "xml") ); if (pXMLDocument == NULL) { fprintf(stderr, "Document not parsed successfully. \n"); return; } cur = xmlDocGetRootElement(pXMLDocument); if (cur == NULL) { fprintf(stderr, "Empty document\n"); xmlFreeDoc(pXMLDocument); return; } if (!xmlStrEqual(cur->name, (const xmlChar *) "SceneObject")) { fprintf(stderr, "Document of the wrong type; root node == %s\n", cur->name); xmlFreeDoc(pXMLDocument); return; } SimpleLog("cur->name: %s", (const char*)cur->name); cur = cur->children; SimpleLog("cur->children->name: %s", (const char*)cur->name); } What I get in the console is: cur->name: SceneObject cur->children->name: text Why "cur->children->name" is "text" and is not "ParticleSystem"? What am I doing wrong and how can I fix this? Thanks.
The "text" node is the whitespace (newline character) between <SceneObject> and <ParticleSystem> in your document. cur->children->next is the <ParticleSystem> node you want in this case. In general you can consult the type member of a node to determine whether it is an element, text, cdata, etc.
2,285,110
2,285,154
Restrict application to one instance per shell session on Windows
There are a lot of solutions for restricting an application from running twice. Searching by process name, using a named mutex etc. But I all of these methods don't work if I want to restrict my application to the shell session. A user may have more than login session and shell on windows (right?)? If this is true I want to be able to run one instance of my application in every shell session but allow only one. Is there a way to get a shell identifier which could then be put into the mutex name?
You can create local (session only) or global (whole system) mutexes. See http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx for more info. Look for global and local.
2,285,375
2,305,626
Intel Thread Building Blocks Concurrent Queue: Using pop() over pop_if_present()
What is the difference in using the blocking call pop() as compared to, while(pop_if_present(...)) Which should be preferred over the other? And why? I am looking for a deeper understanding of the tradeoff between polling yourself as in the case of while(pop_if_present(...)) with respect to letting the system doing it for you. This is quite a general theme. For example, with boost::asio I could do a myIO.run() which blocks or do the following: while(1) { myIO.poll() } One possible explanation is is that the thread that invokes while(pop_if_present(...)) will remain busy so this is bad. But someone or something has to poll for the async event. Why and how can this be cheaper when it is delegated to the OS or the library? Is it because the OS or the library smart about polling for example do an exponential backoff?
Intel's TBB library is open source, so I took a look... It looks like pop_if_present() essentially checks if the queue is empty and returns immediately if it is. If not, it attempts to get the element on the top of the queue (which might fail, since another thread may have come along and taken it). If it misses, it performs an "atomic_backoff" pause before checking again. The atomic_backoff will simply spin the first few times it's called (doubling its spin loop count each time), but after a certain number of pauses it'll just yield to the OS scheduler instead of spinning on the assumption that since it's been waiting a while, it might as well do it nicely. For the plain pop() function, if there isn't anything in the queue will perform atomic_backoff waits until there is something in the queue that it gets. Note that there are at least 2 interesting things (to me anyway) about this: the pop() function performs spin waits (up to a point) for something to show up in the queue; it's not going to yield to the OS unless it has to wait for more than a little short moment. So as you might expect, there's not much reason to spin yourself calling pop_if_present() unless you have something else you're going to do between calls to pop_if_present() when pop() does yield to the OS, it does so by simply giving up it's time slice. It doesn't block the thread on a synchronization object that can be signaled when an item is placed on the queue - it seems to go into a sleep/poll cycle to check the queue for something to pop. This surprised me a little. Take this analysis with a grain of salt... The source I used for this analysis might be a bit old (it's actually from concurrent_queue_v2.h and .cpp) because the more recent concurrent_queue has a different API - there's no pop() or pop_if_present(), just a try_pop() function in the latest class concurrent_queue interface. The old interface has been moved (possibly changed somewhat) to the concurrent_bounded_queue class. It appears that the newer concurrent_queues can be configured when the library is built to use OS synchronization objects instead of busy waits and polling.
2,285,409
2,286,479
C++ urljoin equivalent
Python has a function urljoin that takes two URLs and concatenates them intelligently. Is there a library that provides a similar function in c++? urljoin documentation: http://docs.python.org/library/urlparse.html And python example: >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html') 'http://www.cwi.nl/%7Eguido/FAQ.html'
I figured it out. I used the library uriparser: http://uriparser.sourceforge.net/ and hastily implemented the function as follows. It does sparse error checking and may leak memory. std::string urljoin(std::string &base, std::string &relative) { UriParserStateA state; UriUriA uriOne; UriUriA uriTwo; state.uri = &uriOne; if (uriParseUriA(&state, base.c_str()) != URI_SUCCESS) { return ""; } state.uri = &uriTwo; if (uriParseUriA(&state, relative.c_str()) != URI_SUCCESS) { uriFreeUriMembersA(&uriTwo); return ""; } UriUriA result; if (uriAddBaseUriA(&result, &uriTwo, &uriOne) != URI_SUCCESS) { uriFreeUriMembersA(&result); return ""; } uriFreeUriMembersA(&uriOne); uriFreeUriMembersA(&uriTwo); int charsRequired; uriToStringCharsRequiredA(&result, &charsRequired); charsRequired++; char *buf = (char*) malloc(charsRequired * sizeof(char)); if (uriToStringA(buf, &result, charsRequired, NULL) != URI_SUCCESS) return ""; uriFreeUriMembersA(&result); std::string ret(buf); free(buf); return ret; }
2,285,718
2,285,903
How do we typedef or redefine a templated nested class in the subclass?
Consider the following: template <typename T> class Base { public: template <typename U> class Nested { }; }; template <typename T> class Derived : public Base<T> { public: //How do we typedef of redefine Base<T>::Nested? using Base<T>::Nested; //This does not work using Base<T>::template<typename U> Nested; //Cannot do this either typedef typename Base<T>::template<typename U> Nested Nested; //Nope.. //now we want to use the Nested class here template <typename U> Class NestedDerived : public Nested { }; //or like this: Nested<int> nestedVar; // obviously does not work }; How to use the templated Nested class in the Derived class? Is this possible to do in current version of C++ standard?
Actually using works as advertised, it just doesn't get rid of the dependent-name issue in the template and it can't currently alias templates directly (will be fixed in C++0x): template <class T> struct Base { template <class U> struct Nested {}; }; template <class T> struct Derived : Base<T> { using Base<T>::Nested; // need to prefix Nested with template because // it is a dependent template: struct X : Base<T>::template Nested<int> {}; // same here: template<class U> struct Y : Base<T>::template Nested<U> {}; // data member, typename is needed here: typename Base<T>::template Nested<int> data; }; void f() { Derived<int>::Nested<int> n; // works fine outside } There is another possible gotcha when using Derived<T>::Nested in templates, but again that is a dependent-name issue, not inheritance-related: template<class T> void g() { // Nested is a dependent type and a dependent template, thus // we need 'typename' and 'template': typedef typename Derived<T>::template Nested<int> NestedInt; } Just remember that names that depend on template arguments have to be prefixed with typename if its a dependent type: typename A<T>::B directly prefixed with template if its a dependent template: A<T>::template f<int>() both if both: typename A<T>::template B<int> typename is illegal in base-class-lists: template<class T> struct A : B<T>, C<T>::template D<int> {};
2,285,822
2,285,861
C++, what is a good way to hash array data?
I have a curious problem and I am brainstorming possible solutions. The problem is such: I have a number of inputs (up to several thousand different ones), which basically differ in two-three arrays (arrays are a different size generaly, from size one up to couple thousand elements long). the functions which process arrays take some time to initialize data, so i thought to cache function/functor together with data and store them in map. now, how do i go about converting raw arrays into usable hashtable type? i initially thought to read array into a string and use string as the key. is it good idea? do you have better suggestion?
Are these arrays integer? If yes, just go with something like this hash = (hash + (324723947 + a[i])) ^93485734985; Similar thing would work fine for strings if you do it on all characters. Finally, you may check out extra libs here
2,285,878
2,285,968
c++ elevating privileges on an .exe using OpenProcess()
I have been reading some of the books by Hoglund and I thought I would have a 'go' at his 'simple debugger'... Anyway, I have been trying to use the line hProcess = OpenProcess(PROCESS_ALL_ACCESS | PROCESS_VM_OPERATION, 0, aPID); Every time I use it on a running process hProcess is being returned as NULL, why is this - the target I was using was an instance of notepad.exe. I can terminate a process no problem using: hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | PROCESS_TERMINATE, FALSE, aPID ); I am wondering how to elevate privileges, and why it doesn't work. Thanks, R.
One possibility is given in MSDN: Windows Server 2003 and Windows XP/2000: The size of the PROCESS_ALL_ACCESS flag increased on Windows Server 2008 and Windows Vista. If an application compiled for Windows Server 2008 and Windows Vista is run on Windows Server 2003 or Windows XP/2000, the PROCESS_ALL_ACCESS flag is too large and the function specifying this flag fails with ERROR_ACCESS_DENIED. To avoid this problem, specify the minimum set of access rights required for the operation. If PROCESS_ALL_ACCESS must be used, set _WIN32_WINNT to the minimum operating system targeted by your application (for example, #define _WIN32_WINNT _WIN32_WINNT_WINXP). For more information, see Using the Windows Headers. What OS are you targeting, and what value is being used for PROCESS_ALL_ACCESS? If it's an OS before Vista, and the value you are passing is 0xFFFF, this could be the cause of the problem.
2,285,900
2,285,920
Read and write bytes from a file (c++)
I think I probably have to use an fstream object but i'm not sure how. Essentially I want to read in a file into a byte buffer, modify it, then rewrite these bytes to a file. So I just need to know how to do byte i/o.
#include <fstream> ifstream fileBuffer("input file path", ios::in|ios::binary); ofstream outputBuffer("output file path", ios::out|ios::binary); char input[1024]; char output[1024]; if (fileBuffer.is_open()) { fileBuffer.seekg(0, ios::beg); fileBuffer.getline(input, 1024); } // Modify output here. outputBuffer.write(output, sizeof(output)); outputBuffer.close(); fileBuffer.close(); From memory I think this is how it goes.
2,285,915
2,285,934
non-static vs. static function and variable
I have one question about static and non-static function and variable. 1) non-static function access static variable. It's OK! class Bar { public: static int i; void nonStaticFunction() { Bar::i = 10; } }; int Bar::i=0; 2) non-static function access non-static variable Definitely OK! 3) static function access static variable&funciton Definitely OK! 4) static function access non-static function It's OK class Bar { public: static void staticFunction( const Bar & bar) { bar.memberFunction(); } void memberFunction() const { } } 5) static function access non-static variable It's OK or not OK? I am puzzled about this! How about this example class Bar { public: static void staticFunction( Bar & bar) { bar.memberFunction(); } void memberFunction() { i = 0; } int i; };
static function access non-static variable It's OK or not OK? I am puzzled about this! When called, a static function isn't bound to an instance of the class. Class instances (objects) are going to be the entities that hold the "non-static" variables. Therefore, from the static function, you won't be able to access them without actually being passed or storing elsewhere a specific instance to operate on. So yes, the code in your last example is valid, because you are passed in an instance. However, you could not do: static void staticFunction() { // error, this function is static, and is therefore // not bound to a specific instance when called i = 5; }
2,286,016
2,286,070
Why does c++ have its separate syntax for new & delete?
Why can't it just be regular function calls? New is essentially: malloc(sizeof(Foo)); Foo::Foo(); While delete is Foo:~Foo(); free(...); So why does new/delete end up having it's own syntax rather than being regular functions?
Here's a stab at it: The new operator calls the operator new() function. Similarly, the delete operator calls the operator delete() function (and similarly for the array versions). So why is this? Because the user is allowed to override operator new() but not the new operator (which is a keyword). You override operator new() (and delete) to define your own allocator, however, you are not responsible (or allowed to for that matter) for calling appropriate constructors and destructors. These function are called automatically by the compiler when it sees the new keyword. Without this dichotomy, a user could override the operator new() function, but the compiler would still have to treat this as a special function and call the appropriate constructor(s) for the object(s) being created.
2,286,130
2,286,170
Free Lightweight IDE/Text Editor for Windows - C++ Development
I have searched a lot for the exact development tool that fits my requirements, but could not find it anywhere. Here are my requirements: 1) Free. 2) Lightweight. (Eclipse is out). 3) Can handle a large project. 4) Input: Just the source tree, and possibly makefiles. No project/solution files. 5) Indexing - Auto Completion and "Go to Declaration/Definition". - Very Important. The only reason for not using Notepad++. 6) Good tabbed source editing with Highlighting with a nice GUI. No terminal editors for me. I do not need any other features like Code compilation, Debugging, etc. Used Notepad++ for the same project, but my requirement no. 5 is missing. It does have plugins, but they are a pain to use. I am currently using kscope on Linux over VMWare, and I found it to be exactly the perfect tool that I need, but VMWare is too slow, and too heavy for my machine. Can you suggest the perfect texteditor/IDE for me? Thank You.
Try Code::Blocks Highlights: * Open Source! GPLv3, no hidden costs. * Cross-platform. Runs on Linux, Mac, Windows (uses wxWidgets). * Written in C++. No interpreted languages or proprietary libs needed. * Extensible through plugins Compiler: * Multiple compiler support: o GCC (MingW / GNU GCC) o MSVC++ o Digital Mars o Borland C++ 5.5 o Open Watcom o ...and more * Very fast custom build system (no makefiles needed) * Support for parallel builds (utilizing your CPU's extra cores) * Multi-target projects * Workspaces to combine multiple projects * Inter-project dependencies inside workspace * Imports MSVC projects and workspaces (NOTE: assembly code not supported yet) * Imports Dev-C++ projects Debugger: * Interfaces GNU GDB * Also supports MS CDB (not fully featured) * Full breakpoints support: o Code breakpoints o Data breakpoints (read, write and read/write) o Breakpoint conditions (break only when an expression is true) o Breakpoint ignore counts (break only after certain number of hits) * Display local function symbols and arguments * User-defined watches (support for watching user-defined types through scripting) * Call stack * Disassembly * Custom memory dump * Switch between threads * View CPU registers Interface: * Syntax highlighting, customizable and extensible * Code folding for C++ and XML files. * Tabbed interface * Code completion * Class Browser * Smart indent * One-key swap between .h and .c/.cpp files * Open files list for quick switching between files (optional) * External customizable "Tools" * To-do list management with different users
2,286,162
2,290,869
Classes, Static Methods, or Instance Methods - Memory Consumption and Executable Size in Compiled Languages?
I keep wondering about this to try to improve performance and size of my Flex swfs, how do classes vs. static methods vs. instance methods impact performance and the final compiled "executable's" size? Thinking how it might be possible to apply something like HAML and Sass to Flex... Say I am building a very large admin interface with lots of components and views, and each of those components has a Skin object applied to them (thinking of the Spark Skinning Architecture for Flex). Now I want to add 10 different Effects to every skin (say there are 100 components on the screen, so that's 1000 instantiated effects). Is it better to: Have each Effect be a Class (BlurEffect, GlowEffect...), and add those 10 to the skin. Have all Effects be instance methods in one larger class, say "MultiEffect.as", and add that one class to the skin, referenced like multiEffect.glow(). Have all Effects be static methods in one singleton-esque "EffectManager.as" class, and just reference the effects in the skin via EffectManager.glow(this). So Multiple Effect Classes per skin, vs. One Effect class per skin, with instance methods, vs. One Effect class globally, with static methods How do those things impact memory and executable size (swf size in this example)? I know that classes are better OO practices and that static methods are slower than instance methods, and that Singletons are to be avoided, so it's not about performance necessarily. More about memory (which if smaller would be better in some cases), and file size.
Couldn't find such information for Flex, but for Java (which shouldn't be too different), object creation overhead is only 8 bytes of memory. That means if we're talking about 1000 instances, the overhead of using objects for each instance is at most 8K - negligible. If 100x more, it's still 800K which is still nothing. So, echoing the previous answers, choose the option that gives you a better design. Oh, and the difference in resulting file size is pretty much nothing.
2,286,207
2,286,358
Templates vs. Action Hierarchy
I'm creating a button class and am having a hard time deciding between 2 solutions. 1) Templatize the Button class and have it take a function object in its constructor to call when the button is pressed. The guy I'm coding with is worried that this will lead to code bloat/thrashing. 2) Create a ButtonAction base class, and there will be a different ButtonAction for each button. Thus the Button class takes a ButtonAction in its constructor to call when the button is pressed. We've also considered the use of function pointers, but haven't thought it through that thoroughly.
You could use boost::function<> objects for your actions. This way you don't need any templates and the button class becomes very flexible: struct Button { typedef boost::function<void ()> action_t; action_t action; Button(const action_t &a_action) : action(a_action) { } void click() { action(); } }; This way the class is easy to use with function pointers, functor objects or things like boost::bind: void dosomething(); Button b1 = Button(&dosomething); struct SomeAction { void operator()() {} }; Button b2 = Button(SomeAction());
2,286,298
2,286,445
how to use processor registers in visual studio?
i'm trying to write a program that solves the rsa challenge (yes i have interesting goals) and currently i don't have a 64 bit linux box and i don't really wanna spend my time writing a program that doesn't have a chance to ever finish. so while i can do some assembler programming, i would prefer using C++. however, i would also be interested in how to use inline assembly to do the same thing. the plan here is to use the 16 64 bit general purpose registers and the 128 bit sse registers to do (really really long) integer math. so any help on how to do that would be greatly appreciated.
Based on your comment to BarsMonsters anser, you don't need to get closer to the CPU, you need a large integer library. One option is gmp, which includes arbitrary integer arithmetic. It has good algorithms for things like multiplying large integers, and a good compiler will do a better job of optimising this than most people. The main issue that might make you look for an alternative is that it supports variable precision arithmetic, which may be an overhead you'd rather avoid if you know for sure that your numbers have at most 512 binary digits. Even so, you probably want to look at algorithms more than low-level tricks (long multiplication may already be a bad choice at that size), and I'm pretty confident you'll be better off letting the compiler do your optimisation. My advice - spend your time doing the things that require human intelligence, not the things that a machine can do far more consistently and a billion times faster. And if you really can optimise machine code better than a compiler can, download LLVM and implement that logic as an optimisation pass so we can all get the benefit ;-)
2,286,430
2,286,462
Inserting a std::list element to std::list
std::list <std::list <int>> mylist; std::list <int> mylist_; mylist_.push_back(0); mylist.push_back(mylist_); is it possible to insert a sub-list into the list (mylist) without creating the temporary local sub-list (mylist_) and would it be better to use the type (sub-list) as pointer in list (mylist) in terms of performance?
You can't really do it without temporaries, but you can do it more concisely: mylist.push_back(std::list<int>(1, 0)); // insert 1 element with value 0 As JonM notes, the temporary will probably be optimized away by any decent compiler. You can use arrays: int vals[] = { 1, 2, 3, 4 }; mylist.push_back(std::list<int>(vals, vals+sizeof(vals)/sizeof(vals[0]))); Utilities like Boost.Assign ease that: mylist.push_back(boost::assign::list_of(1)(2)(3)); Performance-wise it depends on what you want to do - if you e.g. expect the lists to be handed around much, use (preferrably smart) pointers to avoid endless copying.
2,286,640
2,286,918
Boost regular expressions
Does anyone know of any good tutorials on regular expressions using boost? I have been searching for a decent one, but it seems most are for people who know a little about regular expressions
You may want to look at sections 23.6, 23.7, 23.8, and 23.9 (pp. 830-849) of Bjarne's Stroustrup's new book: Programming: Principles and Practice using C++ Just like the rest of the book, these sections are very pedagogical and assume essentially zero background on regular expressions.
2,286,794
2,292,046
Network programming using C++
How can we do network programming in C++ similar to Remoting in .NET? Please help with any tutorials. It would be fine if I know how to enable two computers to communicate in the form of sending and receiving messages using C++/C#. Thanks, Rakesh.
Check out our C++ Remoting framework. There's also a screencast showing how to use it. This is probably the closest that you'll get to .NET Remoting in C++.
2,286,890
2,286,894
getting input numbers from the user
How can I get input from the user if they are to separate their inputs by whitespace (e.g. 1 2 3 4 5) and I want to put it in an array? Thanks. Hmmmm. I see most of the responses are using a vector which I guess I'll have to do research on. I thought there would be a more simpler, yet possibly messier response since we haven't covered vectors like using sscanf or something. Thanks for the inputs.
#include <vector> #include <iostream> using namespace std; int main() { vector<int> num; int t; while (cin >> t) { num.push_back(t); } }
2,286,991
2,287,034
C++ Two Dimensional std::vector best practices
I am building an app that needs to have support for two dimensional arrays to hold a grid of data. I have a class Map that contains a 2d grid of data. I want to use vectors rather than arrays, and I was wondering what the best practices were for using 2d vectors. Should I have a vector of vectors of MapCells? or should it be a vector of vectors of pointers to MapCells? or references to MapCells? class Map { private: vector<vector<MapCell>> cells; public: void loadMap() { cells.clear(); for (int i = 0; i < WIDTH; i++) { //How should I be allocating these? vector<MapCell> row(HEIGHT); for (int j = 0; j < HEIGHT; j++) { //Should I be dynamically allocating these? MapCell cell; row.push_back(cell); } cells.push_back(row); } } } Basically what way of doing this is going to get me in the least amount of trouble (with respect to memory management or anything else)?
When you want a square or 2d grid, do something similar to what the compiler does for multidimensional arrays (real ones, not an array of pointers to arrays) and store a single large array which you index correctly. Example using the Matrix class below: struct Map { private: Matrix<MapCell> cells; public: void loadMap() { Matrix<MapCell> cells (WIDTH, HEIGHT); for (int i = 0; i < WIDTH; i++) { for (int j = 0; j < HEIGHT; j++) { // modify cells[i][j] } } swap(this->cells, cells); // if there's any problem loading, don't modify this->cells // Matrix swap guarantees no-throw (because vector swap does) // which is a common and important aspect of swaps } }; Variants of matrix classes abound, and there are many ways to tailor for specific use. Here's an example in less than 100 lines that gets you 80% or more of what you need: #include <algorithm> #include <memory> #include <vector> template<class T, class A=std::allocator<T> > struct Matrix { typedef T value_type; typedef std::vector<value_type, A> Container; Matrix() : _b(0) {} Matrix(int a, int b, value_type const& initial=value_type()) : _b(0) { resize(a, b, initial); } Matrix(Matrix const& other) : _data(other._data), _b(other._b) {} Matrix& operator=(Matrix copy) { swap(*this, copy); return *this; } bool empty() const { return _data.empty(); } void clear() { _data.clear(); _b = 0; } int dim_a() const { return _b ? _data.size() / _b : 0; } int dim_b() const { return _b; } value_type* operator[](int a) { return &_data[a * _b]; } value_type const* operator[](int a) const { return &_data[a * _b]; } void resize(int a, int b, value_type const& initial=value_type()) { if (a == 0) { b = 0; } _data.resize(a * b, initial); _b = b; } friend void swap(Matrix& a, Matrix& b) { using std::swap; swap(a._data, b._data); swap(a._b, b._b); } template<class Stream> friend Stream& operator<<(Stream& s, Matrix const& value) { s << "<Matrix at " << &value << " dimensions " << value.dim_a() << 'x' << value.dim_b(); if (!value.empty()) { bool first = true; typedef typename Container::const_iterator Iter; Iter i = value._data.begin(), end = value._data.end(); while (i != end) { s << (first ? " [[" : "], ["); first = false; s << *i; ++i; for (int b = value._b - 1; b; --b) { s << ", " << *i; ++i; } } s << "]]"; } s << '>'; return s; } private: Container _data; int _b; };
2,287,114
2,287,187
Thread type for background drawing to a bitmap in MFC
I have a MFC document/view C++ graphics application that does all its drawing to an off screen bitmap, and then copys that to the supplied CDC pointer in the OnDraw method. Over the last couple of days I've been looking to place the drawing component in a seperate worker thread, so it doesn't stall the GUI. I seem to get a fair number of MFC GDI related asserts firing when I do this, e,g, VERIFY(::MoveToEx(m_hAttribDC, x, y, &point) So a few questions; Are there any problems with using worker threads with MFC & GDI? Are there issues using MFC GDI objects across threads? Do GDI objects have to be declared locally to a thread? While it is possible the issue is resource/locking related, the drawing thread has its own provate CDC and CBitmap that it uses for all the drawing, and only copies the bitmap back to the main thread when it hasz excludive access via a mutex. The code has also been tested by direct calling rather than as a seperate thread to prove the problem does relate to threading.
Device contexts can be used by any thread (the only thing you must be aware of is that the thread which did the GetDC should also call ReleaseDC), but are not inherently thread safe. You have to ensure that only one caller is accessing the DC at any given point in time, but you seem to have taken care of that, from what you write. What do you mean by Do GDI thread have to be declared locally to a thread ? They must be allocated and freed in the same thread, but they can be created/used in any thread. Once again, you are responsible not to use such a resource from two threads simultaneously. You should probably check the series of posts from Raymond Chen on the subject: Thread affinity of user interface objects, part 1: Window handles Thread affinity of user interface objects, part 2: Device contexts Thread affinity of user interface objects, part 3: Menus, icons, cursors, and accelerator tables Thread affinity of user interface objects, part 4: GDI objects and other notes on affinity Thread affinity of user interface objects, part 5: Object clean-up and be sure that you don't link to the single threaded versions of the C/MFC libraries.
2,287,121
2,287,145
How to read groups of integers from a file, line by line in C++
I have a text file with on every line one or more integers, seperated by a space. How can I in an elegant way read this with C++? If I would not care about the lines I could use cin >>, but it matters on which line integers are. Example input: 1213 153 15 155 84 866 89 48 12 12 12 58 12
It depends on whether you want to do it in a line by line basis or as a full set. For the whole file into a vector of integers: int main() { std::vector<int> v( std::istream_iterator<int>(std::cin), std::istream_iterator<int>() ); } If you want to deal in a line per line basis: int main() { std::string line; std::vector< std::vector<int> > all_integers; while ( getline( std::cin, line ) ) { std::istringstream is( line ); all_integers.push_back( std::vector<int>( std::istream_iterator<int>(is), std::istream_iterator<int>() ) ); } }
2,287,212
2,287,232
How to convert UTF-8 <-> UTF16 portable
is there a simple, portable way (win32, linux at least) to convert UTF-16 to UTF-8 and back? Preferably using boost. Thx for your help, Tobias
Both libiconv and icu can do this.
2,287,318
2,287,393
Using C++/Qt4 application as backend for web application
for one of my applications I'd like to provide a minimal web interface. This core application is written in C++ and uses Qt4 as a framework. Since I'm also using some libraries I wrote to calculate some things and do some complex data management, I'd like to use this existing code as a backend to the web interface. Idea 1: Using an embedded web server The first thing I tried (and which worked to some degree) was using an embedded web server (mongoose). As you can imagine, it is just a very thin library and you have to implement a lot of things yourself (like session management, cookies, etc.). Idea 2: Using a normal web server and adding a fcgi/cgi/scgi backend to my application The next thing that came to my head was using a mature but compact web server (for instance, lighttpd) and simple provide a fcgi/scgi/cgi backend to it. I could write the web application using a good framework, like Pylons, PHP, or RoR, (...) and simply have an URL prefix, like /a/... which allows me to directly talk to the backend. I tried to implement the libfcgi into my application, but it looks messier than needed (for instance you'd have to implement your own TCP/IP sockets to pass on data between your app and the web server and tunnel it through the FCGI library, meh) Idea 3: Creating a command line version of my application which does the most basic things and use a normal web server and framework to do the rest This is the third idea that came to my head. It is basically about creating a web application using a traditional way (PHP, RoR, etc.) and using a command line version of my application to process data and return it when needed. I've got some experience with creating web applications, but I never had to do something like this, so I'd like to hear some ideas or suggestions. I'd like to use JavaScript on the browsers (AJAX, that is) and pass some JSON constructs between web browser and server to make the user experience a bit smoother. So what are your suggestions, ideas on this? I don't want to re-invent the wheel, honestly.
I would never expose a custom written application to the net as front-end, for that servers like apache or lighthttp are build. They give you some serious security out of the box. As for interaction of your app with that webserver, it depends a bit on the load and what kind of experience you have with writing software in PHP, python or other languages supported by your web server (via interpreter of course). A slight load, and a command line tool accessed from PHP might do perfectly well. A more heavy load and you might wish to implement a simple (SOAP?) server with Qt and access that from a python (or php) script. That way you don't need to do layout in you app, and you also don't need to implement security all that much.
2,287,442
2,287,458
Use of Mutex between a c# exe and an c++ dll
Is it possible to use a Mutex Object for a application which users c++ dll to do background work and a c# to display it. Bot these use a common resource ie db . So can Mutex be used to lock this resource. In my db c++ will insert to db and c# will read it.
There is a thing called "named mutex", which is OS object and can be shared between different libraries and applications, only by specifying its name on creation/use.Refer to http://msdn.microsoft.com/en-us/library/ms682411%28VS.85%29.aspx
2,287,451
4,684,224
How to perform atomic operations on Linux that work on x86, arm, GCC and icc?
Every Modern OS provides today some atomic operations: Windows has Interlocked* API FreeBSD has <machine/atomic.h> Solaris has <atomic.h> Mac OS X has <libkern/OSAtomic.h> Anything like that for Linux? I need it to work on most Linux supported platforms including: x86, x86_64 and arm. I need it to work on at least GCC and Intel Compiler. I need not to use 3rd par library like glib or qt. I need it to work in C++ (C not required) Issues: GCC atomic builtins __sync_* are not supported on all platforms (ARM) and are not supported by the Intel compiler. AFAIK <asm/atomic.h> should not be used in user space and I haven't successfully used it at all. Also, I'm not sure if it would work with Intel compiler. Any suggestions? I know that there are many related questions but some of them point to __sync* which is not feasible for me (ARM) and some point to asm/atomic.h. Maybe there is an inline assembly library that does this for GCC (ICC supports gcc assembly)? Edit: There is a very partial solution for add operations only (allows implementing atomic counter but not lock free-structures that require CAS): If you use libstc++ (Intel Compiler uses libstdc++) then you can use __gnu_cxx::__exchange_and_add that defined in <ext/atomicity.h> or <bits/atomicity.h>. Depends on compiler version. However I'd still like to see something that supports CAS.
Projects are using this: http://packages.debian.org/source/sid/libatomic-ops If you want simple operations such as CAS, can't you just just use the arch-specific implementations out of the kernel, and do arch checks in user-space with autotools/cmake? As far as licensing goes, although the kernel is GPL, I think it's arguable that the inline assembly for these operations is provided by Intel/AMD, not that the kernel has a license on them. They just happen to be in an easily accessible form in the kernel source.
2,287,506
2,287,626
Getting location of a file: network or local
What is the easiest way in Windows to get the location of a file? I have a filename that was returned to me by the Windows function GetModuleName (returns the full name of a module (exe or dll)), and which could be in any valid filename format, e.g. myfile.dll c:\windows\myfile.dll \?\c:\windows\myfile.dll (or something like this) x:\bin\myfile.dll \myserver\myshare\myfile.dll What is the easiest way to know whether the path refers to a local drive or to a network drive?
GetFullPathName() will help normalize the path name. I don't think you need it though. You'd want to go through the handle. So call CreateFile(), get a handle, then call e.g. GetFinalPathNameByHandle(VOLUME_NAME_GUID) This works because network drives don't have volume GUIDs.