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
1,364,603
1,364,631
Performance of comparisons in C++ ( foo >= 0 vs. foo != 0 )
I've been working on a piece of code recently where performance is very important, and essentially I have the following situation: int len = some_very_big_number; int counter = some_rather_small_number; for( int i = len; i >= 0; --i ){ while( counter > 0 && costly other stuff here ){ /* do stuff */ --counter; } /* do more stuff */ } So here I have a loop that runs very often and for a certain number of runs the while block will be executed as well until the variable counter is reduced to zero and then the while loop will not be called because the first expression will be false. The question is now, if there is a difference in performance between using counter > 0 and counter != 0? I suspect there would be, does anyone know specifics about this.
Do you think that what will solve your problem! :D if(x >= 0) 00CA1011 cmp dword ptr [esp],0 00CA1015 jl main+2Ch (0CA102Ch) <---- ... if(x != 0) 00CA1026 cmp dword ptr [esp],0 00CA102A je main+3Bh (0CA103Bh) <----
1,364,793
1,364,815
Initializing arrays in C++
I'm trying to initialize the last element in the array int grades[10]; to grade 7 but it doesn't seem to work I'm using C++ btw
If you want to initialize them all at definition: int grades[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 7 }; If you want to initialize after: int grades[10]; grades[9] = 7; But, be aware that grades 0..8 will still be uninitialized, and will likely be junk values.
1,364,837
1,364,878
Why doesn't this C++ template code compile?
Does anyone know why this will not compile? I've tried both VS 2008 and GCC 4.something and both spit out errors. It doesn't matter whether or not I'm referencing "ThisFunctionDoesNotCompile()". I can workaround this by just passing 'InternalType' as a second template parameter to Base, but I'm still curious why this comes up as an error. #include <iostream> using namespace std; class DataClass { public: int m_data; }; template<typename DerivedType> class Base { public: int ThisFunctionCompiles() { // No problems here. typename DerivedType::InternalType temp; temp.m_data = 5; return temp.m_data; } // error C2039: 'InternalType' : is not a member of 'Derived<InInternalType>' typename DerivedType::InternalType ThisFunctionDoesNotCompile() { return static_cast<DerivedType*>(this)->GetInternalData(); } }; template<typename InInternalType> class Derived : public Base<Derived<InInternalType> > { public: typedef InInternalType InternalType; InternalType GetInternalData() { return m_internalData; } private: InternalType m_internalData; public: void SetInternalData( int newVal ) { m_internalData.m_data = newVal; } }; int main() { Derived<DataClass> testDerived; testDerived.SetInternalData( 3 ); cout << testDerived.GetInternalData().m_data << endl; cout << testDerived.ThisFunctionCompiles() << endl; // The compiler gives an error regardless of whether or not this is commented out. //cout << testDerived.ThisFunctionDoesNotCompile().m_data << endl; return 0; } These are the errors I get in VS 2008: 1>e:\test\generaltestprogram\generaltestprogram\main.cpp(27) : error C2039: 'InternalType' : is not a member of 'Derived<InInternalType>' 1> with 1> [ 1> InInternalType=DataClass 1> ] 1> e:\test\generaltestprogram\generaltestprogram\main.cpp(35) : see reference to class template instantiation 'Base<DerivedType>' being compiled 1> with 1> [ 1> DerivedType=Derived<DataClass> 1> ] 1> e:\test\generaltestprogram\generaltestprogram\main.cpp(58) : see reference to class template instantiation 'Derived<InInternalType>' being compiled 1> with 1> [ 1> InInternalType=DataClass 1> ] 1>e:\test\generaltestprogram\generaltestprogram\main.cpp(27) : error C2146: syntax error : missing ';' before identifier 'ThisFunctionDoesNotCompile' 1>e:\test\generaltestprogram\generaltestprogram\main.cpp(27) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 1>e:\test\generaltestprogram\generaltestprogram\main.cpp(28) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 1>e:\test\generaltestprogram\generaltestprogram\main.cpp(28) : warning C4183: 'ThisFunctionDoesNotCompile': missing return type; assumed to be a member function returning 'int' And these are what GCC gives me: main.cpp: In instantiation of 'Base<Derived<DataClass> >': main.cpp:96: instantiated from 'Derived<DataClass>' main.cpp:119: instantiated from here main.cpp:88: error: no type named 'InternalType' in 'class Derived<DataClass>'
At the time that the templated class Base is instantiated as a parent of the class Derived, the class Derived is not a complete type. Since Base<Derived<DataClass> > is a parent class of Derived<DataClass>, it must be instantiated before Derived<DataClass> can be instantiated. So when the class Base<Derived<DataClass> > is built from the template, Derived<DataClass> behaves as if it were a forward declaration. And as you're probably aware, you can't reference members of incomplete types, nor can your forward-declare nested types, so you're out of luck here. This, by the way, is why it's difficult to implement a properly covariant clone() method using templates. See here and here (mine).
1,364,953
1,364,975
global variable not printing correctly in visual studio
I am playing around with some recursion, and trying to count the number of additions in a recursive fib function (code below). The problem is, g_add never gets printed as anything but zero (0). In the debugger it is set correctly, but it wont print correctly. In fact, the code below is modified a bit, to sanity check that everything else is OK. In real life, g_add is set to zero initially, not to the 10 below, but look at the output is printing... volatile int g_add = 10; int rfib(int n) { if(n == 0) return 0; else if(n == 1) return 1; else { ++g_add; return rfib(n-1) + rfib(n-2); } } int _tmain(int argc, _TCHAR* argv[]) { printf("Fib: %d\n", g_add); for(int n =0; n<6;n++,g_add = 0) { printf("Fib %d is: %d - additions: %d\n", n, rfib(n), g_add); } } And the output: Fib: 10 Fib 0 is: 0 - additions: 10 Fib 1 is: 1 - additions: 0 Fib 2 is: 1 - additions: 0 Fib 3 is: 2 - additions: 0 (note, the debugger says it is 1) Fib 4 is: 3 - additions: 0 Fib 5 is: 5 - additions: 0 Any thoughts on why g_add is not being printed correctly? And what I could do about it? I have tried with and without the volatile keyword. I think this might be related to the VS environment, rather than C++ so, I tagged both.
You're assuming the order in which the parameters are evaluated. Use this instead: int fib = rfib(n); printf("Fib %d is: %d - additions: %d\n", n, fib, g_add);
1,365,206
1,365,280
Should the "this" pointer and smart pointers be mixed?
How should I avoid using the "this" pointer in conjunction with smart pointers? Are there any design patterns/general suggestions on working around this? I'm assuming combining the two is a no-no since either: you're passing around a native pointer to a smart pointer-managed object which defeats the point of using the smart pointers in the first place, if you wrap the "this" pointer in a smart pointer at use, e.g. "return CSmartPtr(this);", you've effectively set up multiple smart pointers managing the same object so the first one to have a reference count of zero will destroy the object from under the other, or if you have a member variable holding the value of CSmartPtr(this) to return in these cases, it'll ultimately be a circular reference that results in the reference count always being one. To give a bit of context, I recently learned about the negative implications of combining STL containers with objects (repeated shallow copying, slicing when using containers of a base class, etc), so I'm replacing some usage of these in my code with smart pointers to the objects. A few objects pass around references to themselves using the "this" pointer, which is where I'm stuck. I've found smart pointers + “this” considered harmful? asked on a somewhat similar problem, but the answer isn't useful as I'm not using Boost. Edit: A (very contrived) example of what I'd been doing would be ...::AddToProcessingList(vector<CSmartPtr> &vecPtrs) { vecPtrs.push_back(CSmartPtr(this)); }
Combining the two can be done, but you always need to keep clear in your mind about the ownership issues. Generally, the rule I follow is to never convert a raw pointer to a smart pointer (with ownership), unless you are sure that you are taking ownership of the object at that point. Times when this is safe to do should be obvious, but include things like: you just created the object (via new) you were passed the object from some external method call where the semantic is obviously one of ownership (such as an add to a container class) the object is being passed to another thread As long as you follow the rule, and you don't have any ambiguous ownership situations, then there should be no arising issues. In your examples above, I might look on them as follows: you're passing around a native pointer to a smart pointer-managed object which defeats the point of using the smart pointers in the first place In this case, since you are passing around the native pointer, you can assume by my rule that you are not transferring ownership so you can not convert it to a smart pointer if you wrap the "this" pointer in a smart pointer at use, e.g. "return CSmartPtr(this);", you've effectively set up multiple smart pointers managing the same object so the first one to have a reference count of zero will destroy the object from under the other This is obviously illegal, since you have said that the object is already owned by some other smart pointer. if you have a member variable holding the value of CSmartPtr(this) to return in these cases, it'll ultimately be a circular reference that results in the reference count always being one. This can actually be managed, if some external code implicitly owns the member variable - this code can call some kind of close() method at some point prior to the object being released. Obviously on reflection, that external code owns the object so it should really have a smart pointer itself. The boost library (which I accept you have said you are not using) makes these kind of issues easier to manage, because it divides up the smart pointer library along the different types of ownership (scoped, shared, weak and so on).
1,365,247
1,366,320
How should smart pointers get down casted?
Do smart pointers handle down casting, and if not what is a safe way of working around this limitation? An example of what I'm trying to do is having two STL vectors (for example) containing smart pointers. The first contains smart pointers to a base class while the second contains smart pointers to a derived class. The smart pointers are referenced counted, e.g. similar behaviour to Boost's shared_ptrs, but hand-rolled. I've included some sample code that I whipped up to provide an example: vector<CBaseSmartPtr> vecBase; vector<CDerivedSmartPtr> vecDer; ... CBaseSmartPtr first = vecBase.front(); vecDer.push_back(CDerivedSmartPtr(dynamic_cast<CDerived*>(first.get())); This seems not safe to me, as I think I'm ending up with two smart pointers managing the same object. At some point down the track this is probably going to result in one of them freeing the object while the other still holds references to it. What I'd hope for but don't think will work is a straight down-cast while keeping the same object, e.g. dynamic_cast<CDerivedSmartPtr>(first) Should I be looking to change the second container to also use CBaseSmartPtr and downcast on usage only? Are there other solutions?
Smart pointers can handle downcasting, but it's not automatic. And getting const-correctness in can be a bit complex (I've used our smart pointer implementation in interview questions, there's some template trickery involved). But many users of smart pointers never instantiate their smart pointers with const-qualified types anyway. The first thing you need to get correct is the counter. Since you may need to share a counter between smart_ptr<Base> and smart_ptr<Derived>, the counter type should not depend on the type argument. In general, this is not a big deal anyway. A counter is merely a size_t, probably wrapped in a class. (Note: there are alternative smart pointer designs, but the question strongly suggests a counter is used) A cast towards base should be fairly trivial. Hence, your smart_ptr should have a constructor taking a smart_ptr. In this ctor, add a line static_cast<T*>((U*)0);. This doesn't generate code, but prevents instantiation when T is not a base of U (modulo const qualifications). The other way around should be an explicit cast. You can't programatically enumerate all bases of T, so smart_ptr<T> cannot derive from smart_ptr<Base1_of_T>, smart_ptr<Base2_of_T>, ... Hence, a dynamic_cast<smart_ptr<T> > won't work. You can provide your own smart_dynamic_cast<SPT>(smart_ptr<U> const& pU). This is best implemented as a function returing an SPT. In this function, you can simply do a return SPT(dynamic_cast<SPT::value_type*>(&*pU)).
1,365,291
1,365,304
keep cmd open while running a file
I'm learning C++ and I'm using Visual C++ Express and while running this #include <stdio.h> int main() { printf("Hello, World!\n"); return 0; } the cmd window closes so fast, I can't see Hello World is there anyway to prevent this?
If you press Control + F5, you won't be attached with a debugger - however, it'll stay open with a "Press any key to continue" style message.
1,365,317
1,365,329
Print to console without flooding in C++
My apologies for an inaccurate title, but I'm not sure what this is called exactly. How would one print to the console a single, updating line? For example, if I wanted to print a percent completion status every cycle but not flood the console with steams of text, how would I accomplish this? (What is this called? -- for future Googling) Thank you!
There is no portable way to clean the screen though there is a simple way to return to the beginning of the line using \r then overwriting what we wrote before. I am using Sleep from Windows API: #include <iostream> #include <windows.h> using namespace std; int main() { for(int i = 1; i <= 10; i++) { std::cout << i*10 << '%'; std::cout.flush(); // see wintermute's comment Sleep(1000); std::cout << '\r'; } }
1,365,662
1,365,718
Can't link libpqxx in MinGW
Using MSYS, I compiled libpq (from compiling postgres). I then compiled libpqxx. Now, I want to create a client that will use libpqxx. libpq seemed to work fine. And, I can compile code with libpqxx. However, linking the libpq client application fails. Here's my code: #include <pqxx/pqxx> #include <iostream> using namespace std; using namespace pqxx; int main() { connection Conn("dbname=test"); cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!! return 0; } I added a bunch of libs to the link in a vain hope it would suddenly work. Here's what I have so far: g++ -IC:\msys\1.0\local\pgsql\include -IC:\msys\1.0\local\include -O0 -g3 -Wall -c -fmessage-length=0 -osrc\Controller.o ..\src\Controller.cpp g++ -LC:\MinGW\lib -LC:\msys\1.0\local\pgsql\lib -LC:\msys\1.0\local\lib -oController.exe src\Controller.o -lws2_32 -lole32 -lpqxx -lpq -loleaut32 -luuid C:\msys\1.0\local\lib/libpqxx.a(connection_base.o): In function `ZN45_GLOBAL__N__ZN4pqxx16encrypt_passwordERKSsS1_7wait_fdEibP7timeval': C:/msys/1.0/home/rsolomon/libpqxx/libpqxx-3.0.2/src/connection_base.cxx:1434: undefined reference to `select@20' C:\msys\1.0\local\lib/libpqxx.a(connection_base.o): In function `ZN4pqxx15connection_base12check_resultERKNS_6resultE': C:/msys/1.0/home/rsolomon/libpqxx/libpqxx-3.0.2/src/connection_base.cxx:420: undefined reference to `select@20' collect2: ld returned 1 exit status Build error occurred, build is stopped Time consumed: 1770 ms. I'm thinking the -lws2_32 should've gave me the "select@20". Why is the linker so uppity?
The Unix linker traditionally processes libraries from left to right. So it first considers ws2_32, finds that it has not much use, then goes on to pqxx, and sees that select is undefined and doesn't get defined by any of the later libraries. IOW, try moving ws2_32 to the end of the command line.
1,365,711
2,201,866
pthread thread state
Is there a mechanism that I can use to tell if a pthread thread is currently running, or has exited? Is there a method for pthread_join() that is able to timeout after a specific period of time if the thread has not yet exited?
I just ended up wrapping the thread in a C++ class and keeping a state variable around that could be checked later.
1,365,729
1,365,750
making an exe low priority
How do I run a .exe as low priority? I know I can go to task manager, and change the priority setting there manually, but is there a way that I can launch the .exe from a .bat file with a command to make the .exe run at a given priority (in this case low)? The .exe is a program that I've written in C++; can I set the priority in C++ code? I am running windows xp.
In a batch file, you can use the start command: Starts a separate window to run a specified program or command. START ["title"] [/D path] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED] [/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL] [/AFFINITY <hex affinity>] [/WAIT] [/B] [command/program] [parameters] [ . . . ] LOW Start application in the IDLE priority class NORMAL Start application in the NORMAL priority class HIGH Start application in the HIGH priority class REALTIME Start application in the REALTIME priority class ABOVENORMAL Start application in the ABOVENORMAL priority class BELOWNORMAL Start application in the BELOWNORMAL priority class
1,366,095
1,366,475
Game engine development question
I am thinking of making a simple game engine for my course final year project. I want it to be modular and expandable so that I can add new parts if I have time. For example I would make a graphics engine that would be completely independent of the other systems, once that was finished I could add a physics engine etc. I would also want to make a tool set to go with this engine. For the tools I would like to use C# but I am not sure about the libraries. My question is, if I want a C# GUI program, can I reference a library written in C++? Also would there be any performance problems etc. if I made some of the libraries in C# but wanted to use them from a C++ game. I would like to avoid C++ as much as possible, my experiences have shown that development time can be a lot higher for a project over that of using C# or Java etc. My graphics development would be in OpenGL, this is all I have been taught. We have only done this in C++ but I have seen that projects such as SharpGL allow for the development with C#. Is there any performance issues with this. I am not looking for a blindingly fast, top graphics game. It will most likely be something simple to show my engine working. My engine probably won't be that great either as I only have a year and am working on my own. Any advice on this would be appreciated. I am still really in the planning stages so it wouldn't be too much work to completely change what I want to do. I would just like to preempt any major problems I might have. Thanks
If you can pull this off even under a relaxed set of goals, you're set for a great project. First, you need to get a grasp of scope: How long do you have to work on the project? How many people are working on the project? If you can only create one "piece of the pie" on your own, which one would you pick? Use this to establish a working plan to make sure if you don't get as far as you'd like, you still have enough to make the work show as a great project. A game engine is a big development task. A game engine with a toolchain is an enormous development task. In a lot of ways, choosing a smaller but more challenging task is preferable because it shows higher-level thinking about problem solving, which is greatly preferred by academics - double that if you are CS and not [Area of] Engineering. Since you are working in managed languages, things you may want to consider are: Expressing gameplay logic (rules of the game) in a clean manner so as to provide an efficient and reliable path from designer->developer->tester. If you want, this could absolutely include the manner in which you describe the rules (Custom editor? Code API? DSL?) Game AI has no shortage of extremely challenging problems. Physics and graphics are interesting and I believe managed languages will eventually be used in these areas, but you may find yourself a bit more limited in your ability to solve these problems. If I were going to work in this area now, I would be trying to answer: "If I could use a managed language for writing [graphics|physics] code without hurting performance, what kinds of [language|runtime] features make the most difference in improving the expressiveness, correctness, maintainability, and reliability of the resulting programs." This goes way past simply having garbage collection and pointer safety.
1,366,148
1,366,170
Terminate Excel Application using OLE
How can I mannually terminate an excel application using OLE Automation? I would like to do this in some exception handling so that an excel process does not remain running if a function throws an error. Currently I use the below code to open excel: Variant excel = Variant::CreateObject("Excel.Application");
Like this: OleVariant excel; excel = Variant::CreateObject("Excel.Application"); // // Your code // excel.OleProcedure("Quit");
1,366,217
32,269,026
Check if Outlook is installed on PC
Is there a way that I could programatically detect if Microsoft Outlook (any version of it) is installed on the PC. I have to do it in unmanaged c++.
At MSDN is an example of how to detect Outlook version (or if Outlook is installed at all). Below is a prettified version of that example: #include <Windows.h> #include <Msi.h> #include "stdafx.h" static int compareOutlookVersion(const TCHAR* exe) { const TCHAR outlookRegister[][MAX_PATH] = { TEXT("{E83B4360-C208-4325-9504-0D23003A74A5}"), // Outlook 2013 TEXT("{1E77DE88-BCAB-4C37-B9E5-073AF52DFD7A}"), // Outlook 2010 TEXT("{24AAE126-0911-478F-A019-07B875EB9996}"), // Outlook 2007 TEXT("{BC174BAD-2F53-4855-A1D5-0D575C19B1EA}") // Outlook 2003 }; const int outlookVersions[] = { 2013, 2010, 2007, 2003 }; DWORD pathLength = 0; for (int i = 0; i < (sizeof(outlookVersions) / sizeof(outlookVersions[0])); i++) if (ERROR_SUCCESS == MsiProvideQualifiedComponent( outlookRegister[i], exe, (DWORD) INSTALLMODE_DEFAULT, NULL, &pathLength )) { return outlookVersions[i]; } return 0; } int getOutlookVersion(int* bits) { int version; *bits = 32; version = compareOutlookVersion(TEXT("outlook.exe")); if (version) { return version; } *bits = 64; version = compareOutlookVersion(TEXT("outlook.x64.exe")); if (version) { return version; } *bits = 0; return 0; // No Outlook found. } int _tmain(int argc, _TCHAR* argv[]) { HRESULT result; int version; int bits; version = getOutlookVersion(&bits); if (version) { printf("Outlook %d, %d bit\n", version, bits); } else { printf("No Outlook found.\n"); } return 0; }
1,366,232
1,366,741
How many render targets do low end Pixel Shader 2.0 supporting video cards support?
MRT allows for rendering to multiple texture targets in the pixel shader, but I'm not sure how many targets that is. I'm currently using 3 render targets but I may need as much as 5 (though probably just 4). I think the Radeon 9500s are pretty much entry level ps/vs 2.0 cards but I'm really not sure how many render targets it actually supports besides the fact it supports them? Thanks for any help!
Non definitive answer: ATI R600 and above have up to 8 (Earlier cards, 9x00 and up also have MRT, but I'm not sure how many) NVidia 6x00 and above have up to 4 (I thought G80+ was supposed to do 8, but mine says only 4) The number for your current card is in the DX Caps member "NumSimultaneousRTs" I's say 4 is probably the safe bet. If you need more you may want to consider rejigging/encoding the data till it fits in 4, since bandwidth is still always a worry :-)
1,366,277
1,366,283
C++: Confusing declaration semantics
After trying my hand at Perl and a little bit of C, I am trying to learn C++ and already i am bogged down by the details and pitfalls. Consider this:- int x = 1; { int x = x; // garbage value of x } int const arr = 3; { int arr[arr]; // i am told this is perfectly valid and declares an array of 3 ints !! } Huh, Why the difference ? To Clarify: Use of the same name is valid in one case and invalid in another.
Welcome to the universe of C++! For your question, the answer lay in a concept called 'Point-of-declaration'. >>int x = 1; >>{ int x = x; } // garbage value of x From Section:-3.3.1.1 (C++ Standard Draft) The point of declaration for a name is immediately after its complete declarator and before its initializer (if any), except as noted below. int x = 12; { int x = x; } Here; the 'operator =' is the initializer. You can say that the point-of-declaration for 'x' is not yet reached, so the value of 'x' is indeterminate. >>int const arr = 3; >>{ int arr[arr]; } // i am told this is perfectly valid and declares an array of 3 ints !! Why? From Section:-3.3.1.4 (C++ Standard Draft) A nonlocal name remains visible up to the point of declaration of the local name that hides it. Here the point of declaration is reached at ';' character. So the earlier visible value of 'arr' is used i.e. = 3. Also, you may wish to know that the following is valid :- const int e = 2; { enum { e = e }; } // enum e = 2 From Section:-Chapter-3.3.1.4 (C++ Standard Draft):- The point of declaration for an enumerator is immediately after its enumerator-definition. But, don't do this const int Spades = 1, Clubs = 2, Hearts = 3, Diamonds = 4; enum Suits { Spades = Spades, // error Clubs, // error Hearts, // error Diamonds // error }; Why? Because enumerators are exported to the enclosing scope of the enumeration. In the above example, the enumerators Spades, Clubs, Hearts, and Diamonds are declared. Because the enumerators are exported to the enclosing scope, they are considered to have global scope. The identifiers in the example are already defined in global scope. So its an error. For additional details and pitfalls ( :-) ), read-up on section 3.3 'Declarative regions and scopes' from the Draft C++ Standard, if interested you can get hold of the pdf from here(http://www.research.att.com/~bs/SC22-N-4411.pdf).
1,366,365
1,367,128
Imagemagick problem when loading a png file
I've compiled the latest version of imagemagick for the mac and I get the assertion below when I load a particular png file. This is a bit of a hassle as it crashes the program in debug mode. Anyone ever seen this before? Any workarounds? Assertion failed: (quantum_info->signature == MagickSignature), function DestroyQuantumInfo, file magick/quantum.c, line 215.
From "A Basic Introduction to PNG Features" - Integrity Checks - PNG supports three main types of integrity-checking to help avoid problems with file transfers and the like. The first and simplest is the eight-byte magic signature at the beginning of every PNG image. It will detect the most common type of file corruption: that due to the transfer of a binary file in text. On most systems, line-endings in text files are flagged by either a carriage-return character (CR), a line-feed character (LF), or both. Macintoshes use CRs; Unix systems use LFs; and all non-Unix PC systems (DOS, Windows 3.x/95/NT, OS/2) use CR/LF pairs.
1,366,378
1,366,397
std::string's character reference
I have the following string: index 0 1 2 3 4 5 6 7 std::string myString with the content of "\xff\xff\xff\x00\xff\x0d\x0a\xf5" When I'm refering to myString[3], I get the expected '\x00' value. But when I'm referring to myString[5], I get two values "\x0d\x0a" instead of just '\x0d'. Even more interesting is the myString[6] value, which is the '\xf5'. This time it's like the \x0d didn't exist and the correct position was referenced. My question would be: what is so special about the \x0d character in a std:string object? How come it is skipped when indexing? It's like counting this way: index 0 1 2 3 4 5 5 6 std::string myString = "\xff\xff\xff\x00\xff\x0d\x0a\xf5" As a comment, the '\x0d' character is the 13th ASCII character "carriage return" and '\x0a' is the line feed character. UPDATE: Can it be that std::string considers "\x0d\x0a" as a single character and thus occupies only one position in the string? Is this '\x0d' a "mystery" character with regard to std::string? ADDITIONAL INFO: http://en.wikipedia.org/wiki/Newline
Are you sure this is happening with std::string? std::string::operator[] returns a const char &, so how can it be returning two chars ('\x0d' and '\x0a')? That said, "\x0d\x0a" is usually used for line endings under Windows, whereas only '\x0a' is used under Linux, so conversion of the former to the latter is relatively common under Windows -- for example, I'm thinking of the behaviour of fopen when called with "wt". I would guess something similar is happening to you. Edit: Based on your comments on the original question, I think I can guess what's going on. I believe your string doesn't really contain what you think it contains. You're being misled because the mechanism you're using to output the string to a file (probably ofstream?) is performing end-of-line translation. This means that a '\n' (the Unix end-of-line code) is being translated to '\r\n' (the Windows end-of-line code). The purpose of end-of-line translation is to make code more portable between operating systems. You can inhibit it by opening the file in binary mode; for ofstream, this is done by specifying the ios_base::binary flag when you open the file, but this flag is not set by default. (See this Wikipedia article for more information on end-of-line markers on different operating systems.) This is what I believe is going on. Your string actually contains index 0 1 2 3 4 5 6 myString contents "\xff\xff\xff\x00\xff\x0a\xf5" You're outputting it something like this: ofstream file("myfile.txt"); for(size_t i=0; i<myString.size(); i++) ofstream << myString[i]; Because of the end-of-line translation expalined above, the '\x0a' in myString[5] is being output as '\x0d\x0a', and that's what is confusing you.
1,366,388
1,366,416
Capturing text change events in a QComboBox
I am developing a Qt application on Red Hat Linux. I want to capture Carriage Return key press events in a QComboBox. I have connected a slot to the signal editTextChanged() which is emitted for every key press but not for the Enter Key. Why so? Is there any other way to detect Carriage Returns?
I am assuming you wrote a slot and connected it to QComboBox::editTextChanged() signal. This signal is fired when the text changes and Enter does not change the text, it accepts it. If you want to capture Carriage Return, there are a number of ways you can follow. Subclass QComboBox. Override keyPressEvent() : first call QComboBox::keyPressEvent() and then check if the pressed key is Enter. If it is, emit a signal. Use this subclass whenever you need. Search about promoting widgets in QDesigner if you don't know how. Implement a new class which inherits QObject. In this class, override eventFilter() : check if the event is a key press. If it is, check if it is the Enter key. If it is, emit a signal. Then, create an instance of this class and set it as event filter to your QComboBox. Connect a slot to this instance's signal, which you implemented. If these are not clear, i recommend reading the following pages: Using Custom Widgets with Qt designer Qt Events & Event Filters
1,366,401
1,366,404
How can I handle dependencies on public functions that have to be called in a certain order?
Suppose I have a class that processes some data: class SomeClass { public: void SetData(IData*); void ProcessData(void); } The class would need the data to be set before ProcessData() can be called. How can I enforce this dependency? I could return an error code or throw an exception if ProcessData() is called before any data has been passed in. How sound is it to throw an exception? Additional information Some of the answers suggest passing in the IData to the constructor or ProcessData(). Those are sound answers. The reason why I am not doing this here is because this is part of a GUI system; the user may load in new data to SomeClass any point in time and make modification to it, so during the time when SomeClass is created, the data may not be available. (Yes, there are better design I could use to avoid this problem, but my boss wants to see results on the screen and I have to compromise between good design and visual results).
Make the SomeClass constructor require IData and remove SetData. Similarly, you could also pass IData to ProcessData.
1,366,437
1,366,460
Optimizing a floating point division and conversion operation
I have the following formula float mean = (r+b+g)/3/255.0f; I want to speed it up. There are the following preconditions 0<= mean <= 1 and 0 <= r,g,b <= 255 and r, g, b are unsigned chars so if I try to use the fact that >> 8 is like dividing by 256 and I use something like float mean = (float)(((r+b+g)/3) >> 8); this will always return 0. Is there a way to skip the costly float division and still end up with a mean between 0 and 1?
Pre-convert your divisions into a multiplicable constant: a / 3 / 255 is the same as a * (1 / (3 * 255)) so pre-compute: const float AVERAGE_SCALE_FACTOR = 1.f / (3.f * 255.f) then just do float mean = (r + g + b) * AVERAGE_SCALE_FACTOR; since multiplying is generally a lot faster than dividing.
1,366,470
1,366,513
C++ app on SunOS has a memory leak. How to find it?
i just landed on SunOS: $ uname -a SunOS sunfi95 5.9 Generic_122300-13 sun4u sparc SUNW,Sun-Fire-880 and have Sun studio: $ CC -V CC: Sun C++ 5.8 2005/10/13 How I can find memleaks in code? (dbx is not a option in this case). Valgrind does not work on sparc systems, only one solution that cross my mind is to use some smart lib that will overload new and delete and count how many times they are called. Anyone know something that is on BSD like license?
On Sun OS you can use Purify, or try to port(generally you'll port the leak, too) your program to Unix/Linux and use valgrind to find the leak.
1,366,524
1,366,539
Boost.Any vs. Boost.Variant
I'm having trouble choosing between Boost.Any and Boost.Variant. When should I use each one? What are the advantages and disadvantages of each? I am basically looking to store some states from external sources.
Have you looked at the comparison in the variant library already? (Not sure what states from external sources are, so it's kind of hard to say what's more appropriate for you.)
1,366,599
1,368,296
Throwing a JavaScript exception from C++ code using Google V8
I'm programming a JavaScript application which accesses some C++ code over Google's V8. Everything works fine, but I couldn't figure out how I can throw a JavaScript exception which can be catched in the JavaScript code from the C++ method. For example, if I have a function in C++ like ... using namespace std; using namespace v8; ... static Handle<Value> jsHello(const Arguments& args) { String::Utf8Value input(args[0]); if (input == "Hello") { string result = "world"; return String::New(result.c_str()); } else { // throw exception } } ... global->Set(String::New("hello"), FunctionTemplate::New(jsHello)); Persistent<Context> context = Context::New(NULL, global); ... exposed to JavaScript, I'ld like to use it in the JavaScript code like try { hello("throw me some exception!"); } catch (e) { // catched it! } What is the correct way to throw a V8-exception out of the C++ code?
Edit: This answer is for older versions of V8. For current versions, see Sutarmin Anton's Answer. return v8::ThrowException(v8::String::New("Exception message")); You can also throw a more specific exception with the static functions in v8::Exception: return v8::ThrowException(v8::Exception::RangeError(v8::String::New("..."))); return v8::ThrowException(v8::Exception::ReferenceError(v8::String::New("..."))); return v8::ThrowException(v8::Exception::SyntaxError(v8::String::New("..."))); return v8::ThrowException(v8::Exception::TypeError(v8::String::New("..."))); return v8::ThrowException(v8::Exception::Error(v8::String::New("...")));
1,366,896
1,366,920
C++ templates and implicit type conversion
I have the following code: #include <iostream> #include "boost/shared_ptr.hpp" using boost::shared_ptr; class Base { public: virtual ~Base() {} virtual void print() = 0; }; template <typename T> class Child : public Base { public: virtual void print() { std::cout << "in Child" << std::endl; } }; class GrandChild : public Child<int> { public: virtual void print() { std::cout << "in GrandChild" << std::endl; } }; template <typename T> void call_print(shared_ptr<Child<T> > a) { a->print(); } void call_base_print(shared_ptr<Base> a) { a->print(); } int main() { shared_ptr<GrandChild> gchild(new GrandChild); call_print(shared_ptr<Child<int> >(gchild)); // call_print(gchild); // Cannot compile! call_base_print(gchild); // This works. return 0; } I found it strange that call_base_print(gchild) works but call_print(gchild) causes a compiler error. I know that C++ does not allow two implicit conversions, but I don't think there're two conversions here... Could anyone enlighten me?
You don't get to the point of type conversion. It fails earlier, in template instantiation. call_base_print doesn't require type deduction. call_print<T>(shared_ptr<Child<T> > a) does. You're passing a shared_ptr<GrandChild>. And there's simply no T you can substitute such that shared_ptr<Child<T> > is shared_ptr<GrandChild>. Therefore, instantiation fails, and there is no function to call.
1,367,110
1,385,304
Cross-platform crash handler
I'm looking for a cross-platform crash handler. Google Breakpad looks promising, but it is sorely lacking any documentation, and requires a reasonable amount of fiddling to actually get going. What is a better alternative? All I need is the ability to reliably record crash dumps, stack traces, and CPU information at the time of a crash. Alternatively, what is the experience using Google Breakpad? Has it been great or horrible?
Well, it turns out that google-breakpad is pretty nice after all. It's not totally easy to set up, but it's OK for what I need.
1,367,316
1,368,601
#include <> and #include ""
Possible Duplicate: what is the difference between #include <filename> and #include “filename” Is there a fundamental difference between the two #include syntax, apart from the way the path the compiler will search for? I have the feeling that Intel's compiler does not give exactly the same output.
The C language standard says that <> is to be used for "headers" and "" is to be used for "source files". Now, don't get all up in arms about the "source files" thing. When the standard says "source files", it doesn't mean what you think. The term "source files" as used in the standard encompasses what we colloquially call "header files" (in addition to what we commonly call "source files"). When the standard talks about "headers", it isn't specifically talking about files at all. The standard does not require headers to exist as files. They could be built-in to the compiler for all the standard cares. So the real difference between <> and "" is that <> is used for headers and "" is used for files. If you know that the source you'll be including is a file then you should use "". In practice, compilers use different search algorithms for <> versus "". This is allowed by the standard as the search algorithm to be used for either one is implementation defined. But this is not the real difference as expressed by the standard.
1,367,335
1,367,346
ostringstream and ends
I've been working with somebody else's code and noticed that on all uses of ostringsteam they are in the habit of explicitly appending std::ends. This is something I've never done and have never encountered a problem. It doesn't appear to, but should std::ends make any difference in the following code? ostringstream message; message << "Hello world, version " << 2 /* << std::ends ??? */; printf( "%s\n", message.str().c_str() );
Appending std::ends is nonsense here since stringstream’s c_str returns a null-terminated char*. The same was not the case for the (now deprecated) strstreams where appending std::ends was necessary. I believe the author simply didn’t know of this changed behaviour.
1,367,429
1,367,494
Sorting a std::map by value before output & destroy
I'm aware that map is not prepared to be sorted. It's heavily optimized for fast and random key access and actually doesn't support std::sort. My current problem is that I've a full map<std::string,int> which I'm not going to use anymore. I just need to extract 10 pairs in value(int) order and destroy it. The best thing, if it was possible, would be to sort it in place and then iterate it 10 times, but that apparently is not a solution. I'm trying different solutions as going through a multimap<int,string> (to allow duplicate keys), but I'd like to know if there is a more elegant solution, using stl algorithms as much as posible. EDIT: I'm using a map because for the 99% of the time, I need it as a map: fast key lookups to increase values. Just need a good way of later extracting in value order when I don't need the map anymore. Current approach whould be: std::copy the map(std::string,int) to a vector(pair(std::string,int)) sort the vector get the first 10 values destroy vector and map
Maps are stored as a tree sorted in key order. You want the 10 smallest (or largest) integer values, and their keys, right? In that case, iterate the map and put all the key-value pairs in a vector of pairs (std::vector<std::pair<std::string, int> >). I think you can just use the two-iterator-arg constructor of std::vector for this. Then use std::partial_sort on the vector. Specify a comparator to partial_sort, which compares pairs by just comparing the value int, ignoring the key string. Then you have the 10 pairs you want at the start of the vector, and the rest of the vector contains the remaining pairs in an unspecified order. Code (untested): typedef std::pair<std::string, int> mypair; struct IntCmp { bool operator()(const mypair &lhs, const mypair &rhs) { return lhs.second < rhs.second; } }; void print10(const std::map<std::string,int> &mymap) { std::vector<mypair> myvec(mymap.begin(), mymap.end()); assert(myvec.size() >= 10); std::partial_sort(myvec.begin(), myvec.begin() + 10, myvec.end(), IntCmp()); for (int i = 0; i < 10; ++i) { std::cout << i << ": " << myvec[i].first << "-> " << myvec[i].second << "\n"; } } Note that if there are several strings with the same value, either side of the limit of 10, then it's not specified which ones you get. You can control this by having your comparator look at the string too, in cases where the integers are equal.
1,367,558
1,388,182
Prevent zoom in CDHTMLDialog (BHO on IE)
I have a CDHTMLDialog running in IE that has a fixed size that I chose, and runs in a fixed window to match this size. My problem is that the user can zoom on it (by ctrl-mousewheel) causing my html to be larger or smaller than the window which looks awkward and adds annoying scrollbars. Also, the user might use ctrl-+ or ctrl-- to change the html size, which also causes my CDHTMLDialog to become larger or smaller (though only on navigation after changing size). Anyone maybe has an idea on how to prevent all zooms on the CDHTMLDialog, including wheel and ctrl-+?
Found it :) Upon document complete I run the following: CComVariant vZoom = 100; m_pBrowserApp->ExecWB(OLECMDID_OPTICAL_ZOOM, OLECMDEXECOPT_DODEFAULT,&vZoom, NULL); Which resets zoom in my DHTMLDialog to 100%. Source: Here
1,367,649
1,368,535
Is there a way to apply an action to N C++ class members in a loop over member names (probably via pre-processor)?
The problem: I have a C++ class with gajillion (>100) members that behave nearly identically: same type in a function, each member has the same exact code done to it as other members, e.g. assignment from a map in a constructor where map key is same as member key This identicality of behavior is repeated across many-many functions (>20), of course the behavior in each function is different so there's no way to factor things out. The list of members is very fluid, with constant additions and sometimes deletions, some (but not all) driven by changing columns in a DB table. As you can imagine, this presents a big pain-in-the-behind as far as code creation and maintenance, since to add a new member you have to add code to every function where analogous members are used. Example of a solution I'd like Actual C++ code I need (say, in constructor): MyClass::MyClass(SomeMap & map) { // construct an object from a map intMember1 = map["intMember1"]; intMember2 = map["intMember2"]; ... // Up to intMemberN = map["intMemberN"]; } C++ code I want to be able to write: MyClass::MyClass(SomeMap & map) { // construct an object from a map #FOR_EACH_WORD Label ("intMember1", "intMember2", ... "intMemberN") $Label = map["$Label"]; #END_FOR_EACH_WORD } Requirements The solution must be compatible with GCC (with Nmake as make system, if that matters). Don't care about other compilers. The solution can be on a pre-processor level, or something compilable. I'm fine with either one; but so far, all of my research pointed me to the conclusion that the latter is just plain out impossible in C++ (I so miss Perl now that I'm forced to do C++ !) The solution must be to at least some extent "industry standard" (e.g. Boost is great, but a custom Perl script that Joe-Quick-Fingers created once and posted on his blog is not. Heck, I can easily write that Perl script, being much more of a Perl expert than a C++ one - I just can't get bigwigs in Software Engineering at my BigCompany to buy into using it :) ) The solution should allow me to declare a list of IDs (ideally, in only one header file instead of in every "#FOR_EACH_WORD" directive as I did in the example above) The solution must not be limited to "create an object from a DB table" constructor. There are many functions, most of them not constructors, that need this. A solution of "Make them all values in a single vector, and then run a 'for' loop across the vector" is an obvious one, and can not be used - the code's in a library used by many apps, the members are public, and re-writing those apps to use vector members instead of named members is out of the question, sadly.
Boost.Preprocessor proposes many convenient macros to perform such operations. Bojan Resnik already provided a solution using this library, but it assumes that every member name is constructed the same way. Since you explicitely required the possibily to declare a list of IDs, here is a solution that should better fulfill your needs. #include <boost/preprocessor/seq/for_each.hpp> #include <boost/preprocessor/stringize.hpp> // sequence of member names (can be declared in a separate header file) #define MEMBERS (foo)(bar) // macro for the map example #define GET_FROM_MAP(r, map, member) member = map[BOOST_PP_STRINGIZE(member)]; BOOST_PP_SEQ_FOR_EACH(GET_FROM_MAP, mymap, MEMBERS) // generates // foo = mymap["foo"]; bar = mymap["bar]; ------- //Somewhere else, we need to print all the values on the standard output: #define PRINT(r, ostream, member) ostream << member << std::endl; BOOST_PP_SEQ_FOR_EACH(PRINT, std::cout, MEMBERS) As you can see, you just need to write a macro representing the pattern you want to repeat, and pass it to the BOOST_PP_SEQ_FOR_EACH macro.
1,368,240
1,368,280
Workaround for stack limit in windows with gnu g++
I have built and compiled a command line program with GNU g++ which "overflows" the stack for a number of reasons, mainly deep inheritance, lots of objects created, etc. So I followed this workaround on Mac OS X to solve the problem when linking: -Wl,-stack_size,0x10000000,-stack_addr,0xc0000000 Under Linux, I just tried ulimit -s unlimited; running the program in this way does not give a segmentation fault any more But when trying to compile it on Windows with GNU g++, the compiler does not recognize -Wl,-stack_size,0x10000000,-stack_addr,0xc0000000 What other option would you use as a workaround for the problem? Thanks in advance
-Wl,--stack,somelargesize looks like what you're after. However, I'd strongly recommend refactoring your code to make use of the heap for large allocations instead. Address space is a finite resource and your "workaround" asks for quite a large chunk of it.
1,368,429
1,368,995
Unrolling small loops with Visual Studio 2005
How do you tell the compiler to unroll loops based on the number of iterations or some other attribute? Or, how do you turn on loop unrolling optimization in Visual Studio 2005? EDIT: E.g. //Code Snippet 1 vector<int> b; for(int i=0;i<3;++i) b.push_back(i); As opposed to //Code Snippet 2 vector<int> b; b.push_back(0); b.push_back(1); b.push_back(2); push_back() is an example, I could replace this with anything which can take a long time. But I read somewhere that I can use Code 1 and the compiler can unroll it to Code 2 if the loop satisfies some criteria. So my question is: how do you do that? There's already a discussion on SO as to which one is more efficient but any comments on that is appreciated anyway.
It's generally fairly simple: "You enable optimizations". If you tell the compiler to optimize your code, then loop unrolling is one of the many optimizations it tries to apply. Keep in mind though, that unrolling is not always going to produce faster code. It might cause cache misses (in both data and instruction cache). And with the advanced branch prediction found in modern CPU's, the costs of the branches that make up a loop is often negligible. Sometimes, the compiler may determine that unrolling would produce slower code, and then it won't do it.
1,368,451
1,368,515
Is Qt classified as a c++ library? If not a library, how would you classify QT?
I recently started looking into Qt (I installed Qt 4.5.2 and installed their Eclipse-CDT plugin called "qt integration v1.5.2" and I will do all my development in Linux-Eclipse-CDT-QTintegration). Originally I thought Qt was a straight vanilla C++ library but when I installed and started running Qt example code I saw lots of "weird" things that I consider to be non-standard. My goal is to understand at a high level of abstraction: Is Qt classified as a C++ library? If not a library, how would you classify Qt (analogy/metaphors are appreciated)?
Qt is a framework, not a library. This isn't a hard-and-fast distinction enforced by the programming language, rather, it describes how the code is designed and intended to be used: A library is someone else's code that is used by your code. Using a library means that your application remains as it is, it just has another library to help it out. A framework is someone else's code that your code fits into. Using a framework means that the framework defines the structure of your application. If you're using a framework, you need to learn that framework's conventions, which may be a bit different than the base language; otherwise, you can spend a lot of time fighting the framework, and you'll be missing out on some of what it has to offer. Qt in particular doesn't look like straight vanilla C++ because it isn't straight vanilla C++. It adds (limited) extensions to C++'s object system to permit features like signals and slots; these extensions are implemented using Qt's moc, which acts as a C++ preprocessor. For more information on Qt's extensions to C++: Meta-Object System Why Doesn't Qt Use Templates for Signals and Slots?
1,368,512
1,368,564
What is the purpose of the *.pro file?
I just started using Qt and noticed that in each example code folder there is a .pro file (and there is also a makefile created too... why?). What is the purpose of the .pro file?
It's a multiplatform project file which qmake turns into platform-specific makefiles. The main reason for its existence is easier configuration and compilation of multiplatform projects. Compare e.g. to autotools-generated configure scripts and makefiles commonly seen in unixland.
1,368,534
1,368,577
Why does Qt use its own make tool, qmake?
I just started using Qt and noticed that it uses its own make tool, qmake. Why does Qt use its own make tool? Is there something special that prevents it from using a standard make tool? Does qmake call the GCC C++ compiler?
Qt uses qmake to transparently support Qt's various addons, including "moc, the meta-object compiler" (which provides signals & slots), "uic, the ui compiler" (which creates header files from .ui designer files), "rcc, the resource compiler" (which compiles resources). There's nothing to stop you using any build system you want. however, it's a lot more work. For example, you need to run "moc" over every header file that contains a class that has signals or slots. In general it's not recommended, especially for someone who's just starting to use Qt. QMake does not call g++/gcc directly. Instead, qmake creates native make files on your current platform. Under linux it creates standard GNU make files, under windows it can generate visual studio make files, under Mac OS X it can generate XCode project files. You then invoke your native build system (either GNU make, or MS NMake, or xcodebuild or whatever), which will call your native compiler (g++/gcc or whatever).
1,368,551
1,368,581
Can you use the standard GDB debugger with Qt executables?
I just started using Qt and I wanted to debug my Qt application. Can I use the standard GDB debugger with Qt executables?
Yes you can. You might also want to use the gdb integration in Qt Creator, which does a much better job of inspecting data at run time than gdb alone.
1,368,584
1,368,739
What does the Q_OBJECT macro do? Why do all Qt objects need this macro?
I just started using Qt and noticed that all the example class definitions have the macro Q_OBJECT as the first line. What is the purpose of this preprocessor macro?
From the Qt documentation: The Meta-Object Compiler, moc, is the program that handles Qt's C++ extensions. The moc tool reads a C++ header file. If it finds one or more class declarations that contain the Q_OBJECT macro, it produces a C++ source file containing the meta-object code for those classes. Among other things, meta-object code is required for the signals and slots mechanism, the run-time type information, and the dynamic property system.
1,368,593
1,368,841
Qt question: How do signals and slots work?
How do signals and slots work at a high level abstraction? How are signals and slots implemented at a high level abstraction?
I've actually read this Qt page about it, and it does a good job of explaining: https://doc.qt.io/qt-5/signalsandslots.html
1,368,642
1,368,873
Is there a shorter way to forward declare a class in a namespace?
I can forward declare a function in a namespace by doing this: void myNamespace::doThing(); which is equivalent to: namespace myNamespace { void doThing(); } To forward declare a class in a namespace: namespace myNamespace { class myClass; } Is there a shorter way to do this? I was thinking something along the lines of: class myNamespace::myClass;
No, however with a little reformatting namespace myNamespace { class myClass; } isn't much worse than class myNamespace::myClass;
1,369,292
1,369,750
Is it possible to generate a global list of marked strings at compile time/runtime?
So, I'm working on translating my C++ app into multiple languages. What I'm currently using is something like: #define TR(x) (lookupTranslatedString( currentLocale(), x )) wcout << TR(L"This phrase is in English") << endl; The translations are from a CSV file which maps the english string to the translated string. "This phrase is in English","Nasa Tagalog itong pagsabi" This is simplified, but that's the basic idea. My question is about generating the list of English phrases that need to be translated. I just need the CSV with all the english phrases, and blank translated phrases. I was hoping that it might be possible to either generate this list at compile time or at runtime. At compiletime I was thinking something like this: #define TR(x) \ #warning x \ (lookupTranslatedString( currentLocale(), x )) and then maybe parse the compile log, or something. This seems not to work so well. At runtime would also be great. I was thinking of just starting the app and having a hidden command that would dump the english CSV. I've seen similar methods used to register commands with a central list, using global variables. It might look something like this: class TrString { public: static std::set< std::wstring > sEnglishPhrases; TrString( std::wstring english_phrase ) { sEnglishPhrases.insert( english_phrase ); } }; #define TR(x) do {static TrString trstr(x);} while( false ); (lookupTranslatedString( currentLocale(), x )); I know there's two problems with the above code. I doubt it compiles, but more importantly, in order to generate a list of all english phrases, I'd need to hit every single code path before accessing sEnglishPhrases. It looks like I'll end up writing a small parser to read through all my code and look for TR strings, which isn't really that tough. I was just hoping to learn a little more about C++, and if there's a better way to do this.
I think you're almost there. Taking the last idea: class TrString { public: static std::set< std::string > sEnglishPhrases; std::string phrase; TrString(const std::string& english_phrase ):phrase(english_phrase) { sEnglishPhrases.insert( english_phrase ); } friend ostream &operator<<(ostream &stream, const TrString& o); }; ostream &operator<<(ostream &stream, const TrString& o) { stream << lookupTranslatedString( currentLocale(), o.phrase); return stream; } #define TR(x) ( TrString(x) ) // ... std::cout << TR("This phrase is in English") << std::endl; And as you say, you do need to run the code over every TR() statement, but you could configure a unit test framework to do this. My alternative would be to use the above TrString class to make static variables for each module: // unnamed namespace gives static instances namespace { TrString InEnglish("This phrase is in English"); // ... } Now you just need to link in an alternative main() to print out TrString:: sEnglishPhrases
1,369,530
1,370,100
Registry hive question
Does anyone have a smal example of how to programmatically, in c/c++, load a users registry hive? I would loike to load a hive set some values and close the hive. Thanks in advance for any help. Tony
I haven't got a specific example, but the Windows API calls you need would be: RegOpenKeyEx() to load the registry key RegSetValueEx() / RegGetValue() [and sister functions] to get/set registry values RegCloseKey() to close the registry. There's some example code behind this link on codersource.net ... although I can't vouch for how complete or correct it is. Review against the MSDN :-)
1,369,827
1,375,128
Reconnect to Process Started Via COM
First, I'd like to note that I need to use the COM/OLE2 APIs, the low level stuff, the stuff you can put in a C Windows Console program. I can't use MFC. I can't use .NET. My question is: Given the following code: CLSID clsid; HRESULT hr; hr = CLSIDFromProgID(L"InternetExplorer.Application", &clsid); assert(SUCCEEDED(hr)); hr = CoCreateInstance(clsid, NULL, CLSCTX_LOCAL_SERVER, IID_IDispatch, (void **)&(iePtr_)); assert(SUCCEEDED(hr)); Is there a way to write some information to the disk so that I can reconnect to the same instance of IE later on? Basically can "iePtr_" be stringified for later reconstitution by some other process? Thanks. ---- added later------ The broader problem I am trying to solve is that I want to start an AutoCAD application, load some data into it, and then leave it running for my client to interact with. Later he will go back to my application and I want to reconnect to the same AutoCAD session and feed it more data. Now, I full well realize I can keep the IDispatch pointer in memory in my application and I'll be able to continue to interact with the same AutoCAD process. That's my fallback position. However, I use a "wrapper" program to do my COM stuff. So the wrapper is transient. My main application starts the wrapper, then the wrapper communicates, and then exits. I just want subsequent wrapper processes to be able to reconnect to the same AutoCAD process. Why use a wrapper? Here's the working reason: My main application is a 32-bit application, but I can use a 64-bit wrapper and communicate with 64-bit AutoCAD. I need to be able to communicate with 64-bit AutoCAD and can probably not port my main application easily (500K+ lines of C++) vs. my wrapper program (couple hundred lines).
If the application registered itself in the Running Object Table, you can use the GetActiveObject function to get a reference to the application object. IUnknown *pUnknown; hr = GetActiveObject(clsid, NULL, &pUnknown); assert(SUCCEEDED(hr)); hr = pUnknown->QueryInterface(IID_IDispatch, (void **)&(iePtr_)); assert(SUCCEEDED(hr));
1,369,958
1,369,980
Moving C++ Method Declarations from .hh to .cc File
I'm working on a C++ project in which there are a lot of classes that have classes, methods and includes all in a single file. This is a big problem, because frequently the method implementations require #include statements, and any file that wants to use a class inherits these #includes transitively. I was just thinking that it would be nice to have a tool that did the following operation on a C++ header file: Parse a C++ header file into two pieces: a header file that declares a class, its data and the methods of that class and a separate file that implements the methods. Removes unnecessary includes from the header file. Adds the necessary includes to the implementation file. I understand that parsing C++ is very difficult, but even something that worked imperfectly would be an improvement over the repetitive text editing that I'm doing right now. Is there anything that does anything like this? Or am I stuck with the decision between rolling my own solution or hammering through this with my text editor?
Are you looking for something like Lazy C++? Lzz is a tool that automates many onerous C++ programming tasks. It can save you a lot of time and make coding more enjoyable. Given a sequence of declarations Lzz will generate your header and source files. Example from the same place: // A.lzz class A { public: inline void f (int i) { ... } void g (int j = 0) { ... } }; bool operator == (A const & a1, A const & a2) { ... } Lzz will generate a header file: // A.h #ifndef LZZ_A_h #define LZZ_A_h class A { public: void f (int i); void g (int j = 0); }; inline void A::f (int i) { ... } bool operator == (A const & a1, A const & a2); #endif And a source file: // A.cpp #include "A.h" void A::g (int j) { ... } bool operator == (A const & a1, A const & a2) { ... }
1,370,042
32,255,804
Why is const-correctness specific to C++?
Disclaimer: I am aware that there are two questions about the usefulness of const-correctness, however, none discussed how const-correctness is necessary in C++ as opposed to other programming languages. Also, I am not satisfied with the answers provided to these questions. I've used a few programming languages now, and one thing that bugs me in C++ is the notion of const-correctness. There is no such notion in Java, C#, Python, Ruby, Visual Basic, etc., this seems to be very specific to C++. Before you refer me to the C++ FAQ Lite, I've read it, and it doesn't convince me. Perfectly valid, reliable programs are written in Python all the time, and there is no const keyword or equivalent. In Java and C#, objects can be declared final (or const), but there are no const member functions or const function parameters. If a function doesn't need to modify an object, it can take an interface that only provides read access to the object. That technique can equally be used in C++. On the two real-world C++ systems I've worked on, there was very little use of const anywhere, and everything worked fine. So I'm far from sold on the usefulness of letting const contaminate a codebase. I am wondering what is it in C++ that makes const necessary, as opposed to other programming languages. So far, I've seen only one case where const must be used: #include <iostream> struct Vector2 { int X; int Y; }; void display(/* const */ Vector2& vect) { std::cout << vect.X << " " << vect.Y << std::endl; } int main() { display(Vector2()); } Compiling this with const commented out is accepted by Visual Studio, but with warning C4239, non-standard extension used. So, if you want the syntactic brevity of passing in temporaries, avoiding copies, and staying standard-compliant, you have to pass by const reference, no way around it. Still, this is more like a quirk than a fundamental reason. Otherwise, there really is no situation where const has to be used, except when interfacing with other code that uses const. Const seems to me little else than a self-righteous plague that spreads to everything it touches : The reason that const works in C++ is because you can cast it away. If you couldn't cast it away, then your world would suck. If you declare a method that takes a const Bla, you could pass it a non-const Bla. But if it's the other way around you can't. If you declare a method that takes a non-const Bla, you can't pass it a const Bla. So now you're stuck. So you gradually need a const version of everything that isn't const, and you end up with a shadow world. In C++ you get away with it, because as with anything in C++ it is purely optional whether you want this check or not. You can just whack the constness away if you don't like it. Anders Hejlsberg (C# architect), CLR Design Choices
Well, it will have taken me 6 years to really understand, but now I can finally answer my own question. The reason C++ has "const-correctness" and that Java, C#, etc. don't, is that C++ only supports value types, and these other languages only support or at least default to reference types. Let's see how C#, a language that defaults to reference types, deals with immutability when value types are involved. Let's say you have a mutable value type, and another type that has a readonly field of that type: struct Vector { public int X { get; private set; } public int Y { get; private set; } public void Add(int x, int y) { X += x; Y += y; } } class Foo { readonly Vector _v; public void Add(int x, int y) => _v.Add(x, y); public override string ToString() => $"{_v.X} {_v.Y}"; } void Main() { var f = new Foo(); f.Add(3, 4); Console.WriteLine(f); } What should this code do? fail to compile print "3, 4" print "0, 0" The answer is #3. C# tries to honor your "readonly" keyword by invoking the method Add on a throw-away copy of the object. That's weird, yes, but what other options does it have? If it invokes the method on the original Vector, the object will change, violating the "readonly"-ness of the field. If it fails to compile, then readonly value type members are pretty useless, because you can't invoke any methods on them, out of fear they might change the object. If only we could label which methods are safe to call on readonly instances... Wait, that's exactly what const methods are in C++! C# doesn't bother with const methods because we don't use value types that much in C#; we just avoid mutable value types (and declare them "evil", see 1, 2). Also, reference types don't suffer from this problem, because when you mark a reference type variable as readonly, what's readonly is the reference, not the object itself. That's very easy for the compiler to enforce, it can mark any assignment as a compilation error except at initialization. If all you use is reference types and all your fields and variables are readonly, you get immutability everywhere at little syntactic cost. F# works entirely like this. Java avoids the issue by just not supporting user-defined value types. C++ doesn't have the concept of "reference types", only "value types" (in C#-lingo); some of these value types can be pointers or references, but like value types in C#, none of them own their storage. If C++ treated "const" on its types the way C# treats "readonly" on value types, it would be very confusing as the example above demonstrates, nevermind the nasty interaction with copy constructors. So C++ doesn't create a throw-away copy, because that would create endless pain. It doesn't forbid you to call any methods on members either, because, well, the language wouldn't be very useful then. But it still wants to have some notion of "readonly" or "const-ness". C++ attempts to find a middle way by making you label which methods are safe to call on const members, and then it trusts you to have been faithful and accurate in your labeling and calls methods on the original objects directly. This is not perfect - it's verbose, and you're allowed to violate const-ness as much as you please - but it's arguably better than all the other options.
1,370,111
1,370,149
Looking for C++ implementation of OpenGL gears example
I have often seen the spinning gears OpenGL example ( I think originally done by SGI) but I today I have only been able to find C and Ruby implementations, can anyone point me to a c++ implementation?
What, in particular, would you be looking for in a C++ implementation that the C one doesn't provide? OpenGL is a C API, and thus a C demonstration is practical. A C++ implementation would call all the same functions in the same order and to the same effect, it would likely just wrap the implementation in an object. This doesn't really further one's understanding of the core API, and can possibly add a layer of obfuscation to those not familiar with some C++ styles and patterns. If what you are really looking for is an example of initiating OpenGL wrapped in a C++ framework, I made a few of those a while back. You can find them here. Please note that I'm no longer actively maintaining the code or page, though.
1,370,323
1,370,341
Printing an array in C++?
Is there a way of printing arrays in C++? I'm trying to make a function that reverses a user-input array and then prints it out. I tried Googling this problem and it seemed like C++ can't print arrays. That can't be true can it?
Just iterate over the elements. Like this: for (int i = numElements - 1; i >= 0; i--) cout << array[i]; Note: As Maxim Egorushkin pointed out, this could overflow. See his comment below for a better solution.
1,370,375
1,371,761
How to get excel version from c++ add-in
I have a c++ unmanaged project whose output is an .xll file which is an add-in loaded by excel at startup, this add-in can work with both versions, excel 2003 and excel 2007. Now, what I need to do is to obtain the version of the excel instance that the user is actually using for working with my add-in. Does anyone can suggest me how to get it? Thanks
You can call Excel4(xlfGetWorkspace, &version, 1, &arg), where arg is a numeric XLOPER set to 2 and version is a string XLOPER which can then be coerced to an integer. The result for Excel 2007 would be 12. You can do this in xlAutoOpen.
1,370,621
1,370,989
How do I get mnemonics in TrackPopupMenu?
I have a win32/MFC application with a context menu that I build programatically: CPoint pt; GetMenuPopupPos(&pt); CAtlString csItem = _T("&Example"); CMenu menu; menu.CreatePoupMenu(); menu.AppendMenu(MF_STRING, IDM_EXAMPLE_COMMAND, csItem); menu.TrackPopupMenuEx(TPM_LEFTALIGN|TPM_LEFTBUTTON, pt.x, pt.y, this, NULL); I've omitted the rest of the menu items for brevity. The menu works, including the keyboard shortcuts, but the problem is that I can't see the underlined shortcuts in the final menu. This menu has a single entry: Example While I would expect the entry (where the bold letter would be underlined). Example How do I get the underlines to show up?
By default, Windows doesn't show underlines when a context menu is invoked using the mouse -- only when it is invoked using the keyboard. You can't override this behaviour short of owner-drawing the menu. Your shortcuts will show if the user has selected the "underline menu shortcut keys" option, or if the user invokes the context menu via Shift+F10 or the Windows context menu key.
1,370,683
1,370,721
Opengl Selective glClipPlane
I have a scene drawn in openGL (openGl 1.1 win32). I use glClipPlane to hide foreground objects to allow the user to see/edit distance parts. The selection is done natively without using openGL. But the glClipPlane applies to all openGL elements - coordinate icons, gridlines etc and even elements drawn in gluOrtho2D on top - scale bars, selection boxes etc. Is there anyway to selective override the clipplanes to allow these elements to be drawn while clipping the main scene?
Isn't surrounding only the objects you want to hide with glEnable(GL_CLIP_PLANE); and glDisable(GL_CLIP_PLANE); enough?
1,370,749
1,370,952
Whats the difference between "abc" and {"abc"} in C?
In C specifically (i suppose this also applies to C++), what is the difference between char str[4] = "abc"; char *cstr = {"abc"}; Problems arise when i try and pass my "abc" into a function that accepts char** void f(char** s) { fprintf(stderr, "%s", *s); } Doing the following yields a compiler error. If cast to char** (to make compiler happy) program seg faults. f(&str); However the following works fine f(&cstr[0]);
This is an example of how pointers and arrays are not equivalent in C. In particular: the rule that arrays decay to pointers is not applied recursively This means that an array can be used as a pointer, but a pointer-to-array cannot be used as a pointer-to-pointer. This is what you are experiencing here. This is why the compiler complains about mismatched types when you don't cast &str explicitly to char**. That should be your first clue that something is wrong. The reason that this causes a segfault is this: The way that an array automatically decays to a pointer is by turning into the address of its first element. A pointer to an array is likewise a pointer to the address of the array's first element. So a pointer-to-array and array-as-pointer are the same thing. In other words str, when passed as a pointer, has a value identical to &str. So if you try to make &str into a pointer-to-pointer, it doesn't work, since is just a (single-level) pointer. For example, void f(char** pp); void g(char* p); char[] str = "abcd"; // Lets say this is allocated at address 0x1234 g(str); // Value of p in g is 0x1234 (by automatic conversion of char[4] to char*) char* p_str = &str; // Value of p_str is 0x1234 g(p_str); // Value of p in g is again 0x1234 f(str); // Illegal, no conversion of char[] to char** (obvious) f(p_str); // Illegal, no conversion of char* to char** (obvious) f(&str); // Illegal, no conversion of char*[4] to char** (less obvious) f((char**)p_str); // Ok, now you're overriding the typecheck But after that last call to f((char**)p_str), the value of pp in f is still going to be 0x1234 because you haven't modified the value of p_str, you've only suppressed the type-checker's complaint. This means that *pp is going to be 'a', not a pointer to the address that contains 'a'. And that's why you get a segfault when f tries to execute **pp.
1,370,870
1,370,892
Parse URLs using C-Strings in C++
I'm learning C++ for one of my CS classes, and for our first project I need to parse some URLs using c-strings (i.e. I can't use the C++ String class). The only way I can think of approaching this is just iterating through (since it's a char[]) and using some switch statements. From someone who is more experienced in C++ - is there a better approach? Could you maybe point me to a good online resource? I haven't found one yet.
Weird that you're not allowed to use C++ language features i.e. C++ strings! There are some C string functions available in the standard C library. e.g. strdup - duplicate a string strtok - breaking a string into tokens. Beware - this modifies the original string. strcpy - copying string strstr - find string in string strncpy - copy up to n bytes of string etc There is a good online reference here with a full list of available c string functions for searching and finding things. http://www.cplusplus.com/reference/clibrary/cstring/ You can walk through strings by accessing them like an array if you need to. e.g. char* url="http://stackoverflow.com/questions/1370870/c-strings-in-c" int len = strlen(url); for (int i = 0; i < len; ++i){ std::cout << url[i]; } std::cout << endl; As for actually how to do the parsing, you'll have to work that out on your own. It is an assignment after all.
1,370,976
1,370,985
C++ Style: Prefixing virtual keyword to overridden methods
I've been having a discussion with my coworkers as to whether to prefix overridden methods with the virtual keyword, or only at the originating base class. I tend to prefix all virtual methods (that is, methods involving a vtable lookup) with the virtual keyword. My rationale is threefold: Given that C++ lacks an override keyword, the presence of the virtual keyword at least notifies you that the method involves a lookup and could theoretically be overridden by further specializations, or could be called through a pointer to a higher base class. Consistently using this style means that, when you see a method (at least within our code) without the virtual keyword, you can initially assume that it is neither derived from a base nor specialized in subclass. If, through some error, the virtual were removed from IFoo, all children will still function (CFooSpecialization::DoBar would still override CFooBase::DoBar, rather than simply hiding it). The argument against the practice, as I understood it, was, "But that method isn't virtual" (which I believe is invalid, and borne from a misunderstanding of virtuality), and "When I see the virtual keyword, I expect that means someone is deriving from it, and go searching for them." The hypothetical classes may be spread across several files, and there are several specializations. class IFoo { public: virtual void DoBar() = 0; void DoBaz(); }; class CFooBase : public IFoo { public: virtual void DoBar(); // Default implementation void DoZap(); }; class CFooSpecialization : public CFooBase { public: virtual void DoBar(); // Specialized implementation }; Stylistically, would you remove the virtual keyword from the two derived classes? If so, why? What are Stack Overflow's thoughts here?
I completely agree with your rationale. It's a good reminder that the method will have dynamic dispatch semantics when called. The "that method isn't virtual" argument that you co-worker is using is completely bogus. He's mixed up the concepts of virtual and pure-virtual.
1,371,480
1,371,521
Effect of memory usage in the complexity of an algorithm
I am reading Nicolai Josuttis book on C++STL algorithms. For many algorithms such as stable_sort(), he mentions that the complexity of the algorithm n * log(n) if enough memory is available, otherwise it is n * log(n) * log(n). My question is how does the memory usage affects the complexity ? And how does STL detect such a situation?
Looking at gcc's STL, you'll find inplace_merge in stl_algo.h. This is a traditional merge implementation of merge sort, with O(N), using a buffer the same size as the input. This buffer is is allocated through _Temporary_buffer, from stl_tempbuf.h. This invokes get_temporary_buffer, which ultimately invokes new. Should that throw an exception, the exception gets caught, and the buffer is NULL - which is the "not sufficient memory" case. In that case, the merge works with __merge_without_buffer, which is O(N lg N). As the recursion depth of merge sort is O(lg N), you get O(N lg N) in the case of the "traditional" mergesort (with buffer), and O(N lg N lg N) in the version without buffer.
1,371,494
1,535,405
.NET symbols disappearing from assembly
I have a project that is built with native C++, as well as C++/CLI. I have the following components: Assembly A (C++/CLI) | uses Assembly B (C++/CLI) | uses Static Lib C (Native C++) I did a major re-write of Static Lib C, and it compiles, and other native projects that use it compile fine as well. None of Assembly B changed in the re-write - and as expected, when I compile Assembly B it compiles fine with no errors or warnings. However, when I try to compile Assembly A, none of the symbols that are supposed to be available in Assembly B can be found, causing hundreds of errors. I tried adding and removing B and C as references in the A project with no luck. I tried doing a clean, and rebuilding everything from scratch - but still no luck. I loaded Assembly B up in RedGate's Reflector, and I can not see the symbols, so at least that's consistent. I'm working on a branch, so I loaded an earlier version of Assembly B from the trunk, (and it asked to unload the previous version I had loaded from my branch), and I could see all the symbols in it. So when I look at my current version of Assembly B in Reflector, I see: +TFModelSetNETD, Version=1.0.3532.42171, Culture=neutral, PublicKeyToken=null +TFModelSetNETD.dll + References + {} - + <CppImplementationDetails> + <CrtImplementationDetails> + vc_attributes And that is all. In the older version, I see these four entries, plus all my namespaces declared in Assembly B, Static Lib C, other libs, plus several boost and std namespaces. I should mention this is in Visual Studio 2008. Any ideas as to what is going on here? I just can't understand what I could have done to make the compiler not export any symbols, without giving me any kind of warning. Ideas, tips, or debugging suggestions are all greatly appreciated. Edit: I have loaded the Static Lib C into LibDump, and all the symbols are there - however, none of the symbols either defined in Assembly B, or referenced from Static Lib C are visible in Assembly B when examining it with Redgate Reflector.
What happened was that the header files for the symbols in question were never being included in a cpp file anywhere. The only explanation I have for why it worked is that maybe one of the other compilation units included the headers in question indirectly, but when it changed in the rewrite, the symbols were no longer being included anywhere. Believe it or not this problem was easy compared to the next one I hit - boost::thread causing the assembly to throw an exception on load because of conflicts relating to DLL initialization and thread-local storage.
1,371,564
1,371,630
set an attribute in XML node usig MSXML. I am struck
I try to set an attribute in a XML node using MSXML. IXMLDOMElement alone has the member function setAttribute. So I got the document element. pXMLDocumentElement -> get_documentElement (& pElement ); pElement -> selectSingleNode ( nodePathString ,& pNode ); . . . pElement -> setAttribute ( bstr , var ); I selected the required node in which the attribute has to be set using selectSingleNode function. After selecting the required node, I tried to set attribute. But the PElement pointer does not shift to the required node. It stayed on the root node. Result: added the attribute in root itself. Is there any way, I can shift my PElement to the node resulted in selectSingleNode function? So that I can set the attribute.
I think you have to use the setAttributeNode API on your pNode pointer. While you are at it read this tutorial on using MSXML. And after you have the basics covered this blog.
1,371,608
1,371,629
C++ pointer to class
Can anyone tell me what the difference is between: Display *disp = new Display(); and Display *disp; disp = new Display(); and Display* disp = new Display(); and Display* disp(new Display());
The first case: Display *disp = new Display(); Does three things: It creates a new variable disp, with the type Display*, that is, a pointer to an object of type Display, and then It allocates a new Display object on the heap, and It sets the disp variable to point to the new Display object. In the second case: Display *disp; disp = new GzDisplay(); You create a variable disp with type Display*, and then create an object of a different type, GzDisplay, on the heap, and assign its pointer to the disp variable. This will only work if GzDisplay is a subclass of Display. In this case, it looks like an example of polymorphism. Also, to address your comment, there is no difference between the declarations: Display* disp; and Display *disp; However, because of the way C type rules work, there is a difference between: Display *disp1; Display* disp2; and Display *disp1, disp2; Because in that last case disp1 is a pointer to a Display object, probably allocated on the heap, while disp2 is an actual object, probably allocated on the stack. That is, while the pointer is arguably part of the type, the parser will associate it with the variable instead.
1,371,710
1,371,733
Accessing variables from a struct
How can we access variables of a structure? I have a struct: typedef struct { unsigned short a; unsigned shout b; } Display; and in my other class I have a method: int NewMethod(Display **display) { Display *disp=new Display(); *display = disp; disp->a=11; } What does **display mean? To access variables of struct I have used ->, are there other methods too?
As Taylor said, the double asterisk is "pointer to pointer", you can have as many levels of pointers as you need. As I'm sure you know, the arrow operator (a->b) is a shortcut for the asterisk that dereferences a pointer, and the dot that accesses a field, i.e. a->b = (*a).b; The parentheses are necessary since the dot binds tighter. There is no such operator for double asterisks, you have to first de-reference to get to the required level, before accessing the fields: Display **dpl = ...; (*dpl)->a = 42; or (**dpl).a = 42;
1,371,786
1,371,796
C++ string in classes
I know this is quite a ridiculous question but this is quite confusing and irritating, as something that should work simply is not. I'm using Code Blocks with the GCC compiler and I am trying to simply create a string variable in my class #ifndef ALIEN_LANGUAGE #define ALIEN_LANGUAGE #include <string> class Language { public: private: string str; }; #endif Strange enough, my compiler halts me with an error saying this: C:\Documents and Settings\...|11|error: `string' does not name a type| ||=== Build finished: 1 errors, 0 warnings ===| For some reason, it is unable to find the class "string" which for some reason, my main.cpp is able to detect "#include " while my language class is not able for some reason. This is the main I wrote quickly just to see it main itself is able to see the string file: //main.cpp #include <iostream> #include <string> #include "alien_language.h" using namespace std; int main() { string str; return 0; } Does anyone know what's going on?
using namespace std; That's what's going on. You don't have std:: prefixing the string in your class. Everything in the standard library is in the namespace std. It is generally regarded as bad practice to use using namespace std;, by the way. For more information on why and what to do instead, check out this question: Using std Namespace.
1,372,150
1,372,219
Linux IDE with proper support for STL debugging
I am looking for a Linux IDE with support for STL debugging. the problem is that with Eclipse CDT, if I inspect the vector after the push_back: int main() { vector<string> v; v.push_back("blah"); return 0; } I get something hostile like {<std::_Vector_base<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >> = {_M_impl = {<std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >> = {<__gnu_cxx::new_allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >> = {<No data fields>}, <No data fields>}, _M_start = 0x1fee040, _M_finish = 0x1fee048, _M_end_of_storage = 0x1fee048}}, <No data fields>} instead of something like vector["blah"] or something similar. is there an alternative IDE/Debugger for linux that provides better STL support?
QtCreator has debugger dumpers for the Qt containers, some of the STL containers and a bunch of the Qt classes. It's also more responsive than Eclipse. See Qt Creator debugger dumpers.
1,372,186
1,372,194
Functions accepting C/C++ array types
It seems like g++ ignores difference in array sizes when passing arrays as arguments. I.e., the following compiles with no warnings even with -Wall. void getarray(int a[500]) { a[0] = 1; } int main() { int aaa[100]; getarray(aaa); } Now, I understand the underlying model of passing a pointer and obviously I could just define the function as getarray(int *a). I expected, however, that gcc will at least issue a warning when I specified the array sizes explicitly. Is there any way around this limitation? (I guest boost::array is one solution but I have so much old code using c-style array which got promoted to C++...)
Arrays are passed as a pointer to their first argument. If the size is important, you must declare the function as void getarray(int (&a)[500]); The C idiom is to pass the size of the array like this: void getarray(int a[], int size); The C++ idiom is to use std::vector (or std::tr1::array more recently).
1,372,288
1,372,306
Vector Iterators Casting
Hey, In C++, I have a vector of type: vector<BaseClass*> myVector; In which, I insert (push_back) pointers of derived classes into it. Now, I want to pop back its elements so I do this: vector<ADlgcDev*>::iterator iter; for (iter = myVector.rbegin(); iter != myVector.rend(); iter++) { // but before I pop it, I need to shutdown it down // so I cast this // but this way, I'm unable to call the function (DerivedClass*(*iter))->Shutdown(); myVector.pop_back(); } but as mention in the comments before I pop it, I need to call its Shutdown() method and the cast is not working properly too. Any resolutions? or is impossible?
while (!myVector.empty()) { ((DerivedClass*)(myVector.back()))->Shutdown(); myVector.pop_back(); } Notes: You should probably use dynamic_cast instead of the hard cast. (If it's sure that there are only DerivedClass objects in the vector, why isn't it std::vector<DerivedClass>?) You should probably not have to cast at all, since Shutdown() should be declared in the base class. You should probably delete the objects, too, before you pop them off the vector. (But that might not be so.) You should probably use a smart pointer which calls Shutdown() (and delete, probably). Edit: Using std::vector<T>::clear(), as shown by markh44 is probably better than the pop_back().
1,372,531
1,372,721
Algorithm to filter a set of all phrases containing in other phrase
Given a set of phrases, i would like to filter the set of all phrases that contain any of the other phrases. Contained here means that if a phrase contains all the words of another phrase it should be filtered out. Order of the words within the phrase does not matter. What i have so far is this: Sort the set by the number of words in each phrase. For each phrase X in the set: For each phrase Y in the rest of the set: If all the words in X are in Y then X is contained in Y, discard Y. This is slow given a list of about 10k phrases. Any better options?
This is the problem of finding minimal values of a set of sets. The naive algorithm and problem definition looks like this: set(s for s in sets if not any(other < s for other in sets)) There are sub-quadratic algorithms to do this (such as this), but given that N is 10000 the efficiency of the implementation probably matters more. The optimal approach depends heavily on the distribution of the input data. Given that the input sets are natural language phrases that mostly differ, the approach suggested by redtuna should work well. Here's a python implementation of that algorithm. from collections import defaultdict def find_minimal_phrases(phrases): # Make the phrases hashable phrases = map(frozenset, phrases) # Create a map to find all phrases containing a word phrases_containing = defaultdict(set) for phrase in phrases: for word in phrase: phrases_containing[word].add(phrase) minimal_phrases = [] found_superphrases = set() # in sorted by length order to find minimal sets first thanks to the # fact that a.superset(b) implies len(a) > len(b) for phrase in sorted(phrases, key=len): if phrase not in found_superphrases: connected_phrases = [phrases_containing[word] for word in phrase] connected_phrases.sort(key=len) superphrases = reduce(set.intersection, connected_phrases) found_superphrases.update(superphrases) minimal_phrases.append(phrase) return minimal_phrases This is still quadratic, but on my machine it runs in 350ms for a set of 10k phrases containing 50% of minimal values with words from an exponential distribution.
1,372,554
1,372,596
LibCurl Unicode data
I'm writing an application, and I'm currently using libcurl. The libcurl callback function works fine when I implement it for the Ansi charset, but I fail to get it working when working with Unicode characters. int CURLConnectorAnsi::BufferWriter(char* data, size_t size, size_t nmemb, std::string* buffer) { int ReadBytes = 0; if (buffer != NULL) { buffer->append(data, size * nmemb); ReadBytes = size * nmemb; } return ReadBytes; } This snippet works fine, and returns the contents of the website that I website that I've read. Does anyone know how I can pass the data correctly into a wstring instead of a string? EDIT: I'm trying to manage to get the data in a correct wchar_t* buffer instead (first parameter which is a void* according to curl) of the character buffer, I don't want to know how to add Ansi data into a Unicode buffer. Thanks!
Basically, it has nothing to do with curl and you're facing the problem of converting utf-8 to wide string. You can use something like Glib::ustring class or implement it on your own, or take a look at this code.
1,372,589
1,372,900
How can I build imagemagick without any asserts
Right now I'm using the following: export CFLAGS="-O2-isysroot/Developer/SDKs/MacOSX10.5.sdk -arch i386 -I/sw/include/" export LDFLAGS="-Wl,-syslibroot,/Developer/SDKs/MacOSX10.5.sdk,-L/sw/lib/" sudo ./configure --prefix=/sw --with-quantum-depth=16 --disable-dependency-tracking --with-x=no --without-perl --enable-static --disable-shared --with-jpeg --with-tiff --disable-assert make The code above still generates an 'identify' tool with asserts. I'm testing this by identifying a corrupted png image. Identify just crashes/exits with an assert. I'm running this on a Mac. Any suggestions to build release mode without any asserts? (I'm anticipating a really simple solution :) )
When running configure do this: ./configure DEFS=-DNDEBUG The idea is to have NDEBUG defined.
1,372,916
1,372,950
system("c:\\sample\\startAll.bat") cannot run because of working directory?
I have an application and executables. I want my application to run my executables. The executable files are in a folder, lets say in "c:\sample". In this directory there is a batch file that calls my exe's. like: start a1.exe start a2.exe start a3.exe let's name it as startAll.bat and suppose every exe has a data like a1.dat a2.dat ... and these data files are near this exe's. I want to call this batch file by my application. system("c:\\\\sample\\\\startAll.bat"); when I call it like that, command cannot find these exe's. if I add directory names to batch files, it can not find the data that time. I think it is because of working directory. start c:\sample\a3.exe how can I change the working directory before I call this batch file? or do you suggest anything else?
Call chdir("C:\\sample") before calling system(...) Or put a cd command in your batch file EDIT Since you're not on C: the first lines of the batch script should be C: cd \sample EDIT2 Using the suggestions made by Johannes and MattH a much better version of the BAT file would start with something like this setlocal set BATDIR=%~dp0 cd /d %BATDIR% Now the bat file will work regardless of the directory it's in as there are no hard coded paths. SETLOCAL is used to avoid side effects from running the script (like changing directory or setting environment variables)
1,373,062
1,373,171
What are the known C/C++ optimizations for GCC
I am have a lot of code that I need to optimize and make it run faster. I used opreport to tell me where the code spends a lot of time. I use the following command to get the statistics opreport -g -l -d Suggestions to get better statistics are appreciated using different flags, perhaps find it per line number instead of function number. So a lot of issues that I "think" I see are in regard to: pointers, multidimensional arrays multiplications loops I want compiler to optimize the code better, thus helping him. I factored some code blocks into function with word restrict to tell compiler that my pointer arrays don't overlap. SO I am I am looking for (a) common C constructs that can make code run longer and (b) how to help compiler optimize code. Thanks
Beware of the reports from profiling tools, they can be misleading. For instance, consider an application that does a large amount of string comparisons and not much else. A report is going to tell you that you spend >90% of your time in string comparison functions. So naturally, you decide to implement an optimized version of that code only find out that the profiler tells you that you are still spending 90% of your time there (because that is all your program does...). You have to have intimate knowledge of your application and apply that to a profiler else you might be wasting effort. Compilers today do a fairly good job of optimizing (especially with extra flags as options). It is unlikely that you will benefit from anything at a language level (i.e. how you handle arrays) - you will probably have to read/write asm if you want to hand tune things.
1,373,369
1,373,422
Which is faster/preferred: memset or for loop to zero out an array of doubles?
double d[10]; int length = 10; memset(d, length * sizeof(double), 0); //or for (int i = length; i--;) d[i] = 0.0;
Note that for memset you have to pass the number of bytes, not the number of elements because this is an old C function: memset(d, 0, sizeof(double)*length); memset can be faster since it is written in assembler, whereas std::fill is a template function which simply does a loop internally. But for type safety and more readable code I would recommend std::fill() - it is the c++ way of doing things, and consider memset if a performance optimization is needed at this place in the code.
1,373,402
1,373,936
Switching callstack for C++ functions
Here's my previous question about switching C callstacks. However, C++ uses a different calling convention (thiscall) and may require some different asm code. Can someone explain the differences and point to or supply some code snippets that switch C++ callstacks (preferably in GCC inline asm)? Thanks, James
The code given in the previous question should work fine. The thiscall calling convention differs only in who is responsible for popping the arguments off the stack. Under the thiscall calling convention, the callee pops the arguments (and additionally, the this pointer is passed in ecx); under the C calling convention, the caller pops the arguments. This does not affect context switches. However, if you're going to do context switches yourself, note that you need to save and restore the registers as well (probably on the stack) in addition to switching stacks. Note, by the way, that C++ doesn't always use thiscall -- it's only used for methods with a fixed number of arguments (and apart from that, it's a Microsoftism... g++ doesn't use it).
1,373,456
1,378,586
How to reduce memory consumption in MingW based GUI Application?
I just noticed the memory usage of a simple win32 C based GUI application with single main window taking around 3 MB memory ( via Task Manager ) I used Dev-c++ and Mingw as compiler , and generated windows application via project wizard. why that so ? is there any way to reduce it ?
Found one API which can control the application memory set , This code can show a better result in Task manager. SetProcessWorkingSetSize(GetCurrentProcess(), (SIZE_T) -1, (SIZE_T) -1);
1,373,540
1,373,727
Differences in Microsofts C++ STL for Windows CE?
anyone know of a complete list of the differences in Microsofts implementation of STL for Windows CE, compared to the full STL for desktop? I am using WinCE 6.0, with VS 2005. I am a bit suprised that they seem to have removed so many things; for GCC it is almost the same. Thanks!
according to Standard C++ Library Reference for Devices, the (only) differences are: New Functionality Stream support has been added to this version of the Standard C++ Library. Unsupported Functionality The Standard C++ Library for devices does not include locale support. uncaught_exception is only supported on Windows CE 5.0 and higher versions, including Windows Mobile 2005 platforms. Unsupported Headers The device version of the Standard C++ Library does not support the following headers: <cerrno> <csignal> <locale>
1,373,686
1,373,744
Unable to catch c++ exception using catch (...)
I have a third-party library that is sometimes throwing an exception. So I decided to wrap my code in a try/catch(...) so that I could log information about the exception occurring (no specific details, just that it happened.) But for some reason, the code still crashes. On client computers, it crashes hard and the code to log the exception in the catch(...) never gets executed. If I run this on my debug / development machine I get the popup asking me if I want to debug. When I do this, it reports 0xC0000005: Access violation reading location XXX. The odd thing is that with an older version of the third-party library, the exact same code DOES catch the exception, and the code to log the exception DOES execute. (I verified this within VS watching the same conditions occur.) Here's the pseudo-code that is executing: pObject = pSystem->Get_pObject() pSystem->DoSomethingThatMightDestroy_pObject(); try { /* Call to third party function that is throwing exception */ pObject->SetValue(0); } catch (...) { __DEBUG_LOG_POSITION__; // A macro to log the current file line // This code used to run in the older version of third-party library // but the newer version just crashes before running the catch(...) } So I have two questions: Is there some change in the way the third party might have compiled the library so that my code wouldn't be able to catch the exception? (Yes, there is a chance I can get the third party to make whatever fixes are necessary and recompile for me, if I know what to tell them.) Assuming I can't get the third party to fix it, what can I do to catch these exceptions? I'm thinking along the lines of... is there some way for me to determine whether pObject was deallocated?
AFAIK access violation don't throw exception... at least not standard ones! Maybe catching windows-specific "native" exception would help : https://web.archive.org/web/20081022160935/http://www.gamedev.net/reference/articles/article2488.asp
1,373,889
1,373,909
c++ how to create a directory from a path
what is a convenient way to create a directory when a path like this is given: "\server\foo\bar\" note that the intermediate directories may not exist. CreateDirectory and mkdir only seem to create the last part of a directory and give an error otherwise. the platform is windows, MSVC compiler. thanks!
SHCreateDirectoryEx() can do that. It's available on XP SP2 and newer versions of Windows.
1,373,896
1,374,266
boost make_shared takes in a const reference. Any way to get around this?
I am using boost shared pointers in my program, and I have a class that takes as a parameters a reference to another object. The problem I am running into is the make_shared function requires all parameters to be a const reference, and I get compile errors if my class's constructor doesn't allow const reference parameters to be passed in. Does anyone know the reason behind this? Also, is there anything I can do to get around this? code example of what is giving me problems: class Object { public: Object(int& i) { i = 2; } }; int main(int argc, char *argv[]) { int i = 0; boost::shared_ptr<Object> obj = boost::make_shared<Object>(i); return 1; } This results in a compiler error that states the following :make_shared.hpp:185: error: no matching function for call to `Object::Object(const int&)' note: candidates are: Object::Object(const Object&) note: Object::Object(int&) If the parameter to Objects constructor is a const int, this works. I am curious as to why make_shared behaves this way.
http://www.boost.org/doc/libs/1_39_0/libs/smart_ptr/make_shared.html says: "If you need to pass a non-const reference to a constructor of T, you may do so by wrapping the parameter in a call to boost::ref." Other text on that page seems to support Rüdiger Hanke's answer.
1,373,902
1,430,169
Benefit cost analysis libraries
I was wondering if there are any opensource libraries that are geared towards transportation ben/cost analysis. I currently use microBENCOST and would like to build my own solution. I'm most comfortable with C/c++ and Python. cheers
My girlfriend works for a transportation planning firm, and they use a variety of models developed in SPSS, with a lot of data munging in Excel and visualization in ArcGIS. As far as turnkey solutions go, though, I think you're going to be more or less on your own. Assuming you want to move on to something a bit newer/more maintainable than a DOS application like MicroBENCOST, though, I would second the recommendation to become comfortable with Scipy, and then start building up a toolbox of statistical models based on the original application. For other types of modeling, you may also find SimPy useful; it doesn't do the simplified cost/benefit analysis that MicroBENCOST does, but it may be applicable for more open-ended design problems where original discrete simulation models are called for.
1,373,940
1,374,006
Expected primary-expression before ',' token in strsafe.h
I'm trying to rebuild someone's old C++ project using Dev-C++ (version 4.9.9.2) and the standard compiler that it comes with (I think g++ using MinGW) under Windows XP Pro SP3 32-bit. In one of the files strsafe.h is included and when I try to compile, I get this error: expected primary-expression before ',' token The lines of code that the error points to are in strsafe.h (a Microsoft(?) library header file) all look something like this: hr = StringGetsExWorkerA(pszDest, cchDest, cbDest, NULL, NULL, 0); There are 2 "expected primary-expression" errors for each of these lines. I found this forum thread which suggests that the NULL value is not properly recognized and suggests that I include <cstddef> before strsafe.h. I did that and it doesn't work. Also, it appears that NULL is in fact defined, because when I do '#define NULL 0' before including strsafe.h I get an error telling me that I'm redefining it there. I'm sorry I can't provide any more details, but the code to reproduce this error is simply '#include <strsafe.h>', so I don't really know what else to say. Does anyone have any idea what might be going on and how I can fix this? Thanks! (I already tried downloading the latest version of the Microsoft Platform SDK so I have an up-to-date version of strsafe.h)
I wonder what NULL is defined as? Maybe it's not 0, it could be anything (though it would be really odd if someone defined NULL as something other than 0). Try the following and see if it works. #undef NULL #define NULL 0
1,374,081
1,374,125
How can I find the calling routine for a symbol in case of a linker error "undefined reference"?
I have a problem linking an application for an embedded target. I'm developing on a windows box using Min-GW for an ARM9 target that runs under Linux. Actually I'm switching from static linking to dynamic linking with .so-libraries to save memory space. I get the error message libT3Printer.so: undefined reference to `__ASSERT' I checked all the sources for the lib and I have no idea where this function could be called. Is there any possibility to find out, who (which source file or function) could be the caller of the missing function?
The reference is probably being hidden by a macro. If you run the compiler with the -E option to generate predecessor output you might have a better chance of tracking it down.
1,374,265
1,374,274
how can I use auto_ptr as member variable that handles another member variable
I have a class like this: class A { private: B* ptr; } But B ptr is shared among different A objects. How can I use auto_ptr so that when A gets destructed B stays on so that other A objects that point to the same ptr can continue without issues. Does this look ok: class A { public: auto_ptr< B > m_Ptr; private: B* ptr; } what are the different ways people have implemented this and any issues/advantages they saw one to another... Thanks
What you're looking for is shared_ptr. It handles exactly this type of scenario. http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/shared_ptr.htm This is a part of the BOOST library though and not STL so it may not be available on your particular platform. However if you google around a bit you can find a lot of standalone refcounted pointer implementations that will satisfy your needs here.
1,374,302
4,916,887
C++ Boost Code example of throwing an exception between threads
Can someone please show a simple, but complete example of how one could use Boost exception library to transfer exceptions between thread by modifying the code below? What I'm implementing is a simple multi-threaded Delegate pattern. class DelegeeThread { public: void operator()() { while(true) { // Do some work if( error ) { // This exception must be caught by DelegatorThread throw std::exception("An error happened!"); } } } }; class DelegatorThread { public: DelegatorThread() : delegeeThread(DelegeeThread()){} // launches DelegeeThread void operator()() { while( true ) { // Do some work and wait // ? What do I put in here to catch the exception thrown by DelegeeThread ? } } private: tbb::tbb_thread delegeeThread; };
I assumed you want the delegate to be executed asynchronously on a separate thread. Here is the example using boost threads and exceptions: #include <boost/exception/all.hpp> #include <boost/thread.hpp> #include <boost/bind.hpp> #include <iostream> class DelegeeThread { public: void operator()( boost::exception_ptr& excPtr ) { try { int counter = 0; while( true ) { // Do some work if( ++counter == 1000000000 ) { throw boost::enable_current_exception( std::exception( "An error happened!" ) ); } } } catch( ... ) { // type of exception is preserved excPtr = boost::current_exception(); } } }; class DelegatorThread { public: DelegatorThread() : delegeeThread( boost::bind( &DelegeeThread::operator(), boost::ref( delegee ), boost::ref( exceptionPtr ) ) ) { // launches DelegeeThread } void wait() { // wait for a worker thread to finish delegeeThread.join(); // Check if a worker threw if( exceptionPtr ) { // if so, rethrow on the wait() caller thread boost::rethrow_exception( exceptionPtr ); } } private: DelegeeThread delegee; boost::thread delegeeThread; boost::exception_ptr exceptionPtr; }; int main () { try { // asynchronous work starts here DelegatorThread dt; // do some other work on a main thread... dt.wait(); } catch( std::exception& e ) { std::cout << e.what(); } system("pause"); return 0; }
1,374,325
1,374,366
Is there any difference between type casting & type conversion?
Is there any difference between type casting & type conversion in c++.
Generally, casting refers to an explicit conversion, whether it's done by C-style cast (T(v) or (T)v) or C++-style cast (static_cast, const_cast, dynamic_cast, or reinterpret_cast). Conversion is generally a more generic term used for any time a variable is converted to another: std::string s = "foo"; // Conversion from char[] to char* to std::string int i = 4.3; // Conversion from float to int float *f = reinterpret_cast<float*>(&i); // (illegal) conversion from int* to float*
1,374,372
1,374,444
How to quickly find maximal element of a sum of vectors?
I have a following code in a most inner loop of my program struct V { float val [200]; // 0 <= val[i] <= 1 }; V a[600]; V b[250]; V c[250]; V d[350]; V e[350]; // ... init values in a,b,c,d,e ... int findmax(int ai, int bi, int ci, int di, int ei) { float best_val = 0.0; int best_ii = -1; for (int ii = 0; ii < 200; ii++) { float act_val = a[ai].val[ii] + b[bi].val[ii] + c[ci].val[ii] + d[ci].val[ii] + e[ci].val[ii]; if (act_val > best_val) { best_val = act_val; best_ii = ii; } } return best_ii; } I don't care whether it will be some clever algorithm (but this would be most interesting) or some C++ tricks or intrinsics or assembler. But I need to make findmax function more efficient. Big thanks in advance. Edit: It seems that branch is the slowest operation (misprediction?).
Well, I see no obvious room for algorithmic optimizations. Theoreticaly one could only calculate the sum of the five vectors until it is obvious that the maximum cannot be reached, but this would add way to much overhead for only summing five numbers. You could try using multiple threads and assign ranges to the threads, but you have to think about the thread creation overhead when you have only 200 very short work items. So I tend to say that using Assembler and MMX or SSE instructions on x86 or maybe a (machine specific) C++ a library providing access to this instructions is your best bet.
1,374,468
1,374,485
stringstream, string, and char* conversion confusion
My question can be boiled down to, where does the string returned from stringstream.str().c_str() live in memory, and why can't it be assigned to a const char*? This code example will explain it better than I can #include <string> #include <sstream> #include <iostream> using namespace std; int main() { stringstream ss("this is a string\n"); string str(ss.str()); const char* cstr1 = str.c_str(); const char* cstr2 = ss.str().c_str(); cout << cstr1 // Prints correctly << cstr2; // ERROR, prints out garbage system("PAUSE"); return 0; } The assumption that stringstream.str().c_str() could be assigned to a const char* led to a bug that took me a while to track down. For bonus points, can anyone explain why replacing the cout statement with cout << cstr // Prints correctly << ss.str().c_str() // Prints correctly << cstr2; // Prints correctly (???) prints the strings correctly? I'm compiling in Visual Studio 2008.
stringstream.str() returns a temporary string object that's destroyed at the end of the full expression. If you get a pointer to a C string from that (stringstream.str().c_str()), it will point to a string which is deleted where the statement ends. That's why your code prints garbage. You could copy that temporary string object to some other string object and take the C string from that one: const std::string tmp = stringstream.str(); const char* cstr = tmp.c_str(); Note that I made the temporary string const, because any changes to it might cause it to re-allocate and thus render cstr invalid. It is therefor safer to not to store the result of the call to str() at all and use cstr only until the end of the full expression: use_c_str( stringstream.str().c_str() ); Of course, the latter might not be easy and copying might be too expensive. What you can do instead is to bind the temporary to a const reference. This will extend its lifetime to the lifetime of the reference: { const std::string& tmp = stringstream.str(); const char* cstr = tmp.c_str(); } IMO that's the best solution. Unfortunately it's not very well known.
1,374,695
1,374,713
simple C++ hash_set example
I am new to C++ and STL. I am stuck with the following simple example of a hash set storing custom data structures: #include <iostream> #include <ext/hash_set> using namespace std; using namespace __gnu_cxx; struct trip { int trip_id; int delta_n; int delta_secs; trip(int trip_id, int delta_n, int delta_secs){ this->trip_id = trip_id; this->delta_n = delta_n; this->delta_secs = delta_secs; } }; struct hash_trip { size_t operator()(const trip t) { hash<int> H; return H(t.trip_id); } }; struct eq_trip { bool operator()(const trip t1, const trip t2) { return (t1.trip_id==t2.trip_id) && (t1.delta_n==t2.delta_n) && (t1.delta_secs==t2.delta_secs); } }; int main() { hash_set<trip, hash_trip, eq_trip> trips; trip t = trip(3,2,-1); trip t1 = trip(3,2,0); trips.insert(t); } when I try to compile it, I get the following error message: /usr/include/c++/4.2.1/ext/hashtable.h: In member function ‘size_t __gnu_cxx::hashtable<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey, _Alloc>::_M_bkt_num_key(const _Key&, size_t) const [with _Val = trip, _Key = trip, _HashFcn = hash_trip, _ExtractKey = std::_Identity<trip>, _EqualKey = eq_trip, _Alloc = std::allocator<trip>]’: /usr/include/c++/4.2.1/ext/hashtable.h:599: instantiated from ‘size_t __gnu_cxx::hashtable<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey, _Alloc>::_M_bkt_num(const _Val&, size_t) const [with _Val = trip, _Key = trip, _HashFcn = hash_trip, _ExtractKey = std::_Identity<trip>, _EqualKey = eq_trip, _Alloc = std::allocator<trip>]’ /usr/include/c++/4.2.1/ext/hashtable.h:1006: instantiated from ‘void __gnu_cxx::hashtable<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey, _Alloc>::resize(size_t) [with _Val = trip, _Key = trip, _HashFcn = hash_trip, _ExtractKey = std::_Identity<trip>, _EqualKey = eq_trip, _Alloc = std::allocator<trip>]’ /usr/include/c++/4.2.1/ext/hashtable.h:437: instantiated from ‘std::pair<__gnu_cxx::_Hashtable_iterator<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey, _Alloc>, bool> __gnu_cxx::hashtable<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey, _Alloc>::insert_unique(const _Val&) [with _Val = trip, _Key = trip, _HashFcn = hash_trip, _ExtractKey = std::_Identity<trip>, _EqualKey = eq_trip, _Alloc = std::allocator<trip>]’ /usr/include/c++/4.2.1/ext/hash_set:197: instantiated from ‘std::pair<typename __gnu_cxx::hashtable<_Value, _Value, _HashFcn, std::_Identity<_Value>, _EqualKey, _Alloc>::const_iterator, bool> __gnu_cxx::hash_set<_Value, _HashFcn, _EqualKey, _Alloc>::insert(const typename __gnu_cxx::hashtable<_Value, _Value, _HashFcn, std::_Identity<_Value>, _EqualKey, _Alloc>::value_type&) [with _Value = trip, _HashFcn = hash_trip, _EqualKey = eq_trip, _Alloc = std::allocator<trip>]’ try.cpp:45: instantiated from here /usr/include/c++/4.2.1/ext/hashtable.h:595: error: passing ‘const hash_trip’ as ‘this’ argument of ‘size_t hash_trip::operator()(trip)’ discards qualifiers What am I doing wrong?
So close! The last error in your output reveals your hash_trip routine should be declared const: size_t operator()(const trip t) const // note the ending 'const' { //... } You'll probably need to do the same thing for eq_trip. Also, I would recommend passing the arguments to these functions by constant reference to avoid an unnecessary copy of the data you're passing: size_t operator()(const trip& t) const // note the '&' { //... }
1,374,840
1,374,855
Should boost::ptr_vector be used in place std::vector all of the time?
Just a conceptual question that I've been running into. In my current project it feels like I am over-using the boost smart_ptr and ptr_container libraries. I was creating boost::ptr_vectors in many different objects and calling the transfer() method to move certain pointers from one boost::ptr_vector to another. It is my understanding that it is important to clearly show ownership of heap allocated objects. My question is, would it be desirable to use these boost libraries to create heap-allocated members that belong to an object but then use normal pointers to these members via get() when doing any processing. For example... A game might have a collection of Tiles that belong to it. It might make sense to create these tiles in a boost::ptr_vector. When the game is over these tiles should be automatically freed. However if I want to put these Tiles in a Bag object temporarily, should I create another boost::ptr_vector in the bag and transfer the Game's Tiles to the Bag via transfer() or should I create a std::vector<Tile*> where the Tiles*'s reference the Tiles in the Game and pass that to the Bag? Thanks. **Edit I should point out that in my example The Game would have a Bag object as a member. The Bag would only be filled with Tiles the game owns. So the Bag would not exist without the Game.
You should only use owning smart pointers and pointer containers where there's clear transfer of ownership. It doesn't matter if the object is temporary or not - all that matters is whether it has ownership or not (and, therefore, whether the previous owner relinquishes ownership). If you create a temporary vector of pointers just to pass it to some other function, and the original ptr_vector still references all those objects, there's no ownership transfer, and therefore you should use plain vector for the temporary object - just as you'd use a raw pointer to pass a single object from ptr_vector to a function that takes a pointer, but doesn't store it anywhere.
1,375,201
1,375,324
Lazy C++ - Chicken and Egg Problem
Based on feedback I got from this question, I'm interested in using Lazy C++ on my OSX laptop. The Lazy C++ webpage has binaries for Linux and Windows available, but nothing for OSX. There's also a link to download for the Lazy C++ source, but it requires a lzz binary as part of the build process. This creates a situation where I need an lzz binary in order to get an lzz binary. How can I build lzz on my laptop without an lzz binary? Do I need to do part of the build on a Linux or Windows machine to preprocess the lzz source files, and then transfer the source over to my laptop for building? Or is there something else that I should try?
Given that Lazy C++ appears to be a sort of a preprocessor - generating source files as output - you could probably compile it to completion on a supported platform like Windows, take all the generated files and compile it from these generated files again on OSX. Depending on how complex the build system (Makefiles, in this case) of Lazy C++ is - this is going to be trivial, very complicated or anywhere in between...
1,375,351
1,375,366
How does fprintf work in C++?
How does fprintf work? If I write fprintf(outfile, "test %d %d 255/r", 255, 255); What does it mean? I know that outfile is the name my of output file. What would the other values mean?
"test %d %d 255/r" tells that after it will be arguments (and they are there: 255, 255) and they are expected to be of integer type. And they will be placed instead of %d. In result you'll get string test 255 255 255 in your file. For more infrormation read std::fprintf reference.
1,375,854
1,376,148
If I store a member as an object, will I incur an object copy during constuction?
If the constructor for Door looks like this: Door::Door(Doorknob doorknob) : m_doorknob(doorknob) { } Then you would instantiate a Door like this: Doorknob doorknob; Door door(doorknob); // Does an object copy of doorknob occur here? It seems like if you store Doorknob as a pointer, you can explicitly avoid the copy: Door::Door(Doorknob * doorknob_ptr) : m_doorknob_ptr(doorknob_ptr) { } Instantiate Door like this: Door door(new Doorknob); But now you have to make sure to delete doorknob inside Door's destructor, which seems ugly. What is the preferred approach?
More important than minimizing the number of copy constructor calls is that your code correctly models the problem space. Door owns the doorknob; i.e. the lifecycle of DoorKnob is the same as that of Door. Thus, Door should manage the lifecycle of Doorknob. The second solution is not be preferred for that reason. You are relying on the client to manufacture the Doorknob object, which you then store a pointer to, which is a violation of RAII. Your first solution is acceptable, but as you note, as the problem of making an unnecessary copy of the Doorknob object, since copies as a parameter. The ideal solution is to have contructor take in a reference, as @pingw33n's solution does. Or, since it may not make sense to construct a Doorknob outside of a door, have your Door constructor create the Door.
1,375,874
1,375,937
C++ privately constructed class
How can I call a function and keep my constructor private? If I make the class static, I need to declare an object name which the compiler uses to call the constructor, which it cannot if the constructor is private (also the object would be extraneous). Here is the code I am attempting to use (it is not compilable): I want to keep the constructor private because I will later be doing a lot of checks before adding an object, modifying previous objects when all submitted variables are not unique rather than creating new objects. #include <iostream> #include <fstream> #include <regex> #include <string> #include <list> #include <map> using namespace std; using namespace tr1; class Referral { public: string url; map<string, int> keywords; static bool submit(string url, string keyword, int occurrences) { //if(Referrals.all.size == 0){ // Referral(url, keyword, occurrences); //} } private: list<string> urls; Referral(string url, string keyword, int occurrences) { url = url; keywords[keyword] = occurrences; Referrals.all.push_back(this); } }; struct All { list<Referral> all; }Referrals; int main() { Referral.submit("url", "keyword", 1); }
Based on your main code I think what you're shooting for is a singleton, which would look something like: class Referral { private: Referral() { //... } public: static Referral& instance() { static Referral instance_s; return instance_s; } bool submit(string url, string keyword, int occurrences) { //... } }; Then your call in main would look like: int main() { Referral::instance().submit("url", "keyword", 1); } Another possibility is that you're looking to keep a list of Referrals around, in which case you can use a struct and a list of them to accomplish what you're looking for: struct Referral { Referral(string url, string keyword, int occurrences) : url_m(url), keyword_m(keyword), occurrences_m(occurrences) { } string url_m; string keyword_m; int occurrences_m; }; typedef std::vector<Referral> ReferralSet; Then your call in main would look like: int main() { ReferralSet set; set.push_back(Referral("url", "keyword", 1)); }
1,376,036
1,377,044
Getting a list of user profiles on a computer in C++ Win32
What is the best way to enumerate all of the user profiles on a computer? I know how to get the currently logged in user profile, and I know how to get the "all user" profile. But I'd like to get a list of each and every profile on the computer.
Before going the undocumented route like flokra suggests, I would try NetUserEnum() or NetQueryDisplayInformation() If you want to go into undocumented land, HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList has a (incomplete) list of accounts (It's missing special accounts like ASPNET, HelpAssistant and SUPPORT_xxxx) It also has the path to the profile folder, which is a lot safer than using %ALLUSERSPROFILE%\..\ but why use it when there is GetProfilesDirectory()
1,376,085
1,376,099
C++: Safe to use longjmp and setjmp?
Is it safe to use longjmp and setjmp in C++ on linux/gcc with regards to the following? Exception handling (I'm not implementing exception handling using longjmp/setjmp. I want to know what side effects longjmp/setjmp will have on standard exception handling) *this pointer Signals Smart pointers (boost's shared and intrusive pointers) Anything else you can think of.
setjmp()/longjmp() completely subvert stack unwinding and therefore exception handling as well as RAII (destructors in general). From 18.7/4 "Other runtime support" in the standard: If any automatic objects would be destroyed by a thrown exception transferring control to another (destination) point in the program, then a call to longjmp(jbuf, val) at the throw point that transfers control to the same (destination) point has undefined behavior. So the bottom line is that setjmp()/longjmp() do not play well in C++.
1,376,159
1,376,170
paste code with syntax colors and alignment
I am looking for some blog site where i will be able to directly paste c++ code examples in my publishes and see the code with all the alignments and colors like i see it on pastie.org. I need all those things be made automatically because i don't know HTML and can't make by myself the code changes.
Get wordpress + WP-Syntax. You won't be able to "copy and paste" the code directly, but you'll have to wrap it like this: <pre lang="c++"> CODE GOES HERE </pre>
1,376,264
1,376,298
Initializing static array of strings (C++)?
I can't for the life of me figure out how to do this properly. I have a class that needs to store some constants (text that corresponds to values in an enum type) - I have it declared like this (publicly) in my class: const static char* enumText[]; And I'm trying to initialize it like this: const char* MyClass::enumText[] = { "A", "B", "C", "D", "E" }; However gcc gives me the following error: 'const char* MyClass::enumText[]' is not a static member of 'class MyClass' What am I doing wrong? Thanks!
This code compiles: struct X { static const char* enumtext[]; }; const char* X::enumtext[] = { "A", "B", "C" }; Check your code and find differences. I can only think that you did not define the static attribute in the class, you forgot to include the header or you mistyped the name.
1,376,626
1,376,635
More efficient way of dealing with my data (ints vs floats)
My brain farts a lot when it comes to hex. Some people are abidextrous and others are just plain right handed... well, kind of like that, I'm VERY base10 I guess. Anyway... I'm trying to make some firmware more efficient. We have a function that's calculating a vehicle's speed based on some hex data it gets via the CANBUS. Right now I'm converting it to a float so I can wrap my head around it but I'm wondering if we'd use less ROM space if we left it in integer format? Can that be done without losing accuracy? Right now my floats are accurate to 1/16th of a kph. I know this function seems simple, but running hundreds of times per second it is bogging it down a little. First, here is some sample data: [06] [3c] ... [06] [3a] ... [06] [3b] ... [06] [46] ... [06] [3b] ... I've left off the other 6 bytes as they don't relate to speed. The byte on the left we'll call speed_a and the byte on the right is speed_b. Here is the function to convert: float calculateSpeed() { float speed; speed = ( ( float )speed_a * 256.0 + speed_b ) / 16.0; return speed; } So the data above would translate to: 99.7500 99.6250 99.6875 100.3750 99.6875 and that does accurately reflect the true speed of the vehicle in kph. For our application though, we don't really care what the true speed is because everything is relative. As long as we don't lose resolution we're happy. I thought about just keeping everything in INT form, but then when you divide by 16 it just truncates. I'm not an idiot about most things... but I'm an idiot with base2. Lil' help? Thanks.
Simply don't divide by 16.0. You can still compare, sort, add or subtract speeds.
1,376,792
1,376,794
c++ template syntax error
My C++ is a little rusty having worked in Java and C# for the last half dozen years. I've got a stupid little error that I just cannot figure out. I've pared the code down as much as possible. #include <list> template<class T> class Subscriber { virtual void published( T t ) = 0; }; template <class T> class PubSub { private: std::list< Subscriber<T>* > subscribers; public: void publish( T t ); }; template<class T> void PubSub<T>::publish( T t ) { for( std::list< Subscriber<T>* >::iterator i = subscribers.begin(); i != subscribers.end(); ++i ) i->published( t ); } When I try and compile this (by including this header file in a code file), I get the following error: ../util/pubsub.h: In member function ‘void PubSub<T>::publish(T)’: ../util/pubsub.h:18: error: expected `;' before ‘i’ ../util/pubsub.h:18: error: ‘i’ was not declared in this scope What am I missing here?
for( typename std::list< Subscriber<T>* >::iterator i = ... ^^^^^^^^
1,376,947
1,377,518
Newbie Problem: C/C++ with Eclipse
My setup includes: Windows Vista, Eclipse 3.5.0, and gdb, make, gcc 3.4.4, g++ 3.4.4 enabled through Cygwin, and environmental variable is already set. My FIRST problem is that I can run and build an application like the information in Console: **** Build of configuration Debug for project HelloWorld **** make all <br /> Building file: ../src/HelloWorld.cpp <br /> Invoking: Cygwin C++ Compiler <br /> g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/HelloWorld.d" <br /> -MT"src/HelloWorld.d" -o"src/HelloWorld.o" "../src/HelloWorld.cpp" <br /> Finished building: ../src/HelloWorld.cpp <br /> Building target: HelloWorld.exe <br /> Invoking: Cygwin C++ Linker <br /> g++ -o"HelloWorld.exe" ./src/HelloWorld.o <br /> Finished building target: HelloWorld.exe <br /> But in the Problems view, I still have the following warnings, Error launching external scanner info generator (g++ -E -P -v -dD F:/workspace/.metadata/.plugins/org.eclipse.cdt.make.core/specs.cpp) <br /> Error launching external scanner info generator (g++ -E -P -v -dD F:/workspace/.metadata/.plugins/org.eclipse.cdt.make.core/specs.cpp) <br /> Error launching external scanner info generator (gcc -E -P -v -dD F:/workspace/.metadata/.plugins/org.eclipse.cdt.make.core/specs.c) <br /> Error launching external scanner info generator (gcc -E -P -v -dD F:/workspace/.metadata/.plugins/org.eclipse.cdt.make.core/specs.c) My SECOND problem is that I have set up PATH but I cannot run 'g++ --version' and 'gcc --version' in the windows command, while 'make', 'gdb', 'gcc-3', and 'g++-3' work. Does anyone know what I can do to fix those problems? Is the second problem related to the first problem? Thanks Hank
What is sure is your second problem could very well be related to your first issue: From this thread: Make sure gcc is installed and on the system PATH. This other thread states the obvious: a PATH env var change via the OS GUI won't take effect in an already running app (Eclipse), including an already open console window. If you're re-launching Eclipse after the PATH change, you're not doing so from an existing console window, right? Also, try copying the gcc.exe executable to c:\WINNT just as a test. It won't work from there stand-alone, but you should at least see some difference that will help you determine if your problem is indeed a PATH one. For, cygwin environment, other hacks are possible: Recent versions of Cygwin no longer have gcc.exe or g++.exe. These files have been replaced with .lnk files that point to gcc-3.exe and g++-3.exe (or whatever) Some tools in Eclipse need to launch "gcc" or "g++" to generate some sort of info. The OS cannot find gcc.exe or g++.exe and so it returns an error. I have found that the following procedure works for me: 1/ delete gcc.exe.lnk and g++.exe.lnk from cygwin/bin 2/ Copy gcc-3.exe to gcc.exe 3/ Copy g++-3.exe to g++.exe Be aware though there: is an opened bug (221992) reporting of this message popping up at various intervals. is a fixed bug about (225272) Problems with spawner and fast (Dual Core) machines which can influence this issue (so what version of CDT are you using? I suspect you are not concerned by this one) one solution if the problem really persists would be to replace the spawner.dll with an earlier version (from CDT 4.0.3)
1,377,038
1,756,146
stringstream question
Here is some code that used to work with my code, but is having a problem now: #include <iostream> #include <fstream> #include <sstream> #include <cstring> using namespace std; int main() { stringstream out; out << 100; cout << out.str(); } I get just blank output. I just changed to snow leopard with Xcode 3.2.
Get this exact same issue under the same conditions Snow Leopard 64-Bit XCode 3.2 Base SDK 10.6 and the switch to Base SDK 10.5 resolves it. Apparently it's a SDK 10.6 issue. and the correct workaround is to remove the preprocessor macros: _GLIBCXX_DEBUG=1 _GLIBCXX_DEBUG_PEDANTIC=1 From the preprocessor settings (or else fall back to SDK 10.5 as above). Apple Discussion Link
1,377,084
1,377,101
Unbuffered output with cout
How can you get unbuffered output from cout, so that it instantly writes to the console without the need to flush (similar to cerr)? I thought it could be done through rdbuf()->pubsetbuf, but this doesn't seem to work. The following code snippet below is supposed to immediately output to the console, and then wait a few seconds. But instead, it just waits, and only outputs when the program exits and the buffer is flushed. #include <iostream> int main() { std::cout.rdbuf()->pubsetbuf(0, 0); std::cout << "A"; sleep(5); }
You can set the std::ios_base::unitbuf flag to flush output after each output operation either by calling std::ios_base::setf: std::cout.setf(std::ios::unitbuf); or using the std::unitbuf manipulator: std::cout << std::unitbuf;
1,377,161
1,377,168
Indenting in Codegear RAD Studio
Is there a way to indent/tab multiple lines in one action in the Codegear RAD Studio IDE? i.e. I would like to be able to highlight multiple lines and indent them all by one tab simultaneously.
Seth to indents selected code Select the text and press Ctrl + Shift + I to unindents selected code Select the text and press Ctrl + Shift + U Bye.
1,377,403
1,378,312
Alternative function in iostream.h for getch() of conio.h?
I'm trying to hold the screen on my output using the header file <iostream.h>, but I don't know any equivalent function to the getch() & clrscr() functions of <conio.h> in <iostream.h> or any other C++ library. Are there any such functions?
if you work on windows you can use system("pause"), this will give you "press any key to continue" message.
1,377,474
1,381,511
Why are my C++ exceptions not being caught?
I have some C++ code that uses a very standard exception pattern: try { // some code that throws a std::exception } catch (std::exception &e) { // handle the exception } The problem is that the exceptions are not being caught and I cannot figure out why. The code compiles to a static library in OS X (via Xcode). The library is linked into a Cocoa application, with a call to the function in question happening via an Objective-C++ thunk. I suspect that the interplay between Objective-C and C++ is the culprit but all my attempts to pin this down have failed. I have not been able to create a simple example that reproduces this behavior in a simple example. When I take the relevant code out of the context of my big program everything works. Can anyone suggest why my exceptions are not being caught?
Thanks for the input from everyone. Those are good suggestions for anyone who runs into a similar problem. It's working now, but I'm not 100% sure which of various changes I made caused things to become sane again. Once again, the approach of simplifying down to something that works and building back up from there paid off. One thing that wasn't mentioned in the responses, and which I think was part of my confusion, is to make sure that the handler makes it obvious that it actually caught the exception. I think that in some of my formulations of the handler it was masking that fact and passing the exception on to a higher level handler.