question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
3,127,171
3,127,179
How are circular #includes resolved?
In c lets say we have 2 files 1.h #include<2.h> blah blah and we have 2.h #include<1.h> code How is this resolved??
Typically you protect your include file with an ifndef/define that corresponds to the file name. This doesn't prevent the file from being included again, but it does prevent the contents (inside the ifndef) from being used and triggering the recursive includes again. #ifndef HEADER_1_h #define HEADER_1_h #include "2.h" /// rest of 1.h #endif #ifndef HEADER_2_h #define HEADER_2_h #include "1.h" // rest of 2.h #endif
3,127,174
3,127,810
Add a custom tool to toolchain to remove UTF-8 BOM before compile
My question is in the context of Code::Blocks and its tweaked version of MinGW, and Notepad++ . I want to be able to include Unicode literals in my source, and I can, so long as I use UTF-8 and not use a BOM. This works fine, up to a point, but it BOMs out (bad pun) whenever I reopen the file; it (not surprisingly) has this un-nerving side-effect of displaying the Unicode in its ANSI form. :( Those very useful and yet very annoying three bytes have to be there, and then they have to go! (at compile time). It sounds easy enough, just preprocess the source file(s), and discard the first three bytes (if they are a UTF-8 BOM)... I'm certainly not going to be the processor (by manual removal) each time I compile, so I've even resorted to using BOM-less #include files for these literals, but this is problematic from several perspectives, not the least of which is that it is a pain in the proverbial, and I can't "see" them! ..without a lot of juggling. Is there some way I can tap into the toolchain with a custom preprocessor? ...or if I have missed some obvious solution, I'd very much appreciate hearing about it.
I've fossicked around a bit more, and I've worked out a tentative solution. I'm not completely happy with it because it involves modifying the source, whereas I was actually looking for a piped solution, but it seems that g++.exe only accepts command line args (please correct me if I'm wrong). My "solution" is a bit rough-and-ready, but it works, and is certainly better (for me) than any other viable solution I've come across (which is none!) It requires due attention be paid to your editor's "File has been externally modified" message-box (if the file is being edited), but in fact, the BOM is still in the editor, so it is somewhat of a moot point. It is a simple command line hack. I'd prefer a more-integrated option, but here is this one (and it works): In Codeblocks, go to: Settings -> Compiler and Debugger -> Other settings -> [Advanced options] -> Command line macro: Make these mods to the command line. They should all be on a single line (of course), but for clarity I've seperated them out: cmd /c DropTheBOM.exe $file & $compiler $options $includes -c $file -o $object // (use your compiler cmdline) & MakeTheBOM.exe $file // Write your own utils, or try here: http://code.google.com/p/utf-bom-utils/ PS: #include files are not stripiped of their BOM (if they have one).. A simple BOM y/n arg switch for the routine which #includes these files would solve this issue quite simply... (but it is only a Windows problem... maybe thats why it hasn't been catered for... or has it? Does anyone know?
3,127,182
3,132,417
Qt: delegate to a single editor
What im trying to do is have a table which does not appear editable directly but can be edited in some widget outside the table. That is, the selected node can be edited here, and all nodes use the same editor because i want it to always be shown. What I've tried is to subclass QItemDelegate and just return the instance of QTextEdit i already have, like this: class Delegate extends QItemDelegate { @Override public QWidget createEditor(QWidget parent, QStyleOptionViewItem option, QModelIndex index) { return qtextEdit; } } which works, except that when you leave the editor it gets destroyed. Maybe delegate isn't supposed to be used this way. So how can i achieve this? (ps. im using jambi but c++ code is fine)
The QDataWidgetMapper class is exactly what you want, to edit the values of whatever record outside of the view in external controls. Taken straight from the documentation, this is how you'd use it: QDataWidgetMapper *mapper = new QDataWidgetMapper; mapper->setModel(model); mapper->addMapping(mySpinBox, 0); mapper->addMapping(myLineEdit, 1); mapper->addMapping(myCountryChooser, 2); mapper->toFirst(); And, if you have a view (QTreeView / QListView / QTableView / etc) and you want to edit the currently selected item, connect the appropriate signal & slot: connect(&view, SIGNAL(activated(QModelIndex)), mapper, SLOT(setCurrentModelIndex(QModelIndex)));
3,127,191
3,127,204
How to get MRU List data?
how can i get data prgogrammaticaly from windows registry MRU list? I am using vc++. For example windows xp search history is located in Software\Microsoft\Search Assistant\ACMru\5603. How can i get data from it? EDIT:I still dont know howto do this, can you be more specific? So what steps do i need to do to have acess to data?
As for the Run MRU have a look at: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU Document MRU is saved on filesystem as .lnk-files. Under Windows 7 it is: %APPDATA%\Microsoft\Windows\Recent Edit: On this XP Machine I've got only one entry under the key HKEY_CURRENT_USER\Software\Microsoft\Search Assistant\ACMru\5603 It is Name=000, Type=REG_SZ, Value="*.tmp" I suppose that means that on this machine Search has only been used once, more precisely it is the first (and only) entry in the MRU list, so next entry showing up would be: Name=001, Type=REG_SZ, Value=... and so on. If your question is now how to access the Windows registry, have a look here: Good Windows Registry Wrapper for C++ or for the plain api here: http://www.aspfree.com/c/a/Windows-Scripting/Working-with-the-Windows-Registry-in-C-plus-plus/
3,127,193
3,128,501
Error with bc++ and glut
This code compiles fine in Vc++ but in borland c++ gives me this error.. The code has no syntax errors and works fine.. Seems like there is a problem with the header.. But these are the standard headers and library files Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland main.c: Error E2337 c:\Borland\Bcc55\include\glut\glut.h 146: Only one of a set of verloadedfunctions can be "C"
The error is due to overloaded functions being treated like C-language functions. Because the language "C" has no overloading it can only have one function of a given name. Apparently GLUT has a function that has the same name as some other function in the program. This may be your own function (just check the glut.h line (146 or thereabouts) to see if you've duplicated a name. Your main.c is a "C" program so this will force C-language compilation (unless you've forced C++ compilation with a command line switch). You might try renaming your code to "main.cpp" and recompiling. Another possibility is the DEFINES are not set up to include GLUT properly and GLUT itself is trying to define overloaded functions with the same name. This is probably pretty unlikely as I think that GLUT is compile-able in "C". Here's a piece of code that will force the error so you can see why it happens. Just switch the commenting around on the second "somefunc" subroutine. Save this code as C++ (ie. myfile.cpp). // // Program myfile.cpp // #include <stdio.h> extern "C" float somefunc(int a) { return(a); }; // Un-comment one of the following two lines. extern "C" float somefunc(float a) { return(a); }; // This line should produce the error. // float somefunc(float a) { return(a); }; // This line should compile. void main(void){ printf("Hello World!\n"); } Good luck, /Alan
3,127,210
3,127,526
Qt - Get rid from .dll file missing errors
I have created a GUI which requires .dll files in order to work. Here the list of those: mingwm10.dll libgcc_s_dw2-1.dll QtCore4.dll QtGui4.dll I have read that I should write CONFIG += static in .pro file. But it does not work. Could you help?
You need a Qt installation that is built for static-linking for that CONFIG statement to work. The only way to gt a static Qt install is to download the source package and built it yourself. Now, to deploy your dynamically linked Qt app, just copy those DLL files to the same folder as your built exe file. This may be easier than building Qt statically.
3,127,228
3,127,786
Qt - Esc should not close the dialog
How to make Esc key to minimize a dialog? By default it closes. Should I process KeyEvent or there is a better way?
I think you may use this: void MyDialog::keyPressEvent(QKeyEvent *e) { if(e->key() != Qt::Key_Escape) QDialog::keyPressEvent(e); else {/* minimize */} } Also have a look at Events and Event Filters docs.
3,127,393
3,127,445
Returning char* / Visual Studio debugger weirdness
We're getting some funny behavior in the Visual Studio debugger with the following. I'm not sure if it's the code or some debugger weirdness (seen stuff like it before). We are trying to return a pointer to an value in an array. The weird behavior is that the value of x changes to equal y after func() is called a second time...at least, that's what it appears in the debugger. I suppose my question is, is this even legal/safe? The pointers should be on the heap in main()'s scope right, so it should be fine? char stuff[100]; char * func() { // i is random in the range stuff[i] = 'a'; return &stuff[i]; } main() { char * x = func(); char * y = func(); }
Are you debugging with a debug build? You often get surprising results like this if you debug a release build. A debug build will force the compiler to put all variables on the stack, and keep them around for their entire scope, so you get the expected debug view. A release build might reuse the space for one variable once it's never going to be used again, even if it is still in scope, and might keep short-lived variables in processor registers rather than on the stack. In a release build, it's likely that x and y are placed at the same memory location (or register), since their usage lifetimes don't overlap. There's no need to keep x around after first line, so the compiler is allowed to discard it. If you were to use x later on in the function, then it would need its own space on the stack, so you would probably see it in the debugger as expected. And to answer your question: yes this is valid and correct, as long as i is indeed in range.
3,127,454
3,127,482
How do C++ class members get initialized if I don't do it explicitly?
Suppose I have a class with private memebers ptr, name, pname, rname, crname and age. What happens if I don't initialize them myself? Here is an example: class Example { private: int *ptr; string name; string *pname; string &rname; const string &crname; int age; public: Example() {} }; And then I do: int main() { Example ex; } How are the members initialized in ex? What happens with pointers? Do string and int get 0-intialized with default constructors string() and int()? What about the reference member? Also what about const references? I'd like to learn it so I can write better (bug free) programs. Any feedback would help!
In lieu of explicit initialization, initialization of members in classes works identically to initialization of local variables in functions. For objects, their default constructor is called. For example, for std::string, the default constructor sets it to an empty string. If the object's class does not have a default constructor, it will be a compile error if you do not explicitly initialize it. For primitive types (pointers, ints, etc), they are not initialized -- they contain whatever arbitrary junk happened to be at that memory location previously. For references (e.g. std::string&), it is illegal not to initialize them, and your compiler will complain and refuse to compile such code. References must always be initialized. So, in your specific case, if they are not explicitly initialized: int *ptr; // Contains junk string name; // Empty string string *pname; // Contains junk string &rname; // Compile error const string &crname; // Compile error int age; // Contains junk
3,127,721
3,129,145
Except OOP, why is C++ better than C?
Well that may sound like a troll question, but since C++ seems hard to fully master (and I never really knew STL was actually "part" of it), I wanted to know what are the disadvantages to use C instead of C++ when not relying much on OOP. C++ can have a very much sophisticated syntax sometimes, which is kinda confusing me while trying to use OGRE3D for example...
Why C++ is better than C? Besides the obvious list of features, in my opinion the real answer is that there's no good reason to still use C instead of C++. Even if you don't use OOP, you can use it as a better C. Even if you use just once a unique feature of C++ in your program, C++ is already a winner. On the other hand, there's no disadvantage in using C++: it retains the performance goals of C and it is a quite low level language, while allowing very powerful things. And you will not miss any C feature using C++! And don't forget the wide user base and the rich libraries and frameworks available. By the way, C99 has added some interesting features but after a decade there's still very limited compiler support (so you are bound to ANSI C). In the meantime C++ evolved as well and the compiler vendors are committed to providing conforming implementations.
3,127,727
3,131,600
How to programmatically get windows search history?
How to get the windows search history and use it in my program? For example I write ".doc" in windows search bar. Now I want in my program to find out from somewhere, that I searched for ".doc" in my system (not web).
I don't know if there's an API for it, but if you do a Windows search for an unlikely string, say "zxcvbnm", then search the registry for it, then on XP you can see it under one of the folders in: HKEY_CURRENT_USER\Software\Microsoft\Search\ACMru along with the rest of your recent search strings. I imagine this registry location may change between Windows versions though. If you're targetting Windows 7 then this MSDN article looks like a good starting point.
3,127,966
3,128,008
Multi-window program
I read many articles on the topic, a few of them were here, on stackoverflow, but none of them asked my question. I'll try to be specific. I need to create an application (native WinAPI) with a main window (of window class "a"). When the user clicks a button there, a window of "b" class pops up. It might be modal or not, I don't care right now. I tried making an application with two window classes and two window procedures. But the problem is that when I close the second window, the whole application shuts down. Thank you.
At a guess, the window procedure for your second window is based on one for a main window, so when it receives a WM_DESTROY, it's calling PostQuitMessage. This is normal for the top-level window, because the user expects destroying it to mean exiting the application. For a child window (modal or otherwise) that's not the case though, so the child should not (again, normally) call PostQuitMessage in its WM_DESTROY handler.
3,128,087
3,128,101
Move constructor/operator=
I'm trying to learn about new feature of C++ namely move constructor and assignment X::operator=(X&&) and I found interesting example but the only thing I quite not even understand but more dissagree is one line in move ctor and assignment operator (marked in the code below): MemoryBlock(MemoryBlock&& other) : _data(NULL) , _length(0) { std::cout << "In MemoryBlock(MemoryBlock&&). length = " << other._length << ". Moving resource." << std::endl; // Copy the data pointer and its length from the // source object. _data = other._data; _length = other._length; // Release the data pointer from the source object so that // the destructor does not free the memory multiple times. other._data = NULL; other._length = 0;//WHY WOULD I EVEN BOTHER TO SET IT TO ZERO? IT DOESN'T MATTER IF IT'S ZERO OR ANYTHING ELSE IT IS JUST A VALUE. } So my question is: do I have to set the value of lenght_ to zero or can I leave it untouched? There won't be any memory-leak and one expression less afaics.
Because the "moved from" object is still going to be destructed eventually, so you have to leave it in a consistent state. Exactly how you do this depends on your object, of course, and in this case it apparently means nulling out the data pointer and setting the length to zero.
3,128,099
3,128,107
c++ template seems to break access specifiers
The following code doesn't compile for obvious reasons, namely that Foo is trying to access a private member of Bar. However if you uncomment/comment the lines marked, making Foo a template, it does compile and outputs 42. What am I missing here? Why does this work? Seems to me it shouldn't. Thanks for your help. #include <iostream> class Bar { private: static const int x = 42; }; //template <int> // uncomment me struct Foo { static const int i = Bar::x; }; int main(int argc, char* argv[]) { std::cout << Foo::i << std::endl; // comment me //std::cout << Foo<0>::i << std::endl; // uncomment me }
If you are seeing this behavior, it is a compiler bug. Both Comeau Online and Visual C++ 2010 reject the code as invalid because Bar::x is inaccessible. g++ 4.1.2 incorrectly accepts the invalid code (someone would need to test with a later version to see if it's been fixed; that's the only version I have on this laptop).
3,128,248
3,128,257
Namespace Aliasing in C++
It is widely known that adding declarations/definitions to namespace std results in undefined behavior. The only exception to this rule is for template specializations. What about the following "hack"? #include <iostream> namespace std_ { void Foo() { std::clog << "Hello World!" << std::endl; } using namespace std; } int main() { namespace std = std_; std::Foo(); } Is this really well-defined as far as the standard is concerned? In this case, I'm really not adding anything to namespace std, of course. Every compiler I've tested this on seems to happily swallow this. Before someone makes a comment resembling "why would you ever do that?" -- this is just to satisfy my curiosity...
Redefining std as an alias is okay, as long as you are not in the global declarative region: In a declarative region, a namespace-alias-definition can be used to redefine a namespace-alias declared in that declarative region to refer only to the namespace to which it already refers. Since you define the alias in main(), it shadows the global std name. That's why this works, should work, and is perfectly fine according to the standard. You're not adding anything to the std namespace, and this "hack" only serves to confuse the human reader of the code.
3,128,269
3,128,712
Find array element by member value - what are "for" loop/std::map/Compare/for_each alternatives?
Example routine: const Armature* SceneFile::findArmature(const Str& name){ for (int i = 0; i < (int)armatures.size(); i++) if (name == armatures[i].name) return &armatures[i]; return 0; } Routine's purpose is (obviously) to find a value within an array of elements, based on element's member variable, where comparing member variable with external "key" is search criteria. One way to do it is to iterate through array in loop. Another is to use some kind of "map" class (std::map, some kind of vector sorted values + binarySearch, etc, etc). It is also possible to make a class for std::find or for std::for_each and use it to "wrap" the iteration loop. What are other ways to do that? I'm looking for alternative ways/techniques to extract the required element. Ideally - I'm looking for a language construct, or a template "combo", or a programming pattern I don't know of that would collapse entire loop or entire function into one statement. Preferably using standard C++/STL features (no C++0x, until it becomes a new standard) AND without having to write additional helper classes (i.e. if helper classes exist, they should be generated from existing templates). I.e. something like std::find where comparison is based on class member variable, and a variable is extracted using standard template function, or if variable (the one compared against "key"("name")) in example can be selected as parameter. The purpose of the question is to discover/find language feature/programming technique I don't know yet. I suspect that there may be an applicable construct/tempalte/function/technique similar to for_each, and knowing this technique may be useful. Which is the main reason for asking. Ideas?
If you have access to Boost or another tr1 implementation, you can use bind to do this: const Armature * SceneFile::findArmature(const char * name) { find_if(armatures.begin(), armatures.end(), bind(_stricmp, name, bind(&string::c_str, bind(&Armature::name, _1))) == 0); } Caveat: I suspect many would admit that this is shorter, but claim it fails on the more elegant/simpler criteria.
3,128,286
3,128,753
install driver using c++
I'm trying to install driver behind the user: I've create DLL which call SetupCopyOEMInf using c++ then i call it from VB application: C++ code: PBOOL bRebootRequired = false; PCTSTR szInfFileName = (PCTSTR) "c:\\temp\\ttt\\Driver\\slabvcp.inf"; if(!SetupCopyOEMInf(szInfFileName,NULL, SPOST_PATH, SP_COPY_REPLACEONLY, NULL, 0, NULL, NULL)){; DWORD dw = GetLastError(); LPVOID lpMsgBuf; LPVOID lpDisplayBuf; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf,0, NULL ); MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK); } And when i call this function i receiving error "The system cannot find the file specified." But the path to my file is correct.
PCTSTR szInfFileName = (PCTSTR) "c:\\temp\\ttt\\Driver\\slabvcp.inf"; A cast is not going to work, it will turn your 8-bit character string into Chinese. Fix: PCTSTR szInfFileName = _T("c:\\temp\\ttt\\Driver\\slabvcp.inf");
3,128,295
3,128,591
Questions about "this pointer adjustor" in C++ object layout
I am kind of confused by one question: Under what cirumstances does the MS VC++ compiler generate a this adjustor? Notice that the this adjustor is not necessarily in a thunk. Below is my test code. class myIUnknown { public: virtual void IUnknown_method1(void)=0; virtual void IUnknown_method2(void)=0; int data_unknown_1; int data_unknown_2; }; class BaseX:public myIUnknown { public: BaseX(int); virtual void base_x_method1(void)=0; virtual void base_x_method2(void)=0; int data_base_x; int data_unknown_1; int data_unknown_2; }; class BaseY:public myIUnknown { public: BaseY(int); virtual void base_y_method1(void); virtual void base_y_method2(void)=0; int data_base_y; int data_unknown_1; int data_unknown_2; }; class ClassA:public BaseX, public BaseY { public: ClassA(void); //myIUnknown void IUnknown_method1(void); void IUnknown_method2(void); //baseX void base_x_method1(void) ; void base_x_method2(void) ; //baseY //void base_y_method1(void) ; void base_y_method2(void) ; virtual void class_a_method(void); int data_class_a; int data_unknown_1; int data_unknown_2; }; The object layout is as below: 1> class ClassA size(60): 1> +--- 1> | +--- (base class BaseX) 1> | | +--- (base class myIUnknown) 1> 0 | | | {vfptr} 1> 4 | | | data_unknown_1 1> 8 | | | data_unknown_2 1> | | +--- 1> 12 | | data_base_x 1> 16 | | data_unknown_1 1> 20 | | data_unknown_2 1> | +--- 1> | +--- (base class BaseY) 1> | | +--- (base class myIUnknown) 1> 24 | | | {vfptr} 1> 28 | | | data_unknown_1 1> 32 | | | data_unknown_2 1> | | +--- 1> 36 | | data_base_y 1> 40 | | data_unknown_1 1> 44 | | data_unknown_2 1> | +--- 1> 48 | data_class_a 1> 52 | data_unknown_1 1> 56 | data_unknown_2 1> +--- 1> 1> ClassA::$vftable@BaseX@: 1> | &ClassA_meta 1> | 0 1> 0 | &ClassA::IUnknown_method1 1> 1 | &ClassA::IUnknown_method2 1> 2 | &ClassA::base_x_method1 1> 3 | &ClassA::base_x_method2 1> 4 | &ClassA::class_a_method 1> 1> ClassA::$vftable@BaseY@: 1> | -24 1> 0 | &thunk: this-=24; goto ClassA::IUnknown_method1 <=====in-thunk "this adjustor" 1> 1 | &thunk: this-=24; goto ClassA::IUnknown_method2 <=====in-thunk "this adjustor" 1> 2 | &BaseY::base_y_method1 1> 3 | &ClassA::base_y_method2 1> 1> ClassA::IUnknown_method1 this adjustor: 0 1> ClassA::IUnknown_method2 this adjustor: 0 1> ClassA::base_x_method1 this adjustor: 0 1> ClassA::base_x_method2 this adjustor: 0 1> ClassA::base_y_method2 this adjustor: 24 <============non-in-thunk "this adjustor" 1> ClassA::class_a_method this adjustor: 0 And I found that in the following invokation, this pointer adjustors is generated: in-thunk this adjustor: pY->IUnknown_method1();//adjustor this! this-=24 pY-24==>pA pY->IUnknown_method2();//adjustor this! this-=24 pY-24==>pA non-in-thunk this adjustor: pA->base_y_method2();//adjustor this! this+=24 pA+24==>pY Could anyone tell me why the compiler produce this adjustor in the above invocations? Under what cirumstances will the compiler generate the this adjustor? Many thanks.
Perhaps it's easiest to start by thinking how single inheritance is (typically) implemented in C++. Consider a hierarchy that includes at least one virtual function: struct Base { int x; virtual void f() {} virtual ~Base() {} }; struct Derived : Base { int y; virtual void f() {} virtual ~Derived() {} }; In a typical case, this will be implemented by having a vtable for each class, and create each object with a (hidden) vtable pointer. The vtable pointer for each object (of either Base or Derived class) will have the vtable pointer at the same offset in the structure, and each will contain the pointers to the virtual function (f and the dtor) at the same offsets in the virtual table. Now, consider polymorphic use of these types, such as: void g(Base&b) { b.f(); } Since both Base and Derived (and any other derivatives of Base) all have the vtable arranged the same way, and a pointer to the vtable at the same offset in the structure, the compiler can generate exactly the same code for this, regardless of whether it's dealing with a Base, a Derived, or something else derived from Base. When you add multiple inheritance to the mix, however, this changes. In particular, you can't arrange all your objects so the pointer to the vtable is always at the same offset in every object, for the simple reason that an object that's derived from two base classes will (potentially) have pointers to two separate vtables, which clearly can't be at the same offset in the structure (i.e., you can't put two different things in exactly the same place). To accommodate this, you have to do some sort of explicit adjustment. Each multiply derived class has to have some way for the compiler to find the vtables for all the base classes. Consider something like this: struct Base1 { virtual void f() { } }; struct Base2 { virtual void g() {} }; class Derived1 : Base1, Base2 { virtual void f() {} virtual void g() {} }; class Derived2 : Base2, Base1 { virtual void f() {} virtual void g() {} }; In a typical case, the compiler will arrange the vtable pointers in the same order you specify the base classes, so Derived1 will have a pointer to Base1's vtable followed by a pointer to Base2's vtable. Derived2 will reverse the order. Now, assuming the same function that does a polymorphic call to f(), but is going to be passed a reference to a Base1, or a Derived1, or a Derived2. One of those will almost inevitably have its pointer to Base1's vtable at a different offset than the others. This is where the "this-adjustor" (or whatever you prefer to call it) comes in -- it finds the correct offset for the base class you're trying to use, so when you access members of that class, you get the right data. Note that while I've used the pointer to the vtable as the primary example here, it's not the only possibility. In fact, even if you have no virtual functions in any of the classes, you still need access to the data for each base class, which requires the same kind of adjustment.
3,128,339
3,128,355
Modelling Typeclasses in C++
Is it possible to implement Haskell typeclasses in C++? If yes, then how?
There's a few papers on this, which might be useful as background reading: C++ templates/traits versus Haskell type classes, Sunil Kothari , Martin Sulzmann A Comparative Study of Language Support for Generic Programming, Ronald Garcia , Jaakko Järvi , Andrew Lumsdaine , Jeremy Siek , Jeremiah Willcock
3,128,346
3,128,404
When all does comma operator not act as a comma operator?
If you see this code, class A{ public: A(int a):var(a){} int var; }; int f(A obj) { return obj.var; } int main() { //std::cout<<f(23); // output: 23 std::cout<<f(23, 23); // error: too many arguments to function 'int f(A)' return 0; } f(23, 23) does not compile because the comma acts as a separator here and not as a comma operator. Where all does a comma not work as a comma operator? Or the other way around?
From a grammatical point of view, the parameters of a function call form an optional expression-list inside parentheses. An expression-list consists of one or more assignment-expression separated by a comma token. A comma can only signify a comma operator where an expression is expected. The comma operator makes an expression out of an expression, a , and an assignment-expression, but an expression involving a comma operator is not itself an assignment-expression so can't appear in an expression-list except where it's a constituent of something that is an assignment-expression. For example, you can surround any expression (including one using the comma operator) inside parentheses to from a primary-expression which is an assignment-expression and hence valid in an expression-list. E.g. postfix-expression where the expression-list consists of two assignment-expression each of which is an identifier. f( a, b ); postfix-expression where the expression-list consists of a single assignment-expression which is a primary-expression which is a parenthesized expression using the comma operator. f( (a, b) );
3,128,365
3,146,094
SFML Input GetMouseX and GetMouseY not catching on to mouse movement
I'm programming a GUI in my app and I noticed that button presses weren't being registered very quickly. I did some lazy debugging (send coordinates of mouse to output) and I noticed that Input's GetMouseX and GetMouseY weren't responding nearly fast enough to when the mouse moved somewhere. This small tidbit should be able to reproduce it (in a HandleEvents function that is called in a typical game loop, obviously replace App::whatever with whatever you have in your workspace). int x = App::GetApp()->GetInput().GetMouseX(); int y = App::GetApp()->GetInput().GetMouseY(); std::cout << x << " " << y << "\n"; Just move your mouse around on the screen and watch the output. I'm not sure if this is correct behavior and I'm using it for the wrong purpose, or what, but I need some way to retrieve the mouse's exact location at any given time. Any help is appreciated, thanks. P.S. If I move the mouse slowly the problem doesn't occur. Edit: I was wrong. The problem only occurs in context with the rest of the stuff going on. When I blocked out most of the game loop and only included retrieving cursor position, it worked fine. Still not sure what is wrong though.
The problem was that I was only polling one event per frame rather than polling all of the events.
3,128,469
3,128,475
Build a simple web server that I can run as a windows service
I'm a web developer so all my experience is with ruby, python, or PHP. However, I'm gonna do a little windows programming. I want to build a light weight web server that can handle incoming requests and pass them on to a COM port. I want to be able to distribute it as an exe that will install the server as a windows service. What do you think would be the best language to do this in? What IDE would be best for said language? Thanks, Seth
To be honest you will probably have the most fun doing this in C#. The learning curve will be smaller and the language and most of its features are your friend. The fact that you can set up a windows service in 2 minutes is also a plus.
3,128,534
3,129,003
Observer design pattern and others
I'm starting to read about design patterns and trying to apply them to some coding. I've read about the observer pattern and think it would be a most useful one to make use of. My two questions are these: 1) If I want my object to be both an observer and a subject, is it simply a question of making it inherit from both the observer and the subject class? Say I have several units in an army, and I want them to quickly send local updates to each other. Does it work as I have described, or does it necessitate another pattern completely? 2) If an object needs to communicate with types of many a different nature (say a general needs to communicate with his units, with the faction leader, etc.), does the observer pattern still work? I guess it would just be a question of implementation, but I don't know...
Normally, the observer patterns is about applying a layered approach: a higher level object controls a lower level one and it is an observer, so it can react on changed status of the lower level object. In your case, you want communication between peers and you want all objects to know each other, so observer doesn't add real value. Observer would work better if there would be a controlling object on top of the units that knows what to do on updates. Of course, it is up to you to decide wheter this would work better in your case. BTW, check boost signals as an implementation for your observer
3,128,635
3,130,121
explosion sound thread in MFC game project is stopping the music that is playing
Mabye someone over here can explain to me what am I doing wrong. This is after reading a lot of articles over the net and doing what the articles say should work but it is not working for me. I am developing a nice little game with a background music and an explosion sound. For the explosion I know I need to use threads or my music stops when the first explosion happens. I am using threads but the music still stops. I need the background music to keep on playing all the time and it should continue playing during and after the explosion sound. I tried playing the explosion sync, It doesn't make any difference, the background sound stops playing the second the thread method is triggered. Here is my code. It is very simple, but the explosion sound is not working. This is the GLOBAL decleration in the *.h file: UINT CMonstersThread(LPVOID Param); This is the thread function in the *.cpp file: UINT CMonstersThread(LPVOID Param) { PlaySoundA("sounds\\expl06.wav", NULL, SND_ASYNC); AfxEndThread(0); return FALSE; } This is the call for the thread every time a "friendly" is hit, (in the same *.cpp file): AfxBeginThread(CMonstersThread,NULL,THREAD_PRIORITY_NORMAL,0,0,NULL); That is all my code. And from what I got over the web, it should work but isn't playing the music continuously while making explosion sounds as I expect it should.
I would suggest using XAudio2 from the latest DirectX sdk to play your audio. I will take a little more work & code, but the end result will be better because you will be able to load the sound file separately from playing it. With 'PlaySound' you will notice a lag in the audio if you try to use it right after an event, like a mouse click or a monster dying / explosion and you won't hit this with XAudio2. I know this from experience. Since you are already using Visual Studio, I also suggest you try using VS 2010 if possible because the [Concurrency Runtime, Parallel Pattern Library and Agents Library]]1 make threading and tasking take a little less code. There are samples as well at http://code.msdn.com/concrtextras and you may find something useful here as well. -Rick
3,129,015
3,129,301
C++ State machine affecting "HAS-A Parent"
I'm trying to implement a State Machine. The State Machine will have to have an impact on the object that "HAS" it as a member. However, I obviously can't include the "StateMachine" in the "Game" class AND include the "Game" header in the "StateMachine" class. How do I get around this problem?
As your client class is a member rather than an inheriting daughter, you can not access any private state of the parent (which I'm sure you knew), so you have a limited number of choices: Expose some state in the parent publicly and diddle that (but this is poor design and should be avoided) Give the parent a public notification interface of some kind and use that (better then the above, but still not great) Pass a call-back to the client (a very c programmer type of solution) Use some kind of signal/slots mechanism to notify the parent that something interesting has happened. If you're using any of the big frameworks (Qt, etc...), this may already be available
3,129,078
3,129,090
Discriminating between typedefs to same type in c++
I want functionality similar to the below: typedef int A; typedef int B; struct foo { foo(A a) { /*specific to type A*/ } foo(B b) { /*specific to type B*/ } }; I use the typedefs in my program to denote logically different usage of the same type. So, I would like to create object of type foo differently for different typedefs. I could compile this in g++, but msvc throws a fit saying that foo(A) is already defined when it sees the second definition foo(B). I thought of using a type list and the position of a type in the list to discriminate between the typedefs and tried using a boost::mpl::vector: #include <boost/mpl/vector.hpp > #include <boost/mpl/find.hpp> typedef int A; typedef int B; struct foo { typedef boost::mpl::vector<A, B> supported_types; foo(boost::mpl::find<supported_types, A>::type, A a) {} foo(boost::mpl::find<supported_types, B>::type, B b) {} }; but unfortunately, find too discards my typedef and just returns iterator for A in both cases. I also thought about defining an enum and using it for each type enum { TYPE_A, TYPE_B }; template <int i> struct int2type {}; and using this int2type and type B in the program. But this looks inelegant to me as it is prone to errors. I would like use a typelist and do this, so that it is clear what types would be supported. Please let me know if there is a generic and extensible way of doing this.
A boost strong typedef should do what you're looking for. #include <boost/strong_typedef.hpp> BOOST_STRONG_TYPEDEF(int, A); BOOST_STRONG_TYPEDEF(int, B);
3,129,096
3,129,141
What Design Pattern to use?
The problem to model is this: A hierarchy of levels within an Army, starting with the national army in whole, through field armies, subunits, and eventually the individual men. Each level may involve links to one or more other classes such as General or Officer or whatever. The units within say a field army need to be able to communicate with each other, especially for purposes of modeling morale, cohesion, etc, as well as with those of any enemy field army (e.g. a unit routing in my army affects the enemy morale positively). Furthermore, each unit needs to communicate with those above and below it in the hierarchy (for obvious purposes). I was thinking of having the links in the physical hierarchy represented by actual pointers (possibly bilateral) in each of these entities' classes (e.g. army* in each unit and unit* or a whole collection of them in each army) and then making use of the observer design pattern to implement any communication in other cases (such as the case I mentioned above). However, being no expert in design patterns or programming for that matter I do not know whether there is any other more efficient manner to do this. Any help would be greatly appreciated.
There is a model/design pattern for communicating events between disparate entities that may not know of eachothers existence before the communication happens. The pattern is called 'Publish/Subscribe'. Each entity sends events it wants to publish to a broker and tells the broker about what kinds of events it would be interested in. The broker handles making sure the subscribing entities learn of events they find interesting that are published. This is like the Observer pattern, but in the Observer pattern each interested entity subscribes individually to each entity it wants events from. I think this could result in a lot of overhead because that requires everybody to care about creation and destruction of things. Anyway, there is a nice Wikipedia article on Publish/Subscribe. I would use the Composite pattern (which basically means a tree of some form) for the individual armies. And possibly Observer for relationships up and down the hierarchy or with siblings. But Observer requires too much registering and unregistering for it to be workable in the general case.
3,129,196
3,129,251
data from a std::vector reference becomes corrupt after return from function call
I have a std::vector< tr1::shared_ptr<mapObject> > that I'm trying build from data contained in a compressed file. Here's the function I'm attempting to do that with: using std::tr1::shared_ptr; template<typename T> void loadSharedPtrVector(std::vector< shared_ptr<T> >& vect, TCODZip& zip) // the TCODZip is the compression buffer I'm loading the data from. It's // working correctly and isn't really part of this problem. { vect.clear(); // load the size of the saved vector int numT = zip.getInt(); // load the saved vector for(int i=0; i<numT; ++i) { int type = zip.getInt(); shared_ptr<T> Tptr(new T); T newT = T::loadType(type, zip); Tptr.reset(&newT); std::cerr << "load: " << Tptr->getPosition() << std::endl; // outputs correct values vect.push_back(Tptr); } for(int i=0; i<numT; ++i) { // outputs the last value pushed onto vect std::cerr << "loadDone: " << vect[i]->getPosition() << std::endl; } } The above function is called by this bit of code here: typedef std::tr1::shared_ptr<mapObject> featurePtr; // 'features' is a std::vector<featurePtr>, 'zip' is a TCODZip previously declared utility::loadSharedPtrVector<mapObject>(features, zip); vector<featurePtr>::const_iterator fit; for(fit=features.begin(); fit<features.end(); ++fit) { // outputs mostly garbage cerr << "afterCall: " << (*fit)->getPosition() << endl; } When this is run, the cerr statements give this output (each set of output has ~50 lines, so I cut out most for brevity): load: (5,40) load: (5,45) load: (5,58) (etc. all 'load' lines are correct output) load: (87,68) load: (11,5) loadDone: (11,5) loadDone: (11,5) loadDone: (11,5) loadDone: (11,5) loadDone: (11,5) loadDone: (11,5) (etc. all 'loadDone' lines are the same) afterCall: (11,5) afterCall: (10,1) afterCall: (10,1) afterCall: (10,1) afterCall: (10,1) afterCall: (10,1) afterCall: (10,1) (etc. all 'afterCall' lines are the same except for the first) I apparently have some misconceptions about how shared_ptrs work. I realized that I'm pushing copies of Tptr into vect, and that's why all of its indices are the same, although I thought that declaring a new shared_ptr in the loop would make a separate pointer from the other ones already in vect, but I guess not. I have no idea why the 'afterCall' set of output is different from the 'loadDone' set (except for that first value). In addition to (10,1) it has also output (2274756,134747232) and (134747232, 16), although it outputs (10,1) more than any other. I suspect that my problem boils down to my misuse of shared_ptr. Can anyone tell me exactly how I'm misusing it? The tutorials I find online haven't been very helpful in this regard.
The problem is here: T newT = T::loadType(type, zip); Tptr.reset(&newT); You give shared_ptr pointer to stack memory, which is reclaimed at function return and is no longer valid. Allocate that from the heap: shared_ptr<T> Tptr( new T( T::loadType( type, zip )));
3,129,211
3,129,219
Embedding v8 with Visual C++ 2010
I'm trying to embed the v8 engine to my C++ application. I use Visual C++ 2010. I've built it successfully using this command: scons env="INCLUDE:C:\Program Files\Microsoft SDKs\Windows\v7.0A\Include;C:\Program Files\Microsoft Visual Studio 10.0\VC\include,LIB:C:\Program Files\Microsoft SDKs\Windows\v7.0A\Lib;C:\Program Files\Microsoft Visual Studio 9.0\VC\lib" And then, I: added the v8/include directory to Configuration Properties -> C/C++ -> General --> Additional Include Directories added the v8/v8.lib file to Configuration Properties -> Linker -> Input -> Additional Dependencies. When I try to compile the basic "Hello World" example from the Getting Started page, it shows me the following linking error: 1>v8.lib(platform-win32.obj) : error LNK2001: unresolved external symbol __imp__accept@12 1>v8.lib(platform-win32.obj) : error LNK2001: unresolved external symbol __imp__listen@8 1>v8.lib(platform-win32.obj) : error LNK2001: unresolved external symbol __imp__send@16 1>v8.lib(platform-win32.obj) : error LNK2001: unresolved external symbol __imp__closesocket@4 1>v8.lib(platform-win32.obj) : error LNK2001: unresolved external symbol __imp__freeaddrinfo@4 1>v8.lib(platform-win32.obj) : error LNK2001: unresolved external symbol __imp__timeGetTime@0 1>v8.lib(platform-win32.obj) : error LNK2001: unresolved external symbol __imp__socket@12 1>v8.lib(platform-win32.obj) : error LNK2001: unresolved external symbol __imp__bind@12 1>v8.lib(platform-win32.obj) : error LNK2001: unresolved external symbol __imp__recv@16 1>v8.lib(platform-win32.obj) : error LNK2001: unresolved external symbol __imp__setsockopt@20 1>v8.lib(platform-win32.obj) : error LNK2001: unresolved external symbol __imp__shutdown@8 1>v8.lib(platform-win32.obj) : error LNK2001: unresolved external symbol __imp__ntohs@4 1>v8.lib(platform-win32.obj) : error LNK2001: unresolved external symbol __imp__htons@4 1>v8.lib(platform-win32.obj) : error LNK2001: unresolved external symbol __imp__WSAGetLastError@0 1>v8.lib(platform-win32.obj) : error LNK2001: unresolved external symbol __imp__getaddrinfo@16 1>v8.lib(platform-win32.obj) : error LNK2001: unresolved external symbol __imp__htonl@4 1>v8.lib(platform-win32.obj) : error LNK2001: unresolved external symbol __imp__ntohl@4 1>v8.lib(platform-win32.obj) : error LNK2001: unresolved external symbol __imp__WSAStartup@8 1>v8.lib(platform-win32.obj) : error LNK2001: unresolved external symbol __imp__connect@12 Any ideas how to fix this? Thanks.
You need to link to WinSock (Ws2_32.lib).
3,129,270
3,430,213
C++ Prime number task from the book
I'm a C++ beginner ;) How good is the code below as a way of finding all prime numbers between 2-1000: int i, j; for (i=2; i<1000; i++) { for (j=2; j<=(i/j); j++) { if (! (i%j)) break; if (j > (i/j)) cout << i << " is prime\n"; } }
The one simple answer to the whole bunch of text we posted up here is : Trial division! If someone mentioned mathematical basis that this task was based on, we'd save plenty of time ;)
3,129,359
3,129,365
Does destructor of a C++ class that throws an exception gets called?
Suppose I have a class like this: #include <iostream> using namespace std; class Boda { private: char *ptr; public: Boda() { ptr = new char [20]; } ~Boda() { cout << "calling ~Boda\n"; delete [] ptr; } void ouch() { throw 99; } }; void bad() { Boda b; b.ouch(); } int main() { bad(); } It seems that destructor ~Boda never gets called, thus the ptr resource never get freed. Here is the output of the program: terminate called after throwing an instance of 'int' Aborted So it seems the answer to my question is No. But I thought that the stack got unwound when an exception got thrown? Why didn't Boda b object get destructed in my example? Please help me understand this resource problem. I want to write better programs in the future. Also, is this the so called RAII? Thanks, Boda Cydo.
If the exception is not caught anywhere, then the C++ runtime is free to go straight to terminating the program without doing any stack unwinding or calling any destructors. However, if you add a try-catch block around the call to bad(), you will see the destructor for the the Boda object being called: int main() { try { bad(); } catch(...) { // Catch any exception, forcing stack unwinding always return -1; } } RAII means that dynamically (heap) allocated memory is always owned by an automatically (stack) allocated object that deallocates it when the object destructs. This relies on the guarantee that the destructor will be called when the automatically-allocated object goes out of scope, whether due to a normal return or due to an exception. This corner-case behavior is normally not a problem with respect to RAII, since usually the main reason that you want the destructors to run is to free memory, and all memory is given back to the OS when your program terminates anyway. However if your destructors do something more complicated, like maybe remove a lock file on disk or something, where it would make a difference whether the program called destructors or not when crashing, you may want to wrap your main in a try-catch block that catches everything (only to exit on exception anyway) just to ensure that the stack always unwinds before terminating.
3,129,373
3,129,556
Understanding Google V8's Architecture
I'm not sure I understand V8's architecture (yes, I've read its documentation). In C# with the v8sharp wrapper I write something like this, for example: namespace App { class Point { public Point() { } public Point(double x, double y) { this.X = x; this.Y = y; } public double X { get; set; } public double Y { get; set; } } } static class Program { static void Main() { //registering with v8sharp V8Engine engine = V8Engine.Create(); engine.Register<App.Point>(); //execute javascript object rtn = engine.Execute("new App.Point(10, 10);"); } } How would I write the same thing in Standard C++ without this wrapper? Thanks.
If you look here: http://code.google.com/apis/v8/embed.html they have a sample that is identical to yours under "Accessing Dynamic Variables"
3,129,375
3,129,432
Subclass another application's control?
Is it possible to subclass another application's control so that my application could do something before the other application executes it's code and receiving the lParam and wParam? Ex: subclassing notepad's Edit control and when the user types, being able to know what the user typed? would SetWindowSubclass work if I provide the hWnd of Notepad's edit control? And would I receive the lParam and wParam of all its messages? Thanks
Yes, that is easily possible, if your code is running in the application's process. You can do that with a DLL. You would simply use GetWindowLongPtr with GWLP_WNDPROC to get the application's window function, and use SetWindowLongPtr to set your own. In your window function you check for the message that you would like to alter, and call the application's window function with the altered values. In case of any other message, you will have to call it straight. Use CallWindowProc to call the window funcion, because the default windows function is not a pointer. Another way would be to use the CallWndProc hook function. Call SetWindowsHookEx with WH_CALLWNDPROC to have it installed. Haven't tried this one yet though, but you won't need to have to be in the process's space, IIRC.
3,129,409
3,129,470
Multi-Index Insert Failure Return (Boost)
I'm currently using Boost's multi-index to help keep track of how many times a packet passes through a system. Each time a system touches the packet, its IP address is added to a string, separated by commas. I go through that string then, tokenize it and add each IP found to a multi-index. Since the IPs are set to be unique right now, it's impossible for the same IP to be added twice to the multi-index. What should happen then is the value associated with the IP address should be incremented, counting how many times the packet went through that same IP. Anyways, my issue comes in here. When I use something like stl map, I will get back a response which lets me know a key could not be added due to a duplicate key already existing within the map. Does Boost's multi-index offer anything similar? I know that if I attempt to insert the same IP it will fail, but how can I tell it failed? Here's a portion of my current code: // Multi-index handling using boost::multi_index_container; using namespace boost::multi_index; struct pathlog { string hop; int passedthru; pathlog(std::string hop_,int passedthru_):hop(hop_),passedthru(passedthru_){} friend std::ostream& operator<<(std::ostream& os,const pathlog& e) { os<<e.hop<<" "<<e.passedthru<<std::endl; return os; } }; // structs for data struct hop{}; struct passedthru{}; // multi-index container setup typedef multi_index_container< pathlog, indexed_by< ordered_unique< tag<hop>, BOOST_MULTI_INDEX_MEMBER(pathlog,std::string,hop)>, ordered_non_unique< tag<passedthru>, BOOST_MULTI_INDEX_MEMBER(pathlog,int,passedthru)> > > pathlog_set; int disassemblepathlog(const string& str, pathlog_set& routecontainer, const string& delimiters = ","){ // Tokenizer (heavily modified) from http://oopweb.com/CPP/Documents/CPPHOWTO/Volume/C++Programming-HOWTO-7.html // Skip delimiters at beginning. string::size_type lastPos = str.find_first_not_of(delimiters, 0); // Find first "non-delimiter". string::size_type pos = str.find_first_of(delimiters, lastPos); while (string::npos != pos || string::npos != lastPos) { // Found a token, add it to the vector. routecontainer.insert(pathlog((str.substr(lastPos, pos - lastPos)),1)); // if this fails, I need to increment the counter! // Skip delimiters. Note the "not_of" lastPos = str.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = str.find_first_of(delimiters, lastPos); } }
Your call to insert returns a std::pair< iterator, bool >. The bool will be true only if the insert succeeded. See http://www.boost.org/doc/libs/1_43_0/libs/multi_index/doc/reference/ord_indices.html#modifiers
3,129,419
3,129,532
How to get boost::iostream to operate in a mode comparable to std::ios::binary?
I have the following question on boost::iostreams. If someone is familiar with writing filters, I would actually appreciate your advices / help. I am writing a pair of multichar filters, that work with boost::iostream::filtering_stream as data compressor and decompressor. I started from writing a compressor, picked up some algorithm from lz-family and now am working on a decompressor. In a couple of words, my compressor splits data into packets, which are encoded separately and then flushed to my file. When I have to restore data from my file (in programming terms, receive a read(byte_count) request), I have to read a full packed block, bufferize it, unpack it and only then give the requested number of bytes. I've implemented this logic, but right now I'm struggling with the following problem: When my data is packed, any symbols can appear in the output file. And I have troubles when reading file, which contains symbol (hex 1A, char 26) using boost::iostreams::read(...., size). If I was using std::ifstream, for example, I would have set a std::ios::binary mode and then this symbol could be read simply. Any way to achieve the same when implementing a boost::iostream filter which uses boost::iostream::read routine to read char sequence? Some code here: // Compression // ----------- filtering_ostream out; out.push(my_compressor()); out.push(file_sink("file.out")); // Compress the 'file.in' to 'file.out' std::ifstream stream("file.in"); out << stream.rdbuf(); // Decompression // ------------- filtering_istream in; in.push(my_decompressor()); in.push(file_source("file.out")); std::string res; while (in) { std::string t; // My decompressor wants to retrieve the full block from input (say, 4096 bytes) // but instead retrieves 150 bytes because meets '1A' char in the char sequence // That obviously happens because file should be read as a binary one, but // how do I state that? std::getline(in, t); // <--------- The error happens here res += t; }
Short answer for reading file as binary : specify ios_base::binary when opening file stream. MSDN Link
3,129,736
3,130,532
Playback "clicking" noise
I am trying to write a program to play a small .wav file in C++. I have programmed it following the DirectX SDK documents to write and play on a secondary static buffer. It runs correctly except that at the end of the playback for any .wav file, there is a very noticeable "clicking" noise. I am certain that it's not a defect on my audio hardware's part because any other game that I know uses DirectSound doesn't have it. I've tried polling GetCurrentPosition for it every cycle and stopping it right before it ends but was unreliable. I can't play it on a primary buffer because .wav's played on primary buffers must be looped, which I don't want. Does anybody know a fix to this problem? Thanks in advance.
We'd need to see both the WAV file in question and the code to load the WAV file into the sound buffer. But's here's a few guesses. My first guess is that if we were to load the WAV file you have into an a visual audio editor we'd see the sound coming to an abrupt end instead of tapering off into silence. This would result in an abrubt "popping" noise with almost any audio player. My second guess is that you are copying garbage data into the sound buffer at the end. Some WAV files have extra metadata at the end of the file past the end of the DATA chunk. Not sure how you determined the positions in the sound file to copy samples from, but its easy to mess this up. Did you inspect the WAV file with a hex editor (like Visual Studio) to confirm the length of the DATA chunk is as big as it claims to be? When you debug the ReadFile call to copy data from file into the buffer, did you inspect the last several bytes of your buffer match what you saw in the hex editor?
3,129,741
3,170,079
__COUNTER__ equivalent on Xcode?
I am migrating a project from Linux to Xcode and I encountered a "version" problem.. I need a unique identifier at compile time for my dynamic stuff, on linux I was using the __ COUNTER__ preprocessor, but it seems that the gcc 4.2 used in Xcode doesn't know about __ COUNTER__ yet... So, I was wondering what I could do to solve this? I can upgrade the GCC to 4.3(which understands __ COUNTER__), by using the macports.org or something like that... I am very noob on OSX and not very good on linux =[ or find another way to accomplish this, in the case, a method to give the function/variable an unique identifier. I tried with __ LINE__ but after few days, you end up declaring stuff on the same line on different files, and playing with that is just not that produtive... Any help is appreciated! Thanks, Jonathan
@stinky472: I use a code close to what you wrote above... My problem was that I was using a macro to declare the namespaces of a project, so by that, having the fullname of the class, like class c is in a::b::c. What I did was changing my code to not rely on the namespaces itself, but add a new argument at the class macro declaration to tell what namespace it is using, like: newclass(a::b, c): public d{ }; my problem with counter was that the namespaces were being used on lots of classes, thus, creating the same variable name within the namespaces macros, and by using the new way above, I don't need the counter anymore... thanks for the help, Jonathan
3,129,838
3,129,848
Should Display Lists be cpu intensive?
My application is rendering about 100 display lists / second. While I do expect this to be intensive for the gpu, I don't see why it brings my cpu up to 80 - 90 %. Arn't display lists stored in the graphics card and not in system memory? What would I have to do to reduce this crazy cpu usage? My objects never change so that's why im using DL's instead of VBO's. But really my main concern is cpu usage and how I could reduce it. I'm rendering ~60 (or trying to) frames per second. Thanks
If you are referring to these, then I suspect the bottleneck is going to be CPU related. All the decoding of such files is done on the CPU. Sure, each individual command might result in several commands to your graphics card, which will execute quickly, but the CPU is stuck doing decoding duty.
3,129,916
3,130,371
What is wrong with this use of offsetof?
I'm compiling some c++ code in MinGW GCC 4.4.0, and getting warnings with the following form... warning: invalid access to non-static data member '<membername>' of NULL object warning: (perhaps the 'offsetof' macro was used incorrectly) This problem seems familiar - something I've tried to resolve before and failed, I think, but a while ago. The code builds fine in Visual C++, but I haven't built this particular code recently in any other compiler. The problem code is the following template... template<typename T> class c_Align_Of { private: struct c_Test { char m_Char; T m_Test; }; public: enum { e_Align = offsetof (c_Test, m_Test) }; }; Obviously I can probably use some conditional compilation to use compiler-specific functions for this, and I believe C++0x will (at long last) make it redundant. But in any case, I cannot see anything wrong with this use of offsetof. Very pedantically, it's possible that because the T parameter types are sometimes non-POD, so GCC classes c_Test as non-POD and complains (and complains and complains - I'm getting nearly 800 lines of these warnings). This is naughty by the strict wording of the standard, since non-POD types can break offsetof. However, this kind of non-POD shouldn't be a problem in practice - c_Test will not have a virtual table, and no run-time trickery is needed to find the offset of m_Test. Besides, even if c_Test had a virtual table, GCC implements the offsetof macro using an intrinsic that is always evaluated at compile-time based on the static layout of that particular type. Providing a tool then whining (sorry, warning) every time it's used just seems silly. Also, I'm not the only person around here who does this kind of thing... Answer to legit-uses-of-offsetof question I do remember having an issue with offsetof for this kind of reason, but I don't think the problem was this template. Any ideas?
Oops... The issue is with the c_Test struct being non-POD due to the T type being non-POD. Here's a quote from the GCC manual... -Wno-invalid-offsetof (C++ and Objective-C++ only) Suppress warnings from applying the ‘offsetof’ macro to a non-POD type. According to the 1998 ISO C++ standard, applying ‘offsetof’ to a non-POD type is undefined. In existing C++ implementations, however, ‘offsetof’ typically gives meaningful results even when applied to certain kinds of non-POD types. (Such as a simple ‘struct’ that fails to be a POD type only by virtue of having a constructor.) This flag is for users who are aware that they are writing nonportable code and who have deliberately chosen to ignore the warning about it. The restrictions on ‘offsetof’ may be relaxed in a future version of the C++ standard. My problem is that almost all my T types have constructors, and are therefore classed as non-POD. I ignored this point as irrelevant earlier - and of course it should be irrelevant for offsetof in principle. The trouble is that the C++ standard uses the one POD vs. non-POD classification even though there are a number of distinct ways to be non-POD, and the compiler is correct to warn about non-standards-compliant use by default. My solution for the moment will be the option above to suppress the warning - now I just need to figure out how to tell cmake to use it.
3,130,059
3,130,073
Member offset macro - need details
Please take a look at this macro. It is used in Symbian OS SDK, which compiler is based on GCC (< 4 version of it). #ifndef _FOFF #if __GNUC__ < 4 #define _FOFF(c,f) (((TInt)&(((c *)0x1000)->f))-0x1000) #else #define _FOFF(c,f) __builtin_offsetof(c,f) #endif #endif I understand that it is calculating offset to specific class/struct member. But I cannot understand how that weird statement works - what is the constant 0x1000 and why is it there? Could somebody please explain this to me?
"If there was a member of struct c starting exactly at the (perfectly-aligned;-) address 0x1000, then at what address would the struct's member f be?" -- answer: the offset you're looking for, minus of course the hypothetical starting address 0x1000 for the struct... with the difference, AKA distance or offset, computed as integers, otherwise the automatic scaling in address arithmetic throws you off (whence the cast). What parts of the expression, specifically, are giving you problems? The inner part &(((c *)0x1000)->f) is "the address of member f of a hypothetical struct c located at 0x1000. Right in front of it is the cast (I assume TInt is some kind of integer type, of course), then the - 0x1000 to get the offset (AKA distance or difference between the address of the specific member of interest and the start of the whole structure).
3,130,169
3,130,397
How to convert a hex float to a float in C/C++ using _mm_extract_ps SSE GCC instrinc function
I'm writing a SSE code to 2-D convolution but SSE documentation is very sparse. I'm calculating dot-product with _mm_dp_ps and using _mm_extract_ps to get the dot-product result but _mm_extract_ps returns a hex float and I can't figure out how to convert this hex float to a regular float. I could use __builtin_ia32_vec_ext_v4sf that returns a float but I wanna keep compatibility with others compilers. _mm_extract_ps (__m128 __X, const int __N) { union { int i; float f; } __tmp; __tmp.f = __builtin_ia32_vec_ext_v4sf ((__v4sf)__X, __N); return __tmp.i; } What point I'm missing? A little help will be appreciated, thanks. OpenSUSE 11.2, GCC 4.4.1, C++ Compiler options: -fopenmp -Wall -O3 -msse4.1 -march=core2 Linker options: -lgomp -Wall -O3 -msse4.1 -march=core2
You should be able to use _MM_EXTRACT_FLOAT. Incidentally it looks to me as if _mm_extract_ps and _MM_EXTRACT_FLOAT should be the other way around, i.e. _mm_extract_ps should return a float and _MM_EXTRACT_FLOAT should return the int representation, but what do I know.
3,130,407
3,130,688
C++: wide characters outputting incorrectly?
My code is basically this: wstring japan = L"日本"; wstring message = L"Welcome! Japan is "; message += japan; wprintf(message.c_str()); I'm wishing to use wide strings but I do not know how they're outputted, so I used wprintf. When I run something such as: ./widestr | hexdump The hexidecimal codepoints create this: 65 57 63 6c 6d 6f 21 65 4a 20 70 61 6e 61 69 20 20 73 3f 3f e W c l m o ! e J p a n a i s ? ? Why are they all jumped in order? I mean if the wprintf is wrong I still don't get why it'd output in such a specific jumbled order! edit: endianness or something? they seem to rotate each two characters. huh. EDIT 2: I tried using wcout, but it outputs the exact same hexidecimal codepoints. Weird!
You need to define locale #include <stdio.h> #include <string> #include <locale> #include <iostream> using namespace std; int main() { std::locale::global(std::locale("")); wstring japan = L"日本"; wstring message = L"Welcome! Japan is "; message += japan; wprintf(message.c_str()); wcout << message << endl; } Works as expected (i.e. convert wide string to narrow UTF-8 and print it). When you define global locale to "" - you set system locale (and if it is UTF-8 it would be printed out as UTF-8 - i.e. wstring will be converted) Edit: forget what I said about sync_with_stdio -- this is not correct, they are synchronized by default. Not needed.
3,130,408
3,130,557
QString::fromWCharArray gives strange charracters
I have a string named aDrive = "H:/" i want to convert this string into WCHAR so used like below WCHAR Drive[4]; aDrive.toWCharArray ( Drive ) ; when i printed it qDebug ()<<QString::fromWCharArray ( Drive ); it displays like "H:/???" why i get the starnge charracters at the end.. Thank you for your time
QString::toWCharArray() does not zero-terminate the array. Without an explicit array length with QString::fromWCharArray(), it will read wchars until a zero wchar is read. In this case, you'll have to add the zero wchar yourself at the end, or use explicit length parameter with QString::fromWCharArray(). As always, the documentation is your friend.
3,130,462
3,130,622
OpenGL extensions causing linker problems
I'm trying to get the addresses for the VBO addon. In my stdafx.h I have the gl.h, glext.h and wglext.h If I do: glGenBuffersARB = (PFNGLGENBUFFERSARBPROC)wglGetProcAddress("glGenBuffersARB"); glGenBuffersARB(0,0); in stdafx.cpp, this will compile. but if I try to use glGenBuffersARB(0,0); in any of my other h or cpp files I get: Error 11 fatal error LNK1169: one or more multiply defined symbols found C:\Users\Josh\Documents\Visual Studio 2008\Projects\Vectorizer Project\Release\Vectorizer Project.exe Error 10 error LNK2005: _glGenBuffersARB already defined in OGLENGINE.obj stdafx.obj what is the proper way of doing this so I can use the vbo extension anywhere in my code? Thanks
_glGenBuffersARB already defined You probably declared glGenBuffersARB as a global variable in a header (*.h) file, and forgot to add "extern". what is the proper way of doing this so I can use the vbo extension anywhere in my code? Use GLEE or GLEW.
3,130,490
3,130,502
Deleting string object in C++
I have a string object in my C++ program declared as follows: string str; I have copied some data into it and done some operations. Now I want to delete the str object from the memory. I am not able to use delete operator since str is not a pointer. How do I delete that object from the memory to reclaim the memory allocated to it? Thanks, Rakesh.
You don't have to. When the string goes out of scope, it's destructor will be called automatically and the memory will be freed. If you want to clear the string right now (without waiting until it goes out of scope) just use str.clear().
3,130,588
3,130,606
C++ question: feature similar to Obj-C protocols?
I'm used to using Objective-C protocols in my code; they're incredible for a lot of things. However, in C++ I'm not sure how to accomplish the same thing. Here's an example: Table view, which has a function setDelegate(Protocol *delegate) Delegate of class Class, but implementing the protocol 'Protocol' Delegate of class Class2, also implementing 'Protocol' setDelegate(objOfClass) and setDelegate(objOfClass2) are both valid In Obj-C this is simple enough, but I can't figure out how to do it in C++. Is it even possible?
Basically, instead of "Protocol" think "base class with pure virtual functions", sometimes called an interface in other languages. class Protocol { public: virtual void Foo() = 0; }; class Class : public Protocol { public: void Foo() { } }; class Class2 : public Protocol { public: void Foo() { } }; class TableView { public: void setDelegate(Protocol* proto) { } };
3,130,655
3,130,720
Freeing memory for const char * variable in C++
I have a variable declared as const char *. I have allocated memory for that using malloc(). After using it, I want to free that memory using free(). But I am not able to do that and it gives me error that "Attempting to write to protected memory". How do I free the memory allocated? Thanks, Rakesh.
If you're getting that error then you're doing something wrong and you'll need to post the code so we can figure out what it is. For what it's worth, you can free a const char* as evidenced in the following code, which compiles and executes perfectly: #include <cstdlib> int main (void) { const char *x = (const char*) malloc (100); free ((void*) x); return 0; }
3,130,731
3,130,760
MessageBox in Out-of-Process COM Server
When you have a console based client and a COM Server, can you call ::MessageBox(...) from the COM Server and expect it to work?
Yes, you can, but in some cases the box will be shown on another desktop and effectively block the calling thread, so you better not try this other than for debugging purposes.
3,130,734
3,131,019
Exception Safety in Qt
Wikipedia says that "A piece of code is said to be exception-safe, if run-time failures within the code will not produce ill effects, such as memory leaks, garbled stored data, or invalid output. Exception-safe code must satisfy invariants placed on the code even if exceptions occur." And it seems that we need exception handling for exception safety. Ot the other hand, exception handling is not very popular in Qt applications as long as I see. What are your best practices in Qt to satisfy exception safety? What do you use instead of exception handling?
C++ has a very powerful mechanism for excpetion-safety. Destructors are run for all variables that go out of scope due to an exception. This differs from languages like Java, where exception-safety requires the programmer to get the catch and finally clauses right. The C++ behavior of calling destructors works seamlessly with Qt objects on the stack. Qt classes all have destructors and none require manual cleanup. Furthermore, QSharedPointer<T> can be used to manage heap-allocated Qt objects; when the last pointer goes out of scope the object is destroyed. This includes the case where the pointer goes out of scope due to an exception. So, exception-safety is certainly present in Qt. It's just transparent.
3,130,927
3,132,434
How to pass map into py?
I want to use c++ load py. But one of parameters of a function is dict. So, can I pass the map in C++ to dict in py?
Your problem description is a little terse. If I understand correctly though, you'd like to embed a Python interpreter within a C++ application and, from C++, you want to be able to instruct the interpreter to load Python modules. If this is correct, then the answer is no. The Python C API expects a Python object whenever a dict is required. If you wish to use a C++ map, you'll have to use the Python C API and manually manage the coversion between the keys & values. Depending on your needs, the Boost.Python library may be able to simplify some of the cross-language code for you.
3,130,995
3,131,027
How to move QSplitter?
Say I have a window, where there are 2 horizontal sppliters, and a button. How to move a splitter up/down by clicking on the button?
Take a look at http://doc.qt.io/qt-4.8/qsplitter.html#setSizes. The main point is that there is no method to move the splitter explicitly, you can only achieve similar behaviour by resizing the widgets in the QSplitter themselves, which is easily accomplished by using QSplitter::setSizes. I would do something like QList<int> currentSizes = mySplitter->sizes(); // adjust sizes individually here, e.g. currentSizes[0]++; currentSizes[1]--; mySplitter->setSizes(currentSizes); which would move a horizontal splitter with two widgets by one pixel. You would have to add a check to avoid negative sizes, of course.
3,131,055
3,131,248
Deleting registry key values
In MSDN it says that RegEnumValue should not be used when calling function that change the registry keys being enumerated. So does this also apply to deleting registry key values? Like this code does: if (RegOpenKeyEx(m_hkey,m_path.c_str(),0,KEY_ALL_ACCESS,&key) == ERROR_SUCCESS) { bool error=false; idx=0; while (RegEnumValue(key,idx,name,&namesize,NULL,NULL,NULL,NULL) == ERROR_SUCCESS && !error) { error=(RegDeleteValue(key,name)!=ERROR_SUCCESS); idx++; } RegCloseKey(key); }
Your code does not work. When you delete index 0, the next item becomes index 0, and you do not delete that. So yes, it applies to deleting key values.
3,131,123
3,132,089
Boost.Test and Forking
I'm using Boost.Test for Unit testing and am currently running various mock servers in separate threads which get launched from within each test. In order to more accurately test my code the mock server's should really be in separate processes. I was thinking about doing something along these lines: MY_TEST() if (fork() == 0) { runMockServer(); // responds to test requests or times out, then returns exit(0); } // Connect to MockServ and Run actual test here END_TEST() but I'm worried that this will screw up the testing framework. Is this safe? Has anyone done something like this? I'm using Boost 1.34.1 on Ubuntu 8.04 if that matters.
This doesn't really sound like unit-testing for what you want to achieve. Though I don't see why it would not be safe. You may have a race condition where your unit test connects to the MockServ if it isn't ready yet, but that is easily solvable. I've never done something like this directly, but I have written unit tests for libraries that fork/exec child processes and it works flawlessly.
3,131,294
3,131,394
Situation where mutexes are necessary?
Can someone help me out with example of a situation in which absence of mutexes "definetely" leads to incorrect result. I need this so that I could test my mutex implementation. -- Neeraj
Consider any correct code that uses mutexes for synchronization. By removing the locking, you will introduce new (possibly incorrect) behaviors (executions) to the program. However, the new code will still contain all of the old behaviors, therefore there will always be at least one execution that will yield a correct result. Hence, what you're asking for is impossible.
3,131,298
3,131,343
File Reading issue in c++
I have the following program, int iIndex=0; char cPort[5]={"\0"}; char cFileChar; fopen_s(&fFile,"c:\\Config\\FileName.txt","r"); if(fFile !=0) { cFileChar = getc(fFile); while (cFileChar!= EOF) { cPort[iIndex]=cFileChar; iIndex++; cFileChar = getc(fFile); } iDIPort=atoi(cPort); } in the file I have 32000, but when the program execute and read from the file sometime its read fine and set iDIPort to 32000 but sometime it set the variable value to 320000. Kindly help me to sort out this problem.
You write the 5 characters into the cPort array. That's OK. But then, you use cPort as a parameter to the atoi function. This function expects a C zero-terminated-string as argument. As your cPort variable has no space to store this zero-value-char to indicate the end of the string, your code depends on what is right after the cPort variable in memory. The easiest way to solve your problem is to define cPort as an array of 6 chars, and to assign 0 to cPort[5] right before calling atoi. But this won't solve the other issues of your code, the main being not to check if the number you read from the file has more than 5 figures.
3,131,478
3,131,722
Duplicate literals and hard-coding
I see the follow pattern occurring quite frequently: b->last = ngx_cpymem(b->last, "</pre><hr>", sizeof("</pre><hr>") - 1); Notice that the literal string is used twice. The extract is from the nginx source-base. The compiler should be able to merge these literals when it is encountered within the compilation unit. My questions are: Do the commercial-grade compilers(VC++, GCC, LLVM/Clang) remove this redundancy when encountered within a compilation unit ? Does the (static) linker remove such redundancies when linking object files. if 2 applies would this optimization occur during dynamic linking ? If 1 and 2 apply, do they apply to all literals. These questions are important because it allows a programmer to be verbose without losing efficiency -- i.e., think about enormous static data models being hard-wired into a program (for example the rules of a Decision Support System used in some low-level scenario). Edit 2 points / clarifications The code above is written by a recognised "master" programmer. The guy single handedly wrote nginx. I have not asked which of the possible mechanisms of literal hard-coding is better. Therefore don't go off-topic. Edit 2 My original example was quite contrived and restrictive. The following snippet shows the usage of string literals being embedded into internal hard-coded knowledge. The first snippet is meant for the config parser telling it what enum values to set for which string, and the second to be used more generally as a string in the program. Personally I am happy with this as long as the compiler uses one copy of the string literal, and since the elements are static, they don't enter the global symbol tables. static ngx_conf_bitmask_t ngx_http_gzip_proxied_mask[] = { { ngx_string("off"), NGX_HTTP_GZIP_PROXIED_OFF }, { ngx_string("expired"), NGX_HTTP_GZIP_PROXIED_EXPIRED }, { ngx_string("no-cache"), NGX_HTTP_GZIP_PROXIED_NO_CACHE }, { ngx_string("no-store"), NGX_HTTP_GZIP_PROXIED_NO_STORE }, { ngx_string("private"), NGX_HTTP_GZIP_PROXIED_PRIVATE }, { ngx_string("no_last_modified"), NGX_HTTP_GZIP_PROXIED_NO_LM }, { ngx_string("no_etag"), NGX_HTTP_GZIP_PROXIED_NO_ETAG }, { ngx_string("auth"), NGX_HTTP_GZIP_PROXIED_AUTH }, { ngx_string("any"), NGX_HTTP_GZIP_PROXIED_ANY }, { ngx_null_string, 0 } }; followed closely by: static ngx_str_t ngx_http_gzip_no_cache = ngx_string("no-cache"); static ngx_str_t ngx_http_gzip_no_store = ngx_string("no-store"); static ngx_str_t ngx_http_gzip_private = ngx_string("private"); To those that stayed on topic, bravo !
Note that for the specific case of sizeof("</pre><hr>"), it is virtually certain that the string literal will never appear in the output file - the entire sizeof expression can be evaluated to the integer constant 11 at compile-time. Notwithstanding, it is still a very common optimisation for compilers to merge identical string literals.
3,131,532
3,185,312
IPv6 Zone index and scope_id
How does the zone index relate to the scope_id in the sockaddr_in6 structure? The functionality appears to differ between platforms and I'd love to know how they relate. Windows for example has a SCOPE_ID structure (as well as just a 32-bit value). Mac OSX only has a 32-bit value. Obviously the 32-bit value is the way to go but how exactly is it laid out? Is it still the top 4 bits are the "level"? How does network byte order affect this? Also I assume that, under windows, the zone index given in the ip address (eg FF80::1%1) translates directly to the bottom 28 bits of the aforementioned structure. How does it work under Mac OSX that uses names rather than numbers (eg FF80::1%en0). Do I encode it as a four CC? Equally I seem to recall that linux uses 4 characters which couldn't possibly fit in 28-bits. So can someone explain this mess to me? I really am going to need to write a tutorial on all this when I'm finished because there is precious little info about ipv6 around the net. Edit: Is the scope_id in network byte order? I'm just looking at the scope_id returned from a recvfrom and it appears to be in little-endian order ... that can't be right can it?
The index of zone and scope are the same and frequently interchanged, however the terms themselves are different. Scope is used as in "global scope", "local scope", "universal scope" and refer to how unique a particular IPv6 address is. Every interface has a local scope which is unique to the immediate LAN segment, which is say useful for automatic configuration and discovery of local devices, say a printer you just plugged into the network. Global scope IPv6 address may be provided by a DHCP server. Zone is to specify a particular effective interface within the local scope. The scope index is different from interface index such that to specify an interface I use a structure as follows: struct interface_req_t { uint32_t ir_interface; uint32_t ir_scope_id; }; Each platform is unique into how it interprets the value, with Windows having several re-interpretations of interface enumeration depending on domain. The downside with the Windows implementation is that the index can change when you hot swap adapters. On Unix you tend to see interface names %qe0, %eth0, etc, that can be resolved to numeric form when required, e.g. if_nametoindex(). Windows Vista adds a compatible API. Only the local scope is identifiable by it's address prefix fe80::/10. The Windows SCOPE_ID shows over design that also exists in IPv4 multicast, i.e. splitting administration domains of addresses. It's all purely optional and frequently ignored.
3,131,715
3,131,781
Understanding template classes in c++ - problem with new-operator
Dear all, I've been stuck with this problem now for a few days and my searches were not successful. What I am trying to do: I want a template reader class (VariableReader) to handle different types of variables (usually unsigned int and pointers to vector). I started with #ifndef READER_H_ #define READER_H_ #include <string> namespace BAT { template <typename variableType = unsigned int> class VariableReader { public: VariableReader<variableType>(); VariableReader<variableType>(std::string varName); virtual ~VariableReader<variableType>(); std::string getVariableName(); void setVariableName(std::string varName); bool isValidVariableName(std::string varName); variableType getVariable(); private: std::string variableName; variableType variable; }; } #endif and #include "../../interface/Readers/VariableReader.h" namespace BAT { template<typename variableType> VariableReader<variableType>::VariableReader() : variableName("") { // TODO Auto-generated constructor stub } template <typename variableType> VariableReader<variableType>::VariableReader(std::string varName) : variableName(varName) { } template <typename variableType> std::string VariableReader<variableType>::getVariableName() { return variableName; } template <typename variableType> void VariableReader<variableType>::setVariableName(std::string varName) { if (VariableReader::isValidVariableName(varName)) { variableName = varName; } } template <typename variableType> bool VariableReader<variableType>::isValidVariableName(std::string varName) { return varName != ""; } template <typename variableType> VariableReader<variableType>::~VariableReader() { // TODO Auto-generated destructor stub } } However, although it seems to compile I can't use it within other projects. EDIT: forgot to post test-code: #include "cute.h" #include "ide_listener.h" #include "cute_runner.h" #include "Readers/VariableReader.h" using namespace BAT; static VariableReader<int> *reader; void setUp(){ reader = new VariableReader<int>::VariableReader();//this is problem-line } void thisIsATest() { ASSERTM("start writing tests", false); } void runSuite(){ cute::suite s; //TODO add your test here s.push_back(CUTE(thisIsATest)); cute::ide_listener lis; cute::makeRunner(lis)(s, "The Suite"); } int main(){ runSuite(); } I get following error message: Building target: BAT_Tests Invoking: GCC C++ Linker g++ -L"/workspace/BAT/Debug Gcov" -fprofile-arcs -ftest-coverage -std=c99 -o"BAT_Tests" ./src/Test.o -lBAT ./src/Test.o: In function `setUp()': /workspace/BAT_Tests/Debug Gcov/../src/Test.cpp:13: undefined reference to `BAT::VariableReader<int>::VariableReader()' collect2: ld returned 1 exit status make: *** [BAT_Tests] Error 1 As I understand it the linker tries to find the constructor for VariableReader, which is not explicitly defined since I want to have a general constructor only. Please help me to understand what I am missing.
The C++ FAQ Lite section on How can I avoid linker errors with my template functions? shows two solutions: Move the template class's methods into the .h file (or a file included by the .h file). Instantiate the template in the .cpp file using template VariableReader<unsigned int>;.
3,131,991
3,132,035
Iterating over 2-dimensional STL vector c++
I'm currently trying to print out a history of movements for players in a game I am working on. At the end of each round every player has moved some amount in the positive or negative direction and this gets recorded as an int in the movement vector. Eventually I'm wanting to plot the directions moved vs time for each player but I'm having trouble extracting the data out of the 2d vector. So the first thing I tried was to just iterate and print all the elements, however this doesn't compile: void output_movement(const std::vector< std::vector<int> > & movement){ std::vector< std::vector<int> >::iterator row; std::vector<int>::iterator col; for (row = movement.begin(); row != movement.end(); ++row) { for (col = row->begin(); col != row->end(); ++col) { std::cout << **col; } } } The compiler gives this error message which I don't really understand: hg_competition.cpp:45: error: no match for ‘operator=’ in ‘row = ((const std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >*)money_movement)->std::vector<_Tp, _Alloc>::begin [with _Tp = std::vector<int, std::allocator<int> >, _Alloc = std::allocator<std::vector<int, std::allocator<int> > >]()’ /usr/include/c++/4.4/bits/stl_iterator.h:669: note: candidates are: __gnu_cxx::__normal_iterator<std::vector<int, std::allocator<int> >*, std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > > >& __gnu_cxx::__normal_iterator<std::vector<int, std::allocator<int> >*, std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > > >::operator=(const __gnu_cxx::__normal_iterator<std::vector<int, std::allocator<int> >*, std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > > >&) Any help is greatly appreciated!
You need to use a const_iterator if the vector is a const reference. Also, to output col you only need to dereference it once. void output_movement(const std::vector< std::vector<int> > & movement){ std::vector< std::vector<int> >::const_iterator row; std::vector<int>::const_iterator col; for (row = movement.begin(); row != movement.end(); ++row) { for (col = row->begin(); col != row->end(); ++col) { std::cout << *col; } } } Edit: using typedefs will make your code more readable typedef std::vector<int> Vector; typedef std::vector<Vector> DoubleVector; void output_movement( const DoubleVector& movement ) { for (DoubleVector::const_iterator row = movement.begin(); row != movement.end(); ++row) { for (Vector::const_iterator col = row->begin(); col != row->end(); ++col) { std::cout << *col; } std::cout << std::endl; } }
3,132,491
3,132,550
How can i optimize this dijkstra structure code?
This is the dijkstra structure i am using :(however the MAXV(which is maximum number of vertices is maximum at 500 and every time i try to change it to something more than this it generates and error when running ) -I want to use this way to represent a graph with 10000 vertices, does anyone know how to optimize it ? #include<iostream> #include<stdio.h> #include<stdlib.h> #include<conio.h> using namespace std; #define MAXV 500 #define MAXINT 99999 typedef struct{ int next; int weight; }edge; typedef struct{ edge edges[MAXV][MAXV]; int nedges; int nvertices; int ndegree[MAXV]; }graph; and this is my dijkstra code: int dijkstra(graph *g,int start,int end){ int distance[MAXV]; bool intree[MAXV]; for(int i=0;i<=MAXV;++i){ intree[i]=false; distance[i]=MAXINT; } int v=start; distance[v]=0; while(intree[v]==false){ intree[v]=true; for(int i=0;i<g->ndegree[v];++i){ int cand=g->edges[v][i].next; int weight=g->edges[v][i].weight; if(distance[cand] > distance[v]+weight){ distance[cand] = distance[v]+weight; } } int dist=MAXINT; for(int i=0;i<g->nvertices;++i){ if((intree[i]==false) && (dist > distance[i])){ dist=distance[i]; v=i; } } } return distance[end]; }
Use adjacency lists for storing the graph. Right now you're using an adjacency matrix, which means that you allocate MAXV*MAXV*sizeof(edge) bytes just for that. That's a lot when MAXV is 10 000, so you're probably getting a segmentation fault. Switching to adjacency lists will get rid of the error. However, even with adjacency lists, the Dijkstra algorithm you have right now is O(n^2) where n is the number of nodes. That's still a lot for 10 000 nodes. Consider implementing Dijkstra with heaps (also here) if you have to support this many nodes.
3,132,607
3,132,884
Static class variable--use with constructors
I have a class with a static variable: null. static Pointer<Value> Null; Pointer is a class which uses reference count memory management. However, I get an error: no matching function for call to Pointer::Pointer() On the line: Pointer<Value> Value::Null(new Value()); Thanks. Excerpt of Pointer class: template <typename T> class Pointer { public: explicit Pointer(T* inPtr); Constructor Source mPtr = inPtr; if (sRefCountMap.find(mPtr) == sRefCountMap.end()) { sRefCountMap[mPtr] = 1; } else { sRefCountMap[mPtr]++; }
I'm assuming your class is named Value. // Header file class Value { public: ... static const Pointer<Value> Null; }; // This should be in the cpp file. const Pointer<Value> Value::Null(new Value);
3,132,608
3,132,682
Multi-Threading on multi core architecture
When you have a situation where Thread A reads some global variable and Thread B writes to the same variable, now unless read/write is not atomic on a single core, you can do it without synchronizing, however what happens when running on a multi-core machine?
Even on a single core, you cannot assume that an operation will be atomic. That may be the case where you're coding in assembler but, if you are coding in C++ as per your question, you do not know what it will compile down to. You should rely on the synchronisation primitives at the level of abstraction that you're coding to. In your case, that's the threading calls for C++. whether they be pthreads, Windows threads or something else entirely. It's the same reasoning that I gave in another answer to do with whether i++ was thread-safe. The bottom line is, you don't know since you're not coding to that level (if you're doing inline assembler and/or you understand and can control what's going on under the covers, you're no longer coding at the C++ level and you can ignore my advice). The operating system and/or OS-type libraries know a great deal about the environment they're running in, far more so than the C++ compiler would. Use of proper syncronisation primitives will save you a great deal of angst.
3,132,811
3,133,057
Borland Warning 8092
Regarding the following C++ code, LengthAlphabeticalSort lengthAlphabeticalSort; outputList.sort(lengthAlphabeticalSort); // causes borland 8092 error, guaranteed stable_sort. class LengthAlphabeticalSort { public: bool operator() (std::string str1, std::string str2) { if(str1.length() < str2.length()) return true; else return false; } }; I get a warning when compiling with the borland compiler: Warning W8092 worder.cpp 138: template argument _Pr3 passed to 'sort' is not an iterator: random iterator required in function Worder::CommonWords(const Worder &) const Turbo Incremental Link 5.69 Copyright (c) 1997-2005 Borland Can anybody tell me how to fix this problem? It compiles cleanly with VS2010 and gnu
Well, the sort member function on a std::list does take a binary functor like yours, so from looking at your posted code, I'd say your compiler is wrong. However, the error message you posted puzzles me: random iterator required in function Worder::CommonWords(const Worder &) const Why is it saying that a random iterator is required in CommonWords? Is CommonWords the function from which sort is called?
3,132,935
3,132,998
how to get message of catch-all exception
If I want to write useful info to a file whenever i caught a catch-all exception, how to do it? try { //call dll from other company } catch(...) { //how to write info to file here??????? }
You can't get any information out of the ... catch block. That is why code usually handles exceptions like this: try { // do stuff that may throw or fail } catch(const std::runtime_error& re) { // speciffic handling for runtime_error std::cerr << "Runtime error: " << re.what() << std::endl; } catch(const std::exception& ex) { // speciffic handling for all exceptions extending std::exception, except // std::runtime_error which is handled explicitly std::cerr << "Error occurred: " << ex.what() << std::endl; } catch(...) { // catch any other errors (that we have no information about) std::cerr << "Unknown failure occurred. Possible memory corruption" << std::endl; }
3,133,132
3,133,187
how to catch exception in C# which call a C++ dll
My C# called a method from a C++ dll, after the call returned, my application just gone without any message. want to add try catch to get the reason. how can I do it. Just a try-catch in the method call? EDIT: the [HandledProcessCorruptedStateExceptions] is not belong to C#?
An interesting article on exception handling, also with respect to handling corrupted state exceptions: CLR Inside Out: Handling Corrupted State Exceptions However, I would assume that there is something wrong either in the way you are calling the native method or in the native method itself. It's best to fix the original problem that is causing the CSE instead of catching exceptions that indicate that your application is no longer in a stable state. You probably will only make things worse by catching such an expcetion. The article mentioned above states: Even though the CLR prevents you from naively catching CSEs, it's still not a good idea to catch overly broad classes of exceptions. But catch (Exception e) appears in a lot of code, and it's unlikely that this will change. By not delivering exceptions that represent a corrupted process state to code that naively catches all exceptions, you prevent this code from making a serious situation worse.
3,133,286
3,133,314
Header file throwing errors in one project, but not in another
I'm trying to integrate two projects, and to that end am including header files from one into the other. I'm using visual studio 2008 express. The line int E4407B_PPM(int &); is throwing errors in the new project, but the original project compiles just fine. The error I'm getting: error C2143: syntax error : missing ')' before '&' Any ideas? Edit: I ended up removing the lines that took parameters in by reference, and just insured that all functions were declared before they were used in the actual source file. I guess it was a C++/C thing.
You are probably building the second project (or at least the source file) as straight C. Make sure the file has a .cpp extension or that you are forcing a C++ compile (you can use the /TP compile option to do that). Edit You can specify it for a single file: Right click on the file in the solution explorer and select Properties. Click on the Advanced option under C/C++. Choose "Compile as C++ Code (/TP)" (second option in the page in my version of Visual Studio).
3,134,060
5,247,114
Is it possible to have a QMaemo5ListPickSelector which displays images as items?
I wanted to know if its possible to have a QMaemo5ListPickSelector but one which displays rectangular images as list items instead of text ? Is this possible ? If not, is there any other list-like object in Qt which can show images as items instead of text ?
You can access list view using QMaemo5ListPickSelector::view() and set item delegate for this view using QAbstractItemView::setItemDelegate(). In delegate item's visual presentation is pretty much unlimited. See Star Delegate example to get into the details of delegate's implementation http://doc.qt.nokia.com/qt-maemo/itemviews-stardelegate.html
3,134,099
3,268,045
Exception thrown when exiting program (Ogre3d)
I am getting a weird exception when I exit the program. This has started since today morning and I am ready to pull my hair out. As soon as I exit the program, visual studio gives an exception and stops at line 731 in the file crt0dat.c (see attached screenshot) I know this is very little to go on. I have tried several different things: un the program without doing anything, that is, not initializing Ogre Core at all. Does not result in a crash Run the program with everything commented out except creating Ogre root (which is related to Ogre itself and has nothing to do with my code), results in the same crash Run the following program which is as basic as it gets, still results in the crash. The crash happens after return 0, when my program has finished running #include "windows.h" #include "OgreRoot.h" /// -------------------------------------------- INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT) { Ogre::Root* lRoot = new Ogre::Root(); delete lRoot; lRoot = NULL; return 0; } /// -------------------------------------------- Since I have everything on the SVN, I ran the same project on my laptop and it worked without any problems, as well as exited without any problems. This led me to believe that somewhere along the line my visual studio got corrupted. I uninstalled Visual studio, then re-installed it, but the problem persists (When VS installs it goes all over my system. No way to contain it. Does anyone know a surefire way to completely destroy Visual Studio installation?). I am running out of ideas, short of re-installing windows. I hope someone here can be of help. Callstack: 048b0910() ntdll.dll!775d9901() [Frames below may be incorrect and/or missing, no symbols loaded for ntdll.dll] ntdll.dll!775edc30() ntdll.dll!775edb7c() kernel32.dll!76c67363() > msvcr90d.dll!__crtExitProcess(int status=0) + 0x1b bytes C msvcr90d.dll!doexit(int code=0, int quick=0, int retcaller=0) + 0x1d1 bytes C msvcr90d.dll!exit(int code=0) + 0x12 bytes C OgreFWGame.exe!__tmainCRTStartup() + 0x2a2 bytes C OgreFWGame.exe!WinMainCRTStartup() + 0xf bytes C kernel32.dll!76c63677() ntdll.dll!775d9d42() ntdll.dll!775d9d15() Crash Screencapture: link text
Thanks for everybody's help on this problem. I ended up re-installing windows (I tried uninstalling Visual Studio and re-installing it, but something went wrong while uninstalling VS [I followed Microsoft's instructions to the letter] and it would refuse to install again [the setup would crash]). I wish they would make it easy to Uninstall Visual Studio. I wasted about 3 days before I resorted to re-installing windows. My advice would be, if you have another computer to continue to do your work on, is to do the same if something like this happens rather than waste days. If you do find a way to fix the problem, please let me know :)
3,134,183
3,134,368
Understanding the low-level mouse and keyboard hook (win32)
I'm trying to capture global mouse and keyboard input. LRESULT CALLBACK MouseHookProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode >= 0) { if (wParam == WM_RBUTTONDOWN) printf("right mouse down\n"); if (wParam == WM_RBUTTONUP) printf("right mouse up\n"); } return CallNextHookEx(0, nCode, wParam, lParam); } HHOOK mousehook = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc, NULL, 0); while(true) { MSG msg; if (PeekMessage(&msg,0,0,0,PM_REMOVE)) { printf("msg recvd\n"); TranslateMessage(&msg); DispatchMessage(&msg); } #ifdef TEST Sleep(50); #endif } So everything works here, except if I #define TEST to put in the Sleep, the mouse becomes incredibly sluggish, as might be expected if I suddenly only allow the mouse to update 20 times a second. And without the sleep, I am pegging the CPU at 100%. But that's okay for now (that goes away if I use GetMessage). Now as I understand it, the low-level hooks work by context-switching to the process which installed it, and then sending the process some kind of message to let it execute the hook callback. What confuses me a little, though, is why my program will never print "msg recvd", but it prints "right mouse down/up" whenever i click the right mouse button. This leads me to conclude that my MouseHookProc is being invoked during the PeekMessage call. It just happens to be some kind of special message and PeekMessage returns 0. But I still need to call PeekMessage or some equivalent. Since my program needs to do a bunch of things, I clearly can't weigh down my message pumping loop (the one that calls PeekMessage) by calling another function that takes, say 50ms to return. How might I multithread my program to maintain mouse responsiveness while simultaneously doing a little heavy lifting? In a multithreaded win32 program, there is still just one message queue, right? Update: After reading up on MS's documentation I think I know what the right thing for me to do is. I should just spawn a thread in my application which calls SetWindowsHookEx to register the mouse hook, and then sit around in its own message loop, and the system will take care of sending the mouse updates to this thread. It will be free to do whatever it wants within the MouseHookProc, and the rest of my application will run independently.
The problem is your message loop, it burns 100% CPU cycles because you use PeekMessage(). Windows knows how to keep the hook alive even if you don't poll for messages, use GetMessage() to solve your problem. Using Sleep(1) will solve your problem too but is not necessary here. Why must SetWindowsHookEx be used with a windows message queue
3,134,310
3,139,726
Use a model as a source for a QMenu
I created a model which list the existing configurations (let's say it lists "files", as this doesn't really matter here). So far, it works well when attached to a QListView. Example: --- ListView --- - file #1 - - file #2 - - file #3 - - file #4 - ---------------- Is it possible to use the same model for a dynamically updated QMenu ? Something like: Menu -> Submenu #1 -> Submenu #2 -> File-submenu -> file #1 -> file #2 -> file #3 -> file #4 -> Submenu #3 In short: is there any way to create a list of dynamicaly updated QActions (grouped into the same QMenu) depending on a model (derived from QAbstractListModel) ?
If your objective is just to update your menu actons with the item text that are available in the QAbstractListModel, then the answer is Yes. Here is a way.. Individual item's index can be obtained by using the following function. QModelIndex QAbstractListModel::index ( int row, int column = 0, const QModelIndex & parent = QModelIndex() ) const [virtual] With the obtained index, the data can be obtained by, QVariant QModelIndex::data ( int role = Qt::DisplayRole ) const Then the text availalble in the index can be obtained by using, QString QVariant::toString () const Now with the obtained QString you can add an action to the menu. QAction * QMenu::addAction ( const QString & text ) The thing you have to make sure is that, you should be able to traverse through all the items in the Model, so that you can obtain the index of the each and every item. Hope it helps..
3,134,362
3,134,393
Threading on both Windows and Linux
I have seen tutorials on the internet for making multithreaded applications in C++ on Windows, and other tutorials for doing the same on Linux, but not for both at the same time. Are there functions that would work even if they were compiled on either Linux or Windows?
You would need to use a library which contains an implementation for both pthread on Linux and the Win32 threading library on Windows (CreateThread and friends). Boost thread is a popular choice which abstracts the system away.
3,134,416
3,134,442
Why should an API return 'void'?
When writing an API or reusable object, is there any technical reason why all method calls that return 'void' shouldn't just return 'this' (*this in C++)? For example, using the string class, we can do this kind of thing: string input= ...; string.Join(input.TrimStart().TrimEnd().Split("|"), "-"); but we can't do this: string.Join(input.TrimStart().TrimEnd().Split("|").Reverse(), "-"); ..because Array.Reverse() returns void. There are many other examples where an API has lots of void-returning operations, so code ends up looking like: api.Method1(); api.Method2(); api.Method3(); ..but it would be perfectly possible to write: api.Method1().Method2().Method3() ..if the API designer had allowed this. Is there a technical reason for following this route? Or is it just a style thing, to indicate mutability/new object? (x-ref Stylistic question concerning returning void) EPILOGUE I've accepted Luvieere's answer as I think this best represents the intention/design, but it seems there are popular API examples out there that deviate from this : In C++ cout << setprecision(..) << number << setwidth(..) << othernumber; seems to alter the cout object in order to modify the next datum inserted. In .NET, Stack.Pop() and Queue.Dequeue() both return an item but change the collection too. Props to ChrisW and others for getting detailed on the actual performance costs.
Methods that return void state more clearly that they have side effects. The ones that return the modified result are supposed to have no side effects, including modifying the original input. Making a method return void implies that it changes its input or some other internal state of the API.
3,134,458
3,134,505
how to initialize a char array?
char * msg = new char[65546]; want to initialize to 0 for all of them. what is the best way to do this in C++?
char * msg = new char[65546](); It's known as value-initialisation, and was introduced in C++03. If you happen to find yourself trapped in a previous decade, then you'll need to use std::fill() (or memset() if you want to pretend it's C). Note that this won't work for any value other than zero. I think C++0x will offer a way to do that, but I'm a bit behind the times so I can't comment on that. UPDATE: it seems my ruminations on the past and future of the language aren't entirely accurate; see the comments for corrections.
3,134,532
3,134,701
MySql Connector prepared statement only transfers 64 bytes
I am using the MySql Connector C++ to store a JPEG image from a file into the database. I am using the prepared statement. After execution of the prepared statement, only the first 64 bytes of the file are copied into the database. My research of examples show that no iteration is necessary and the examples assume that the prepared statement loads the entire file. Here is my code: std::string statement_text("INSERT INTO "); statement_text += "picture_image_data"; statement_text += " ("; statement_text += "ID_Picture"; statement_text += ", "; statement_text += "Image_Data"; statement_text += ") VALUES (?, ?)"; wxLogDebug("Creating prepared statement using:\n%s\n", statement_text.c_str()); std::string filename("my_image.jpg"); Ptr_Db_Connection db_conn(db_mgr.get_db_connection()); boost::shared_ptr<sql::PreparedStatement> prepared_statement(db_conn->prepareStatement(statement_text)); prepared_statement->setInt(1, picture_id); std::ifstream blob_file(filename.c_str()); prepared_statement->setBlob(2, &blob_file); prepared_statement->execute(); blob_file.close(); Here is the schema of the table: mysql> describe picture_image_data; +------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+------------------+------+-----+---------+----------------+ | ID_Picture | int(10) unsigned | NO | PRI | NULL | auto_increment | | Image_Data | mediumblob | YES | | NULL | | +------------+------------------+------+-----+---------+----------------+ 2 rows in set (0.00 sec) From the MySql Console: mysql> select ID_Picture, LENGTH(image_data) -> FROM picture_image_data -> where ID_Picture = 1; +------------+--------------------+ | ID_Picture | LENGTH(image_data) | +------------+--------------------+ | 1 | 65 | +------------+--------------------+ 1 row in set (0.02 sec) How do I make the prepared statement read the entire file? Do I need to initialize anything in MySql Connector C++ to make this read more than 64 bytes? Note: I am using MySql Connector C++ 1.0.5, Visual Studio 2008 and wxWidgets on Windows XP and Vista. Table creation statement: CREATE TABLE Picture_Image_Data ( ID_Picture INTEGER UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY, Image_Data MEDIUMBLOB ); Hex dump (via Cygwin) of the image file: 0000000 d8ff e0ff 1000 464a 4649 0100 0101 1c00 0000010 1c00 0000 dbff 4300 0500 0403 0404 0503 0000020 0404 0504 0505 0706 080c 0707 0707 0b0f 0000030 090b 110c 120f 1112 110f 1311 1c16 1317 0000040 1a14 1115 1811 1821 1d1a 1f1d 1f1f 1713 0000050 2422 1e22 1c24 1f1e ff1e 00db 0143 0505 0000060 0705 0706 080e 0e08 141e 1411 1e1e 1e1e 0000070 1e1e 1e1e 1e1e 1e1e 1e1e 1e1e 1e1e 1e1e
The issue lies in the constructor of the image file: std::ifstream blob_file(filename.c_str()); This should have the binary mode attribute: std::ifstream blob_file(filename.c_str(), std::ios_base::binary); The file, a JPEG image, is binary data. Also, the hex dump at byte 65 shows 1a, which is the Windows OS end of file character: 0000040 1a14 1115 1811 1821 1d1a 1f1d 1f1f 1713 After fixing the constructor, the MySql shows the data size: mysql> SELECT ID_Picture, LENGTH(Image_Data) -> FROM picture_image_data -> WHERE ID_Picture = 1; +------------+--------------------+ | ID_Picture | LENGTH(Image_Data) | +------------+--------------------+ | 1 | 18453 | +------------+--------------------+ 1 row in set (0.00 sec)
3,134,718
3,134,744
Define bitset size at initialization?
I want to make a bitset in C++. I did a bit of research. All examples I found where like this: bitset<6> myBitset; // do something with it But I don't know the size of the bitset when I define the variable in my class: #include <bitset> class Test { public: std::bitset *myBitset; } This won't compile... And initializing like this also doesn't work: int size = getDependentSizeForBitset(); myBitset = new bitset<size>();
Boost has a dynamic_bitset you can use. Alternatively, you can use a vector<bool>, which (unfortunately) is specialized to act as a bitset. This causes a lot of confusion, and in general is considered a bad idea. But that's how it works, so if that's what you need, you might as well use it, I suppose.
3,134,738
3,134,809
Indexing hash tables
I am just starting to learn hashtables, and so far, I know that you take the object you want to hash and put it through an hash function, then use the index it returns to get the corresponding object you want. There is something I don't understand though: What structure do you use to store the objects in so you can quickly index them with the code returned by the hash function? The only thing I can think of is to use an array, but to handle all the keys, you'd have to allocate one that's 9999999999999 elements big or something ridiculous like that. Or is it as simple as iterating over a linked list or something and comparing the ID in each of the elements with the key from that hash function? And if so, that seems kind of inefficient doesn't it?
Yes, you usually use an array but then you do a couple of things: You convert the hash code to an array index by using the remainder of the hash code divided by the array size. You make the size of the array a prime number as that makes step #1 more efficient (some hash algorithms need this to get a uniform distribution) You come up with a design to handle hash collisions. @JerryCoffin's answer gives you more detail.
3,134,743
3,134,895
C++ program design question
In couple of recent projects that I took part in I was almost addicted to the following coding pattern: (I'm not sure if there is a proper name for this, but anyway...) Let's say some object is in some determined state and we wan't to change this state from outside. These changes could mean any behaviour, could invoke any algorithms, but the fact is that they focus on changing the state (member state, data state, etc...) of some object. And let's call one discrete way of changing those object a Mutator. Mutators are applied once (generally) and they have some internal method like apply(Target& target, ...), which instantly provokes changing the state of the object (in fact, they're some sort of functional objects). They also could be easily assimilated into chains and applied one-by-one (Mutator m1, m2, ...); they also could derive from some basic BasicMutator with virtual void apply(...) method. I have introduced classes called InnerMutator and ExplicitMutator which differ in terms of access - first of them can also change the internal state of the object and should be declared as a friend (friend InnerMutator::access;). In those projects my logic turned to work the following way: Prepare available mutators, choose which to apply Create and set the object to some determined state foreach (mutator) mutator.apply(object); Now the question. This scheme turnes to work well and (to me) seems as a sample of some non-standard but useful design pattern. What makes me feel uncomfortable is that InnerMutator stuff. I don't think declaring mutator a friend to every object which state could be changed is a good idea and I wan't to find the appropriate alternative. Could this situation be solved in terms of Mutators or could you advice some alternative pattern with the same result? Thanks.
I hope this isn't taken offensively, but I can't help but think this design is an overly fancy solution for a rather simple problem. Why do you need to aggregate mutators, for instance? One can merely write: template <class T> void mutate(T& t) { t.mutate1(...); t.mutate2(...); t.mutate3(...); } There's your aggregate mutator, only it's a simple function template relying on static polymorphism rather than a combined list of mutators making one super-mutator. I once did something that might have been rather similar. I made function objects which could be combined by operator && into super function objects that applied both operands (in the order from left to right) so that one could write code like: foreach(v.begin(), v.end(), attack && burn && drain); It was really neat and seemed really clever to me at the time and it was pretty efficient because it generated new function objects on the fly (no runtime mechanisms involved), but when my co-workers saw it, they thought I was insane. In retrospect I was trying to cram everything into functional style programming which has its usefulness but probably shouldn't be over-relied on in C++. It would have been easy enough to write: BOOST_FOR_EACH(Something& something, v) { attack(something); burn(something); drain(something); } Granted it is more lines of code but it has the benefit of being centralized and easy to debug and doesn't introduce alien concepts to other people working with my code. I've found it much more beneficial instead to focus on tight logic rather than trying to forcefully reduce lines of code. I recommend you think deeply about this and really consider if it's worth it to continue with this mutator-based design no matter how clever and tight it is. If other people can't quickly understand it, unless you have the authority of boost authors, it's going to be hard to convince people to like it. As for InnerMutator, I think you should avoid it like the plague. Having external mutator classes which can modify a class's internals as directly as they can here defeats a lot of the purpose of having internals at all.
3,134,745
3,195,976
LNK 2028 - 2019 / Managed and Unmanaged C++ ? (VS 2008)
I am trying to link an open-source library to one of my project. The library is unmanaged (named Tetgen) and my project is in managed C++. My project recognizes the header and can use the functions defined in it. But I get a 2028 error each time it wants to access to some methods defined in the .cpp: error LNK2028: unresolved token (0A000E20) "public: void __thiscall tetgenio::save_nodes(char const *)" (?save_nodes@tetgenio@@$$FQAEXPBD@Z) referenced in function "public: virtual bool __thiscall ForwardModelingPlugin::CustomMeshVol3D::tesselate(void)" (?tesselate@CustomMeshVol3D@ForwardModelingPlugin@@$$FUAE_NXZ) I have tried to create a test function: int tetgenio::Test(int i) { return i; } ...and another Testbis function, defined in the header. Testbis works, Test gives a 2028 error. I have compared the .obj of my project and the .lib created, and for the lib there is: save_nodes@tetgenio@@QAEXPAD@Z But in the .obj it is: save_nodes@tetgenio@@$$FQAEXPBD@Z in the .obj It appears they are not the same. Everything is compiled with /clr. I've tried creating both a .lib and a .dll, with same results either way.
That was because of a linker problem linking to different folders containing the same files.
3,134,821
3,134,958
Local time with milliseconds
how can I get current time with library boost. I can do this: ptime now = boost::posix_timesecond_clock::local_time(); tm d_tm = to_tm(now); But the last time unit of tm structure is second and I need in millisecond. Can I get current time with milliseconds?
look at boost::posix_time::microsec_clock::local_time() #include <boost/date_time/posix_time/posix_time_types.hpp> #include <iostream> int main() { boost::posix_time::ptime time = boost::posix_time::microsec_clock::local_time(); boost::posix_time::time_duration duration( time.time_of_day() ); std::cout << duration.total_milliseconds() << std::endl; return 0; }
3,134,831
3,134,855
In C++, is it still bad practice to return a vector from a function?
Short version: It's common to return large objects—such as vectors/arrays—in many programming languages. Is this style now acceptable in C++0x if the class has a move constructor, or do C++ programmers consider it weird/ugly/abomination? Long version: In C++0x is this still considered bad form? std::vector<std::string> BuildLargeVector(); ... std::vector<std::string> v = BuildLargeVector(); The traditional version would look like this: void BuildLargeVector(std::vector<std::string>& result); ... std::vector<std::string> v; BuildLargeVector(v); In the newer version, the value returned from BuildLargeVector is an rvalue, so v would be constructed using the move constructor of std::vector, assuming (N)RVO doesn't take place. Even prior to C++0x the first form would often be "efficient" because of (N)RVO. However, (N)RVO is at the discretion of the compiler. Now that we have rvalue references it is guaranteed that no deep copy will take place. Edit: Question is really not about optimization. Both forms shown have near-identical performance in real-world programs. Whereas, in the past, the first form could have had order-of-magnitude worse performance. As a result the first form was a major code smell in C++ programming for a long time. Not anymore, I hope?
Dave Abrahams has a pretty comprehensive analysis of the speed of passing/returning values. Short answer, if you need to return a value then return a value. Don't use output references because the compiler does it anyway. Of course there are caveats, so you should read that article.
3,135,160
3,135,391
Ways to Find a Race Condition
I have a bit of code with a race condition in it... I know that it is a race condition because it does not happen consistently, and it seems to happen more often on dual core machines. It never happens when I'm tracing. Although, there is a possibility that it could be a deadlock as well. By analyzing stages of completion of logs where this does and does not occur, I've been able to pinpoint this bug to a single function. However, I do not know where in the scope of the function this is happening. It's not at the top level. Adding log statements or breakpoints is going to change the timing if it is a race condition, and prevent this from happening. Is there any technique that I can use aside from getting a race condition analyzer that will allow me to pinpoint where this is happening? This is in visual studio 9, with C++ (of the nonmanaged variety).
Put sleeps in various parts of your code. Something that is threadsafe will be threadsafe even if it (or asynchronous code) sleeps for even seconds.
3,135,261
3,135,358
Difference between two vector<MyType*> A and B
I've got two vector<MyType*> objects called A and B. The MyType class has a field ID and I want to get the MyType* which are in A but not in B. I'm working on a image analysis application and I was hoping to find a fast/optimized solution.
The unordered approach will typically have quadratic complexity unless the data is sorted beforehand (by your ID field), in which case it would be linear and would not require repeated searches through B. struct CompareId { bool operator()(const MyType* a, const MyType* b) const { return a>ID < b->ID; } }; ... sort(A.begin(), A.end(), CompareId() ); sort(B.begin(), B.end(), CompareId() ); vector<MyType*> C; set_difference(A.begin(), A.end(), B.begin(), B.end(), back_inserter(C) ); Another solution is to use an ordered container like std::set with CompareId used for the StrictWeakOrdering template argument. I think this would be better if you need to apply a lot of set operations. That has its own overhead (being a tree) but if you really find that to be an efficiency problem, you could implement a fast memory allocator to insert and remove elements super fast (note: only do this if you profile and determine this to be a bottleneck). Warning: getting into somewhat complicated territory. There is another solution you can consider which could be very fast if applicable and you never have to worry about sorting data. Basically, make any group of MyType objects which share the same ID store a shared counter (ex: pointer to unsigned int). This will require creating a map of IDs to counters and require fetching the counter from the map each time a MyType object is created based on its ID. Since you have MyType objects with duplicate IDs, you shouldn't have to insert to the map as often as you create MyType objects (most can probably just fetch an existing counter). In addition to this, have a global 'traversal' counter which gets incremented whenever it's fetched. static unsigned int counter = 0; unsigned int traversal_counter() { // make this atomic for multithreaded applications and // needs to be modified to set all existing ID-associated // counters to 0 on overflow (see below) return ++counter; } Now let's go back to where you have A and B vectors storing MyType*. To fetch the elements in A that are not in B, we first call traversal_counter(). Assuming it's the first time we call it, that will give us a traversal value of 1. Now iterate through every MyType* object in B and set the shared counter for each object from 0 to the traversal value, 1. Now iterate through every MyType* object in A. The ones that have a counter value which doesn't match the current traversal value(1) are the elements in A that are not contained in B. What happens when you overflow the traversal counter? In this case, we iterate through all the counters stored in the ID map and set them back to zero along with the traversal counter itself. This will only need to occur once in about 4 billion traversals if it's a 32-bit unsigned int. This is about the fastest solution you can apply to your given problem. It can do any set operation in linear complexity on unsorted data (and always, not just in best-case scenarios like a hash table), but it does introduce some complexity so only consider it if you really need it.
3,135,296
3,135,628
Call C/C++ code form a fortran program in visual studio? (How to compile mixed C and fortran code in visual studio)
i am looking for a way, how i can integrate a c++ code with fortran code (i want simply call some C/C++ functions in the fortran code). I have found some proposals for gcc or console compilers, but i have not any idea how to translate this approach to solve integrationproblem within the visual studio. At the time I am thinking about creating a dll form c++ code and calling it from Fortran code. Has someone already seen a solution? Or what is about overhead for calling function from dll? My fortran code transfers a lot of memory into C function, is there any problems, if i would solve this problem with dll? thx. PS I am using Visual Studio 2008 Prof and Intel compilers 10 PPS I think, i have to specify more concrete, what i want: i want to compile a fortran project in visual studio, which uses some C functions.
There is a new way to do this that has many advantages -- use the Fortran 2003 ISO C Binding. This is a standard and therefore largely OS and language independent way of interfacing Fortran and C (and any language that will use C calling conventions). Intel Fortran 11 supports along with numerous other compilers -- not sure about version 10. Using the ISO C Binding, you can match any C name (any case), don't have to worry about underscores (and variations between compilers) and can specify the types and calling methods (by reference, by value) for the arguments. Intel provides some examples in a folder with their compiler; there are also examples in the gfortran manual and a discussion of additional considerations for Windows. There are previous questions & answers here and on the Intel Fortran forum.
3,135,738
3,135,818
How is a pipe reading with a size of 4 bytes into a 4 byte int returning more data?
Reading from a pipe: unsigned int sample_in = 0; //4 bytes - 32bits, right? unsigned int len = sizeof(sample_in); // = 4 in debugger while (len > 0) { if (0 == ReadFile(hRead, &sample_in, sizeof(sample_in), &bytesRead, 0)) { printf("ReadFile failed\n"); } len-= bytesRead; //bytesRead always = 4, so far } In the debugger, first iteration through: sample_in = 536739282 //36 bits? How is this possible if sample in is an unsigned int? I think I'm missing something very basic, go easy on me! Thanks
Judging from your comment that says //36 bits? I suspect that you're expecting the data to be sent in a BCD-style format: In other words, where each digit is a number that takes up four bits, or two digits per byte. This way would result in wasted space however, you would use four bits, but values "10" to "15" aren't used. In fact integers are represented in binary internally, thus allowing a 32-bit number to represent up to 2^32 different values. This comes out to 4,294,967,295 (unsigned) which happens to be rather larger than the number you saw in sample_in.
3,135,795
3,136,016
Why does this template class in a library generate linker errors when used?
I've got the following setup. RectangleT class defined in a header file in a library. Attempted to use the class in my main application. When linking I get an error for every function I try to call - except constructor and the GetLeft/GetTop/GetRight/GetBottom - BUT - I do get the error when calling GetWidth / GetHeight. Here's the code I've got for a simple template class. namespace My2D { template <typename T> class MY2D_API RectangleT { public: // Construction RectangleT(const T left = 0, const T top = 0, const T right = 0, const T bottom = 0) : m_left(left) , m_top(top) , m_right(right) , m_bottom(bottom) { } RectangleT(const RectangleT<T> &source) : m_left(source.m_left) , m_top(source.m_top) , m_right(source.m_right) , m_bottom(source.m_bottom) { } virtual ~RectangleT(void) { } public: // Getters / setters T GetLeft() const { return m_left; } T GetTop() const { return m_top; } T GetRight() const { return m_right; } T GetBottom() const { return m_bottom; } T GetWidth() const { return m_right - m_left; } T GetHeight() const { return m_bottom - m_top; } void SetLeft(const T value) { m_left = value; } void SetTop(const T value) { m_top = value; } void SetRight(const T value) { m_right = value; } void SetBottom(const T value) { m_bottom = value; } protected: // Members T m_left; T m_top; T m_right; T m_bottom; }; } Anyone got any ideas?!
I removed compiler directive MY2D_API and tried your code, it works fine, see below. Windows 7, MS VS 2010 int main () { My2D::RectangleT < int > rect; rect.SetBottom(3); rect.SetLeft(3); rect.SetRight(8); rect.SetTop(8); return rect.GetHeight(); }
3,135,947
3,135,998
Access own bank account via self-written application
I have used MS Money for several years now and due to my "coding interest" it would be great to know where to start learning the basics for programming such an application. Better to say: Its not about how to design and write an application, its about the "bank details". (Just displaying the amount of a certain bank account for the beginning would be a pleasant aim for me.). I would like to do it in C++ or Java, since I'm used to these languages. Will it be "too big" for a hobby project? I do not know much about all the security issues, the bank server interfaces/technique, etc. At the first place after a "no" I need a reliable source for learning.
Most of the apps I've worked with read in a file exported from the bank's website, which is relatively straight forward. If that's the road you're looking to go down you'll need to write code to: Login to the bank's website to download the file via HTTPS Either get specs for the file format or reverse engineer it Apply whatever business rules you choose to the resulting data
3,136,038
3,136,215
Select() + UDP resulting in too many open files
I currently have a select() statement configured to keep track of two UDP sockers. I send perhaps 10 - 20 messages a second at one general data socket, which is this interpreted as I expected. However, once I hit around 1024 messages, I get the notice: talker: socket: Too many open files talker: failed to bind socket This is logical to me, since ulimit -n shows a max of 1024 open files for this user. However, why are there all of these open files? With UDP, there is no connection made, so I do not believe I need to be closing a socket each time (although perhaps I'm wrong). Any ideas? Thanks in advance.
I think in this case "Too many open files" really means you've hit the file descriptor limit; network sockets count towards this limit. Are you sure that there's nothing else - say in routehelper - that's creating further sockets? What platform are you running on? If Linux, lsof or grobbling around in /proc/<pid>/fd - while it's running, before it hits the limit - might illustrate where all the fds are going. Tip: Don't rely on socket_udp_inboundALL being numerically larger than socket_udp_inboundRC - it's better to explicitly compare their values at least once.
3,136,044
3,136,076
pwsz string confusion
I have never posted before so I am sorry if I am not clear. I am trying to use a third party DLL written in c++ on 2005 and all I have is some very poor documentation. I am dynamically linking to the DLL and using the Ordinal value read from Dependency walker to get a pointer to a method in the DLL. Such as (LPFNDDLLZC) GetProcAddress(hHILCdll, (LPCSTR)15); My code is written in C++ compiled in Microsoft VS 6.0, I can not turn on the UNICODE defines or I will break existing code. The documentation for the DLL says all string arguments are pwsz which I believe means pointer to a wide char string null terminated. I have tried passing in a pointer to an unsigned short, BSTR and various other things and the DLL crashes on the string. I am totally lost as to why, I believe it has to do with my pwsz string construction and I'm lost as to how to fix this. I have read so may articles related but nothing works. Can anyone help? I can post code if need be. Thanks.
You could use MultiByteToWideChar to turn your LPSTR into an LPWSTR which should solve your problem.
3,136,054
4,292,423
Need help with configuration of codeblocks for Qt !
codeblocks 8.02. , win xp SP2 , Qt 4.6 After installing Qt SDK, I installed QtWorkbench (codeblocks plugin that allows you to create Qt applications.) http://code.google.com/p/qtworkbench/. I worked under instructions from that page. I opened the folder "dialogs" and in it I opened a new empty codeblocks project. Also in this folder "dialogs" I opened a new directory "complexwizard". In complexwizard is simple main.cpp : #include <QWidget> #include <QApplication> #include <QPushButton> #include <QLabel> #include <QDesktopWidget> class Communicate : public QWidget { Q_OBJECT public: Communicate(QWidget *parent = 0); private slots: void OnPlus(); void OnMinus(); private: QLabel *label; }; void center(QWidget *widget, int w, int h) { int x, y; int screenWidth; int screenHeight; QDesktopWidget *desktop = QApplication::desktop(); screenWidth = desktop->width(); screenHeight = desktop->height(); x = (screenWidth - w) / 2; y = (screenHeight - h) / 2; widget->move( x, y ); } Communicate::Communicate(QWidget *parent) : QWidget(parent) { int WIDTH = 350; int HEIGHT = 190; resize(WIDTH, HEIGHT); QPushButton *plus = new QPushButton("+", this); plus->setGeometry(50, 40, 75, 30); QPushButton *minus = new QPushButton("-", this); minus->setGeometry(50, 100, 75, 30); label = new QLabel("0", this); label->setGeometry(190, 80, 20, 30); connect(plus, SIGNAL(clicked()), this, SLOT(OnPlus())); connect(minus, SIGNAL(clicked()), this, SLOT(OnMinus())); center(this, WIDTH, HEIGHT); } void Communicate::OnPlus() { int val = label->text().toInt(); val++; label->setText(QString::number(val)); } void Communicate::OnMinus() { int val = label->text().toInt(); val--; label->setText(QString::number(val)); } int main(int argc, char *argv[]) { QApplication app(argc, argv); Communicate window; window.setWindowTitle("Communicate"); window.show(); return app.exec(); } Then I added, "main.cpp" in a blank project and all configured according to the instructions from that page. When I started to compile the program, compiler always says: * It seems that this project has not been built yet. Do you want to buid it now? * I press yes an got this message : Process terminated with status 2 (0 minutes, 0 seconds) 0 errors, 0 warnings In the folder "dialogs" where is a project, new files are created: complexwizard.pro Makefile.complexwizard Makefile.complexwizard.Debug Makefile.complexwizard.Release Since I am relatively new to the world of programming, compiler and other things, this does not tell me much. Therefore, I ask someone who has some suggestion on the basis of these symptoms to help me remove it from standstill. If you're interested, I'll add more data that will need
I 'm the author of QtWorkbench and I have stopped supporting it some time ago. I 'm pretty sure it's outdated by now. I really think that new Qt users should go with QtCreator the "official" Qt IDE to get the best support out of the box. QtWorkbench is still in Google Code in case any one wants to pick up developing it.
3,136,055
3,136,166
wxWidgets: wxString::wxString(int) private within this context
I have a subclass of wxHtmlListBox called TestClass, but I get the error: /usr/include/wx-2.8/wx/string.h:682:0 /usr/include/wx-2.8/wx/string.h:682: error: 'wxString::wxString(int)' is private MainFrame.cpp:106:0 MainFrame.cpp:106: error: within this context MainFrame.cpp line 106 is this: TestClass *tc = new TestClass(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, NULL, wxBORDER_DEFAULT); The files for TestClass can be found at http://cl.ly/1VSo Any thoughts on this?
You're passing wxBORDER_DEFAULT into a const wxString reference: TestClass( wxWindow* parent, // this wxWindowID id = wxID_ANY, // wxID_ANY const wxPoint& pos = wxDefaultPosition, // wxDefaultPosition const wxSize& size = wxDefaultSize, // wxDefaultSize long style = 0, // NULL const wxString& name = wxHtmlListBoxNameStr ); // wxBORDER_DEFAULT ...but wxBORDER_DEFAULT is part of an enum (essentially an integer): enum wxBorder { /* this is different from wxBORDER_NONE as by default the controls do have */ /* border */ wxBORDER_DEFAULT = 0, wxBORDER_NONE = 0x00200000, wxBORDER_STATIC = 0x01000000, wxBORDER_SIMPLE = 0x02000000, wxBORDER_RAISED = 0x04000000, wxBORDER_SUNKEN = 0x08000000, wxBORDER_DOUBLE = 0x10000000, /* deprecated */ wxBORDER_THEME = 0x10000000, /* a mask to extract border style from the combination of flags */ wxBORDER_MASK = 0x1f200000 }; So it's using the constructor you mentioned for a wxString: wxString::wxString(int) ...which is private and hence you're getting an error. Try passing in a string or NULL instead :-)
3,136,105
3,136,164
Best way to do alpha blending with OpenGL?
I'm drawing 2D Polygons, actually I'm drawing lots of triangles and using GLUOrtho2D. I noticed that by zooming out I got much better frame rates. I realized I was maxing out the graphics card's fill rate, not drawing too many polygons as I had initially suspected. I think this is because I'm drawing lots of overlapping polygons and using glEnable(GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); Is this the blend function I should be using? How could I minimize the filling given the nature of what I'm doing? I tried enabling the GL_DEPTH_TEST and Z ordered my polygons, but since I alpha blend, this won't help. What is the most efficient way of doing this sort of thing? Thanks
I doubt using a different blend function would help. One generally chooses the correct blend function based on desired output, not performance. Are all the polygons you render transparent/translucent? If not, it might help to separate the rendering of those apart from the opaque polygons you have and set the proper GL states accordingly. Also are these textured polygons? You might be able to optimize your texture handling (ex: reduce context switches, use more efficient image formats, etc). Finally, how are you rendering these triangles? If in immediate mode or using vertex arrays, consider using VBOs.
3,136,267
3,136,285
Set individual bit in C++
I have a 5 byte data element and I need some help in figuring out how in C++ to set an individual bit of one of these byte; Please see my sample code below: char m_TxBuf[4]; I would like to set bit 2 to high of byte m_TxBuf[1]. 00000 0 00 ^ This one Any support is greatly appreciated; Thanks!
Bitwise operators in C++. "...set bit 2..." Bit endianness. I would like to set bit 2 to high of byte m_TxBuf[1]; m_TxBuf[1] |= 1 << 2
3,136,520
3,136,537
Determine if map contains a value for a key?
What is the best way to determine if a STL map contains a value for a given key? #include <map> using namespace std; struct Bar { int i; }; int main() { map<int, Bar> m; Bar b = {0}; Bar b1 = {1}; m[0] = b; m[1] = b1; //Bar b2 = m[2]; map<int, Bar>::iterator iter = m.find(2); Bar b3 = iter->second; } Examining this in a debugger, it looks like iter is just garbage data. If I uncomment out this line: Bar b2 = m[2] The debugger shows that b2 is {i = 0}. (I'm guessing it means that using an undefined index will return a struct with all empty/uninitialized values?) Neither of these methods is so great. What I'd really like is an interface like this: bool getValue(int key, Bar& out) { if (map contains value for key) { out = map[key]; return true; } return false; } Does something along these lines exist?
Does something along these lines exist? No. With the stl map class, you use ::find() to search the map, and compare the returned iterator to std::map::end() so map<int,Bar>::iterator it = m.find('2'); Bar b3; if(it != m.end()) { //element found; b3 = it->second; } Obviously you can write your own getValue() routine if you want (also in C++, there is no reason to use out), but I would suspect that once you get the hang of using std::map::find() you won't want to waste your time. Also your code is slightly wrong: m.find('2'); will search the map for a keyvalue that is '2'. IIRC the C++ compiler will implicitly convert '2' to an int, which results in the numeric value for the ASCII code for '2' which is not what you want. Since your keytype in this example is int you want to search like this: m.find(2);
3,136,594
3,136,618
Naming convention - underscore in C++ and C# variables
It's common to see a _var variable name in a class field. What does the underscore mean? Is there a reference for all these special naming conventions?
The underscore is simply a convention; nothing more. As such, its use is always somewhat different to each person. Here's how I understand them for the two languages in question: In C++, an underscore usually indicates a private member variable. In C#, I usually see it used only when defining the underlying private member variable for a public property. Other private member variables would not have an underscore. This usage has largely gone to the wayside with the advent of automatic properties though. Before: private string _name; public string Name { get { return this._name; } set { this._name = value; } } After: public string Name { get; set; }
3,136,616
3,136,629
multiple definition linker error after adding a function to a previously linking file
So my program is working fine. Compiling, linking, running, the works. Then, I decide to add a simple function to one of my files, like this: #ifndef UTILITY_HPP #define UTILITY_HPP /* #includes here. There's no circular include, I've checked. */ namespace yarl { namespace utility { (several function declarations and definitions) bool isVowel(const char c) { if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') return true; else return false; } } } #endif That function definition is the only change I've made to my code. Everything else is exactly the same as it was. Nothing calls it yet. I compile, and it fails to link, with g++ giving one of these errors for every file that #includes this one: ./obj/Feature.o: In function `yarl::utility::isVowel(char)': /home/max/Desktop/Development/Yarl Backup/yarl v0.27/src/Utility.hpp:130: multiple definition of `yarl::utility::isVowel(char)' ./obj/Events.o:/home/max/Desktop/Development/Yarl Backup/yarl v0.27/src /Utility.hpp:130: first defined here ./obj/GameData.o: In function `yarl::utility::isVowel(char)': If I comment out isVowel, it works again. I've tried renaming it, still doesn't work. I've tried replacing it with just void randomFunctionName() {}, still doesn't work. I've tried making it non-inline and putting the function body in Utility.cpp, still doesn't work. I am extremely confused. Why would adding one simple function screw up the linker?
Either declare the function inline, or define it in a separate .cpp file. Otherwise every C++ file in which you include the header is trying to make its own, publicly-available definition of the function. Edit: and fwiw, you don't need to explicitly return true or false if you're testing a conditional. Just return the conditional itself: inline bool isVowel(const char c) { return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); }
3,136,625
3,136,707
I can't make this dijkstra code compile. (The Algorithm Design Manual)
This Code is a code I built from the algorithm design manual book but I can't make it compile cause I've got little experience with pointers I think that's the main reason I think I can't compile it: And if someone can change a little bit in the djikstra to make it through heap with the current configuration. #include<iostream> #include<stdio.h> #include<stdlib.h> using namespace std; const int MAXV=1000; const int MAXINT=99999; typedef struct{ int y; int weight; struct edgenode *next; }edgenode; typedef struct{ edgenode *edges[MAXV+1]; int degree[MAXV+1]; int nvertices; int nedges; bool directed; }graph; void add_edge(graph *g,int x,int y,int weight,bool directed); void read_graph(graph *g,bool directed){ int x,y,weight,m; g->nvertices=0; g->nedges=0; g->directed=directed; for(int i=1;i<MAXV;++i) g->degree[i]=0; for(int i=1;i<MAXV;++i) g->edges[i]=NULL; scanf("%d %d",&(g->nvertices),&m); for(int i=1;i<=m;++i){ scanf("%d %d %d",&x,&y,&weight); add_edge(g,x,y,weight,directed); } } void add_edge(graph *g,int x,int y,int weight,bool directed){ edgenode *p; p=malloc(sizeof(edgenode)); p->weight=weight; p->y=y; p->next=g->edges[x]; g->edges[x]=p; g->degree[x]++; if(directed==false) add_edge(g,y,x,weight,true); else g->nedges++; } int dijkstra(graph *g,int start,int end){ edgenode *p; bool intree[MAXV+1]; int distance[MAXV+1]; for(int i=1;i<=g->nvertices;++i){ intree[i]=false; distance[i]=MAXINT; } distance[start]=0; int v=start; while(intree[v]==false){ intree[v]=true; p=g->edges[v]; while(p!=NULL){ int cand=p->y; int weight=p->weight; if(distance[cand] > distance[v]+weight) distance[cand]=distance[v]+weight; p=p->next; } v=1; int dist=MAXINT; for(int i=1;i<=g->nvertices;++i) if((intree[i]==false) && (dist > distance[i])){ dist=distance[i]; v=i; } } return distance[end]; } int main(){ graph g; read_graph(&g,false); int x=1,y,shortest; while(x!=0){ scanf("%d %d",&x,&y); shortest=dijkstra(&g,x,y); printf("The shortest path from %d to %d is %d",x,y,shortest); } return 0; }
Change the definition of the struct, and it would compile. struct edgenode_tag { int y; int weight; struct edgenode_tag *next; }; typedef edgenode_tag edgenode; While this will solve your problem, don't trust my answer below until someone better than me comments on it. What was wrong in your code ? You are using the typedef-ed type before the compiler knows about that type. Instead, you need to use the structure_tag to define the member pointer of type itself. typedef struct { ... my_struct* pS; ... } my_struct; // at this point compiler will know about *my_struct* type // Hence, you can not use that name until after this line. // To define the member pointer of type itself you need to // to use the struct_tag, as I did in your example. // where, struct_tag is *edgenode_tag* EDIT: Also, malloc returns *void**, which you need to cast to the type you are assigning it to. So, inside function add_edges, make this correction (please read more about this in book, it is important to understand this): p = (edgenode*)malloc(sizeof(edgenode));
3,136,651
3,136,675
Is there a standard C++ class that is like QByteArray?
Is there a STL C++ class that works like QByteArray?
std::string or std::vector<unsigned char>
3,136,765
3,136,813
How many gumballs in the jar. 2 errors
Trying to code a guess how many gumballs in the gumballs jar, kinda thing. There are two problems I keep getting: It's supposed to say if the guess is to high or to low but that only happens when i enter a number over 1000 and it says: Enter your guess: 1001 Too High! Too Low! Enter your guess: If you type a letter or phrase it goes haywire saying: Enter your guess: Too High! Too Low! but it keeps saying that at about a couple hundred maybe even a thousand times a minute -.- #include<iostream> #include<ctime> using namespace std; int main(void) { int iGumballs; int iUserguess; int iGuesses = 0; while(true) { system("CLS"); cin.clear(); iGuesses = 0; srand(static_cast<unsigned int>(time(0))); iGumballs = rand()%1000+1; cout << "How many gumballs are in the gumball jar, you guess!" << endl; do { cout << "Enter your guess: "; cin>> iUserguess; if(iUserguess > iGumballs) { cout << "Too High!" << endl << endl; } if(iUserguess > iGumballs) { cout << "Too Low!" << endl << endl; } iGuesses ++; }while(iUserguess > iGumballs || iUserguess < iGumballs); cout << "You guessed the right amount of gumballs! High Five!" << endl << endl; cout << "You took" << iGuesses << " guesses" << endl << endl; system("PAUSE"); } return 0; }
Let me hint at one problem. Let's take a look at the two checks you have for printing the message "too high" and "too low": if(iUserguess > iGumballs) if(iUserguess > iGumballs) Notice anything wrong when I put them together?
3,136,790
3,137,072
Using boost::mpl::lambda to remove types from a boost::mpl::list based on static const member variable
I have a list of types defined as: typedef boost::mpl::list<Apple, Pear, Brick> OriginalList; I would like to create a second list that does not contain any fruit, i.e. the resultant list formed from the first list would contain a single type Brick. Fruit is identified through a static const variable defined within the types, e.g.: struct Apple { static const bool IsFruit = true; }; I currently have a solution that involves creating a meta-function class, and using boost::mpl::remove_if. I believe I should be able to make this more elegant by using boost::mpl::lambda to remove the need for the separate RemoveFruit struct. Any suggestions on how to do this? Full code as it currently stands: include <boost/static_assert.hpp> #include <boost/mpl/list.hpp> #include <boost/mpl/remove_if.hpp> #include <boost/mpl/size.hpp> #include <iostream> struct Apple { static const bool IsFruit = true; }; struct Pear { static const bool IsFruit = true; }; struct Brick { static const bool IsFruit = false; }; typedef boost::mpl::list<Apple, Pear, Brick> OriginalList; BOOST_STATIC_ASSERT(boost::mpl::size<OriginalList>::type::value == 3); // This is what I would like to get rid of: struct RemoveFruit { template <typename T> struct apply { typedef boost::mpl::bool_<T::IsFruit> type; }; }; // Assuming I can embed some predicate directly in here? typedef boost::mpl::remove_if< OriginalList, RemoveFruit >::type NoFruitList; BOOST_STATIC_ASSERT(boost::mpl::size<NoFruitList>::type::value == 1); int main() { std::cout << "There are " << boost::mpl::size<OriginalList>::type::value << " items in the original list\n"; std::cout << "There are " << boost::mpl::size<NoFruitList>::type::value << " items in the no fruit list\n"; return 0; }
I think the best you can do is to define an IsFruit struct like template <typename T> struct isFruit : boost::mpl::bool_<T::IsFruit> {}; And then you can define your no-fruit list as typedef boost::mpl::remove_if< OriginalList, boost::mpl::lambda< isFruit< boost::mpl::_1 > >::type >::type NoFruitList; The additional struct is needed to get access to the IsFruit field in your classes. Note that if you want to get rid of the additional struct entirely, you'll have to rename the boolean members of your other classes. If you follow the boost::mpl convention and call them value instead of IsFruit, you can define NoFruitList as typedef boost::mpl::remove_if< OriginalList, boost::mpl::lambda<boost::mpl::_1>::type >::type NoFruitList;
3,136,919
3,137,174
C++ state design pattern with multiple state machines
I have a C++ state machine implemented using the State design pattern. Each state is implemented as a nested friend class of the context class. class Context { public: /* The Context class' user calls process1() to get it to perform an action */ void process1(); private: class IState; void switchState( IState *newState ); class IState { virtual void doProcess( Context &context ) = 0; }; class StateA : public Context::IState { void doProcess( Context &context ); }; friend class StateA; class StateB : public Context::IState { void doProcess( Context &context ); }; friend class StateB; . . . class StateJ : public Context::IState { void doProcess( Context &context ); }; friend class StateJ; }; Currently, a successful iteration of the state machine runs from Context::StateA to Context::StateJ when Context::process1() is called but some of the states contain internal logic to determine whether to loop back to an earlier state. So a typical execution will look like: StateA StateB StateC StateD StateE StateC StateD StateE StateF StateG StateH StateI StateJ The internal logic to determine next state is currently being implemented by the respective state itself by storing data in the context object. What I need to do now is add a Context::process2() option that significantly differs in the order of execution of states. Of course, this can be done using flags that are set in the context object but I was wondering if there is better way to implement this; maybe even use this method to rewrite the handling of state switches within Context::process2(). The Visitor design pattern might do the trick but I'm not sure whether its intended for implementing state machines. When using Visitor, process1() could contain all logic for the order of execution of states and then just call each state in that order. Similarly, process2() would handle all of its own logic. EDIT: To those of you that replied saying I should be creating a separate state machine, the reason I'm looking to avoid that is because the code for the states used by the second state machine is identical to those in the first; only the progression is different. The second state machine will go through the following state transitions: StateA StateB StateC StateJ So I'm trying to eliminate duplicated code.
I assume that in your code, switchState is invoked by the individual states when it's time to transition to something else. Something like this: void StateA::doProcess(Context& context) { context.switchState(new StateB()); // NOTE: potential leak! } Is this the case? If so, one thing you might consider is having the states return transition objects that abstractly represent a control point in your state graph. You then have the Context run a loop which executes the states, retrieves the resulting transitions, and maps the transitions to the appropriate next states for whatever process you have. The transition map can be set up differently for each process method that you have. Pros: States don't have to know about each other. The transition is their declaration to the world of what they've done. It's up to the context to route between the states in appropriate ways. This could make the states reusable across different Context objects, for example. Allows the idea of "same structure, slightly different behavior" by allowing the context to essentially maintain the same state graph, but plug in a slightly different state with a compatible transition interface as the target of a particular transition. Cons: Adds an extra layer of stuff to set up. Transition mapping code is mostly boilerplate. Tools to generate the boilerplate may help. Doesn't help you if you really want to do something radically different in the two processes which the states don't have the right transitions to support – but then, you're trying to reuse at the wrong level – you probably want different state objects at that point. EDIT: Sample code is up at http://pastebin.com/eBauP060 .