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
5,216,399
5,216,501
/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found
How can I get GLIBCXX_3.4.15 in Ubuntu? I can't run some programs that I'm compiling. When I do: strings /usr/lib/libstdc++.so.6 | grep GLIBC I get: GLIBCXX_3.4 GLIBCXX_3.4.1 GLIBCXX_3.4.2 GLIBCXX_3.4.3 GLIBCXX_3.4.4 GLIBCXX_3.4.5 GLIBCXX_3.4.6 GLIBCXX_3.4.7 GLIBCXX_3.4.8 GLIBCXX_3.4.9 GLIBCXX_3.4.10 GLIBCXX_3.4.11 GL...
I'm compiling gcc 4.6 from source, and apparently sudo make install didn't catch this one. I dug around and found gcc/trunk/x86_64-unknown-linux-gnu/libstdc++-v3/src/.libs/libstdc++.so.6.0.15 I copied it in to /usr/lib and redirected libstdc++.so.6 to point to the new one, and now everything works.
5,216,616
5,225,889
How to set group (like that for GtkRadioButton) for GtkToggleButton in GTK+?
How to set group (like that for GtkRadioButton) for GtkToggleButton in GTK+ ? What is the properties i can use for this aim. I want to check buttons, which set the drawing primitive (rectangle, ellipse, etc)
If I understand your question correctly, you want to have a group of buttons where only one can be turned on at a time, but looking like regular buttons instead of radio buttons. Use radio buttons, and add them to a group as usual, but set the draw-indicator property to FALSE. They will be drawn like regular buttons.
5,216,976
5,217,251
library for sorting vector of string
I have some data stored in vector ; vector<string> data ; I want to sort strings in data, alphabetically.Are there any sorting algorithm or complex library which you can recommend me? Ex ; assume in data ; aaaa ccc bbb acb after sorting, data ; ...
Since you are aiming for efficiency even before starting to write a program, do it other way around : first write a correct program, then profile it and optimize bottlenecks. Therefore, I can only recommend what other already did : std::sort
5,217,490
5,217,919
Passing event from QGraphicsScene to QGraphicsItem in C++ with Qt
I have a base class extending QGraphicsScene... class BaseScene : public QGraphicsScene in that class is the protected event... void BaseScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent) There are some user clicks where I need to pass the event on to the QGraphicsItem inside the QGraphicsScene, as the QGra...
In your reimplemented mousePressEvent() add: QGraphicsScene::mousePressEvent(mouseEvent); This will call the default implementation : "The default implementation depends on the state of the scene. If there is a mouse grabber item, then the event is sent to the mouse grabber. Otherwise, it is forwarded to the topmost i...
5,217,782
5,217,800
Array of sse type: Segmentation Fault
today I tried to initialize an array of the sse type __m128d. Unfortunately it didn't work - why? Is it generally impossible to create arrays of sse types (since they are register types?). The following code segfaults at the assignment in the loop. __m128d* _buffers = new __m128d[32]; for(int i=0;i<32;i++) _buffers...
You must use _mm_malloc() or _aligned_malloc(), depending on what's the preferred function name on your compiler. __m128[di] in combination with new is almost always bad mojo.
5,217,811
5,217,958
How can I avoid a warning about division-by-zero in this template code?
I have a class for fixed-point arithmetic, of which this is the salient portion: template <typename I, I S> struct fixed { I value; fixed(I i) : value(i * S) {} template <typename J, J T> fixed(const fixed<J, T> &fx) { if (S % T == 0) value = fx.value * (S / T); else if (T ...
something like? template<int,int> struct helper { static int apply(...) { return S * fx.value / T; } }; template<int n> struct helper<0,n> { // need 0,0 as well to avoid ambiguity static int apply(...) { return fx.value * (S / T); } }; template<int m> struct helper<m,0> { static int apply(...) { return fx...
5,217,878
5,223,655
How to Register Sink Object for SENS Events
I'm looking at MSDN documentation that says I can CoCreateInstance a SENS object using its CLSID. However, it is not clear if __uuidof(SENS) means anything - since it is just a forward declaration in the Sensevts.h file. Furthermore, the SENS class only offers "outgoing" interfaces, and is labeled "noncreateable" (a...
According to other parts of MSDN, you don't create a SENS object. If I'm reading this right, you create an instance of IEventSystem (CLSID_CEventSystem), query it for the SENS publisher / event classes of interest, and register your subscription with them. Edit: For your new problem, I'm unsure of the root cause, howe...
5,217,891
5,217,961
Moving a function in a running thread to a new thread?
I have a read and write function in a class file. this class subclasses QThread class and overrides run, does not have signals and slots ,It basically runs data processing functions in a thread. in its constructor is the method movetothread(this). To have the two functions to form a queue and implement muli-threading ,...
It doesn't work that way. QObject::moveToThread associates the object with another thread, not the calling function. Furthermore, this affects future event processing only.
5,217,996
5,218,710
Too many Post were made to semaphore
Hi have developped an sample code to implement.Multiple producer and single consumer problem. I have taken a Queue and I have restricted the size of the to 20.So I am using semaphore and CrticalSection (windows api)to protect it.If more than 20 thread the queue it wont be allowed.that semaphore should protect it. I h...
Change WaitForSingleObject(handles,INFINITE) to WaitForSingleObject(handles[SemaphoreIndex],INFINITE). Change switch(WAIT_OBJECT_0) to switch(dwWaitResult) and add error handling to this switch. case StopperIndex: should be case StopperIndex + WAIT_OBJECT_0:, apply same change to case SemaphoreIndex: Turn you compilers...
5,218,017
5,218,053
C++ function object to return `p->first` and `p->second`
Is there a builtin function object that returns p->first and p->second, so that I can happily write transform(m.begin(),m.end(),back_inserter(keys),get_first); transform(m.begin(),m.end(),back_inserter(vals),get_second); STL-based solution is the best, boost solution is second best. Yeah, I know boost::lambda, I don't...
There are nonstandard extensions to g++ and SGI called select1st and select2nd. So there's probably nothing in the STL for that. Boost's bind can also do that, give it a pointer to the correct member function boost::bind(&std::map<string,string>::value_type::second,_1)
5,218,306
5,218,334
Load function at runtime in C++
I have following problem: My program should decide at runtime to load an function (in this case GetExtendedTcpTable()) or not, because the method is not available in Windows 2000!? (can't start the software only in Windows 2000) Thank you for your help! greets leon22
You didn't quite specify your question, but I suppose that you want to load the function dynamically based on the OS version. To determine the OS version, you can use GetVersionEx. To load a function dynamically, first use LoadLibrary to retrieve the module handle of its DLL, and then use GetProcAddress to retrieve a f...
5,218,708
5,219,110
Static global variable used by inline member function
When you have a static global variable in a C++ header file, each translation unit that includes the header file ends up with its own copy of the variable. However, if I declare a class in that same header file, and create a member function of that class, implemented inline within the class declaration, that uses the s...
The standard says (3.2/5): There can be more than one definition of a class type (clause 9), ... provided the definitions satisfy the following requirements ... in each definition of D, corresponding names, looked up according to 3.4, shall refer to an entity defined within the definition of D, or shall ...
5,218,713
5,218,738
One liner to convert from list<T> to vector<T>
Is there an one-liner that converts a list<T> to vector<T>? A google search returns me a lot of results that use manual, lengthy conversion, which make me puke. Should we go to that much trouble to do something as simple as a list-to-vector conversion?
You can only create a new vector with all the elements from the list: std::vector<T> v{ std::begin(l), std::end(l) }; where l is a std::list<T>. This will copy all elements from the list to the vector. Since C++11 this can be made more efficient if you don't need the original list anymore. Instead of copying, you can ...
5,218,746
5,218,795
C++: Simple error I cannot spot! C2146
Pretty new to C++, I have been following the intermediate tutorials at 3DBuzz.com, and trying to experiment with their tasks. Current tutorial is on classes: http://www.3dbuzz.com/vbforum/sv_showvideo.php?v=37 I am trying to overload the &operator << to output my 'Point' as a stream when I want. The relevant part of th...
You are missing << in : stream << myPoint.GetX() << " " << myPoint.GetY() << " " myPoint.GetZ(); ^^
5,218,903
5,219,024
How to call a function using pointer-to-member-function
I have a class: class A { void test_func_0(int); void run(); typedef void(A::*test_func_t)(int); struct test_case_t{ test_func_t test_func; } test_case[100]; }; Now I want to call test_func() inside run(): void A::run() { test_case[0].test_func = &test_func_0; test_case[0].*(test_...
Use this: void A::run() { test_case[0].test_func = &A::test_func_0; (this->*(test_case[0].test_func))(1); } Notice that you had 2 errors. The first one was how you formed the member-function-pointer. Note that the only way to do it is to use &ClassName::FuncName regardless of whether you're at class scope ...
5,219,167
5,219,229
std::map segfaults when using operator []
I have a strange issue. I'm using a factory registration pattern which refers internally to a std::map. I'm using this approach for multiple components, and registration happens at multiple points in different units of compilation (aka .cpp files). This happens at static variables initialization time (before 'main' get...
You could be coming up against the static initialization problem: https://isocpp.org/wiki/faq/ctors#static-init-order How are you initialising the map?
5,219,394
5,220,118
how to use tagDEC (DECIMAL type) in c++?
I use an API that returns a windows DECIMAL type. I need to convert it, the information I need is: the number of decimal place the value itself For example, if my number is 1.234, I would like to get (3, 1234), for 10 (0,10) for 0.01 (2,1). How can I extract this information from the tagDec object ? Thanks
Given DECIMAL d, the number of decimal places is d.scale and the value is (d.sign?-1:1) * (double(d.Lo64) + double(d.Hi32) * double(1UL<<32) * double(1UL<<32)) * pow(10, d.scale)
5,219,743
5,220,007
Common Design for Console and GUI
I am designing a little game for my own fun's and training's sake. The real identity of the game being quite irrelevant for my actual question, suppose it's the Mastermind game (which it actually is :) My real goal here is to have an interface IPlayer which will be used for any player: computer or human, console or gu...
Instead of using return values of the various IPlayer methods, consider introducing an observer class for IPlayer objects, like this: class IPlayerObserver { public: virtual ~IPlayerObserver() { } virtual void guessMade( Combination c ) = 0; // ... }; class IPlayer { public: virtual ~IPlayer() { } virtual vo...
5,219,850
5,219,888
Warning C4710 (not inlined) with inherited destructors
I have 3 classes that build a chain of inheritance. Two of the classes are pure abstract (IProxy and IDataProxy), the third one really "does the work" (DataProxy). The classes are the following (only showing con/destructors here): IProxy: class __declspec(dllexport) IProxy { public: IProxy() {} virtual ~IProxy(...
By defining the constructors inside the class, you implicitly add the inline specifier. Virtual functions (including destructors) are not inlined. However the warning most certainly comes from the fact that a dllexport function must have a given (thiscall) calling convention and therefore will never be inlined. Virtual...
5,219,995
5,220,094
How to map and marshal a C array into a C# code
I am writing C# code that call a C library and something it is not quite clear in my mind. The C function has this signature: double* DoSomeStuff(double* input,int numberOfElements); I have mapped the function as: [System.Runtime.InteropServices.DllImportAttribute("myDll.dll", EntryPoint="DoSomeStuff")] public static...
1) Define the input as IntPtr: [System.Runtime.InteropServices.DllImportAttribute("myDll.dll", EntryPoint="DoSomeStuff")] public static extern System.IntPtr DoSomeStuff(IntPtr input, int numberOfElements) ; 2) Create an array in a fixed block, then create an IntPtr from the Pointer and then pass it to DoSomeStuff. do...
5,220,194
5,221,010
Run a soft in debug mode on a computer which haven't visual 2008
I would like to run my Qt application on a computer which haven't visual 2008 installed. It seems I can't manage to use QODBC driver in debug mode on this computer. All is ok in release. Any ideas ? Thanks!
Have you dropped the VS2008 debug runtime where your qodbc driver ist installed? VS2008 has it's debug runtime here by default C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\Debug_NonRedist\x86
5,220,688
5,234,983
How to debug into Quantlib via SWIG from my C# unit test
I have a module in Quantlib that does not work right when I invoke it from C# via SWIG. Is there a way I could debug into Quantlib from my C# unit test?
No one else has answered yet, so I'll provide what we do in similar situations when debugging Ruby + SWIG. Create a Visual Studio project that contains the C# Source Generated by SWIG, the C++ generated by SWIG, your C# unit test and the rest of the Quantlib source. I just looked through the Quantlib provided Visual S...
5,221,460
5,225,401
Working with strings in an xml file C++
I have a function that retrives text between title and links tags from an XML file, but what i want is to test if the title and link tags are between item tags. This is my code: istringstream iss(content); string line; while(getline(iss, line)) { // get <title> and </title> positions int fou...
If you don't want to "parse" the XML, then you will have to know its exact structure. As other people have commented, this is painful and will break if the supplier changes the XML structure without your notification. Example XML: <-- This is not a "Well formed fragment" --> <-- The following is a title tag withou...
5,221,588
5,223,600
Run C++ program using Java
I created a Java program that will process files using a C++ program. This is the part of the code that calls the C++ program: public static boolean buildPAKFile(String OSMFile){ log("Starting building PAK file for " + OSMFile + "..."); // get name of OSMFile String[] OSMFileName = OSMFile.sp...
I found out with the help of @Adrian Cox that the correct implementation should be like this: String gosmoreCmd = " cat " + OSMFile + " | ../gosmore rebuild" + OSMFileName[0] + ".pak"; String[] cmds = {"/bin/bash", "-c", gosmoreCmd}; Process pr = rt.exec(cmds); /bin/bash runs the shell, which ...
5,221,691
5,221,730
C++ Constness problem
I have a problem with whether making class members constant or not. Let me give an example. #include <iostream> class ValueClass { int ival; public: void set(int i) {ival = i;} int get() {return ival;} }; class XXX; class ABC { ValueClass vc; public: int getval() const {return vc.get() ;} frie...
Make get() const in ValueClass class ValueClass { int ival; public: void set(int i) {ival = i;} int get() const {return ival;} // make get const }; Probably should do the same for getABC const ABC & getABC() const { return abc; } This means that this method does not change the object it...
5,221,961
5,222,012
C++: constructor / initializer for array?
I'm familiar with C++ constructors & initializers: class Foo { int x; public: Foo(int _x) : x(_x) {} }; Foo foo1(37); Foo foo2(104); My question is that I have to implement a class that has a member which is a 3x6 array. How would I do something similar to the above? class Bar { int coeff[3][6]; public: /...
You can't. In C++03 you can't initialize an array in a ctor-initalization list. However you can do it in the constructor body (technically it isn't an initialization any more). That is struct x { int a[4]; x():a({1,2,3,4}) //illegal { a[0] = 1; etc. } }; Edit: after question edit here...
5,221,981
5,222,201
Allegro in Ubuntu: undefined reference to `al_install_system'
I tried installing the Allegro library today. I have same experience in C++, but it seems I have none in doing stuff like that. I have compiled Allegro 5.0 from source and put it in /usr/lib/gcc/i486-linux-gnu/4.4/include/allegro5. But when I try to compile my code, this comes up: > g++ test2.cc -o test2 /home/chri...
You need to link with the Allegro libraries, but you don't seem to do so. allegro-config --libs returns nothing. There's part of your problem. Normally, you should be able to add it to your command line, like so: g++ `allegro-config --libs` test2.cc -o test2 On my system (Ubuntu 10.10) it gives this: $ allegro-confi...
5,222,008
5,222,077
Calling a function immediately before main
Is is possible to register a function to be run immediately before main is entered? I know that all global objects are created before entering main, so I could put the code in the constructor of a global object, but that does not guarantee any particular order. What I would like to do is put some registration code into...
If you're using gcc, you can use the constructor attribute on a function to have it called before main (see the documentation for more details). constructor destructor The constructor attribute causes the function to be called automatically before execution enters main (). Similarly, the destructor attribute causes th...
5,222,066
5,225,514
GameDevelopment: (Java & OpenGL) or (C++ & OpenGL & SDL)?
Since Java supports OpenGL, what is the best option for developing a game? Java + OpenGL C++ + SDL + OpenGL I always avoided Java (in game development, of course) because of it's speed. But, I discovered that Java supports OpenGL. So, I think speed can't be the problem anymore. What should you choose? Are there remar...
I would vote for C++ for the simple fact that you have a dependable destructor in your objects. This lets you wrap many of the OpenGL components (buffers, textures, etc.). You can know that when the object is created, the asset is allocated, and when the object is destroyed (or goes out of scope), the asset is cleaned ...
5,222,404
5,222,460
C++ - value of uninitialized vector<int>
I understand from the answer to this question that values of global/static uninitialized int will be 0. The answer to this one says that for vectors, the default constructor for the object type will be called. I am unable to figure out - what happens when I have vector<int> v(10) in a local function. What is the ...
The zero initialization is specified in the standard as default zero initialization/value initialization for builtin types, primarily to support just this type of case in template use. Note that this behavior is different from a local variable such as int x; which leaves the value uninitialized (as in the C language th...
5,222,452
5,222,489
How to initialize members of the base class subobject to 0?
class A { public: int a,b,c; }; class B: public A { public: int d; B():d(0){} // Some hackery needed here }; int main() { B obj; std::cout<< obj.a << std::endl; // garbage std::cout<< obj.b << std::endl; // garbage std::cout<< obj.c << std::endl; // garbage std::cout<< obj.d << std::endl; // 0 ...
Try B() : A() , d(0){} A() value initializes A and since A is a POD the members will be default(zero) initialized
5,222,537
5,222,588
how to get std::list <std::string>::iterator to output error value?
I'm searching through a list of values, and want to have it return some sort of 'default' error value when it cant find the value to search for. I don't mean std::cerr. i mean a value that i can use in my program like a bool. However, if it does find the string, I need the pointer value of where it is in the string. Ho...
typedef std::list<std::string> MyList; MyList mylist; MyList::iterator iter = mylist.find("somestring"); if (iter != mylist.end() ) { // the string was found } else { // the string was not found }
5,222,606
5,223,026
throwing a boost::shared_ptr< customException>
is there any pitfall of the following; if (someCondition) throw boost::shared_ptr<SomeException>( new SomeException( "foo!" ) ); ... catch( const boost::shared_ptr<SomeException>& expRef ) { }
Yes, there is a pitfall. You won't be able to catch based on base classes: void f() { throw std::runtime_error("look here"); } void g() { throw boost::shared_ptr<std::runtime_error>("look here"); } int main() { try { f(); } catch ( std::exception const& e) {} try { g(); } catch ( boost::shared_pt...
5,222,771
5,222,936
C++ template question
i got assignment, where i must write a class for multidimensional vector i was told that i must use templates, which is totally new to me, and to be exact, then i must use template <unsigned short n> , where n defines how many dimensions my vector has. so far i have this, but it is not working: vector.h #include <vecto...
You should really read up on templates first: http://www.cplusplus.com/doc/tutorial/templates/ Templates are nice because they enable you to work with generic types. For instance, getting the maximum or minimum of two objects (int, long, float etc.) using the same code. In your case it's a good idea to use templates be...
5,223,066
5,223,146
Converting int[] to String in C++
I have a string defined as std::string header = "00110033"; now I need the string to hold the byte values of the digits as if its constructed like this char data_bytes[] = { 0, 0, 1, 1, 0, 0, 3, 3}; std::string header = new std::string(data_bytes, 8).c_str()); I converted the initial string to int array using atoi. N...
you could write a little function string int_array_to_string(int int_array[], int size_of_array) { string returnstring = ""; for (int temp = 0; temp < size_of_array; temp++) returnstring += itoa(int_array[temp]); return returnstring; } untested! a slightly different approach string int_array_to_string(int in...
5,223,299
5,223,474
C++ determine if compiling with debug symbols without defining a preprocessor symbol
I have been using something like this: int main(int argc, char *argv[]) { #ifdef DEBUG printf("RUNNING DEBUG BUILD"); #else printf("Running... this is a release build."); #endif ... However this requires me to compile with -DDEBUG for the debug build. Does GCC give me some way for me to determine when I am c...
Answer is no. Usually these macros (DEBUG, NDEBUG, _DEBUG) are set by the IDE/make system depending on which configuration (debug/release) you have active. I think these answers can be of help: C #define macro for debug printing Where does the -DNDEBUG normally come from? _DEBUG vs NDEBUG
5,223,588
5,224,115
Creating a more advanced scheduler
So i am going to be upgrading some scheduler code and it is currently very dumb. I would love to upgrade the code to be similar to Outlook's every Monday at 5 etc. or every third Thursday of the month. Current schedule system can not specify a day of the week only a period like (daily, weekly, monthly, annually) and c...
Boost.Date_Time should give you the date manipulation functions you need. Should be easier to use their (debugged) code rather than trying to reinvent it.
5,223,690
5,223,872
C++'s "inline" - how strong a hint is it for GCC and Clang/LLVM?
In C++, the keyword "inline" serves two purposes. First, it allows a definition to appear in multiple translation units. Second, it's a hint to the compiler that a function should be inlined in the compiled code. My question: in code generated by GCC and Clang/LLVM, does the keyword "inline" have any bearing on whether...
[Caveat: not a C++/GCC guru] You'll want to read up on inline here. Also, this, for GCC/C99. The extent to which suggestions made by using the inline function specifier are effective (C99 6.7.4). GCC will not inline any functions if the -fno-inline option is used or if -O0 is used. Otherwise, GCC may still be unable ...
5,223,789
5,224,028
#elif defined without parentheses
Using VS2005 with BLAH_BLAH defined the following preprocessor conditional is false: #elif defined BLAH_BLAH but if I change it to #elif defined(BLAH_BLAH) it is true. Why do the parentheses make a difference here?
The header file was created with a linux editor and added to the project with "Add Existing", after creating the file in the VS editor it evaluates to true. Must be a LF/CR issue?
5,223,820
5,223,888
What is the c++ translation for 'textscan' function from Matlab?
What is a simple translation in code for 'textscan' from matlab into C or C++? I am using Ubuntu and I am trying to translate a Matlab code into C++. Thank you very much.
First, the answer is not the same if you're using C or if you're using C++. These are different programming languages. Matlab is a much higher-level language than C and C++. In Matlab textscan reads from files or strings. C and C++ have different mechanisms for that. To read from a file : In C, you should use the FILE ...
5,224,029
5,224,993
Read from input two values and add them, just using one variable.. possible?
Salute.. Let's see this example: int x,y,s; cin>>x>>y; s=x+y; here we have three variables for adding two values.. Can we do this just with one variable? thanks.
How about zero variables? #include <numeric> #include <iterator> #include <iostream> int main() { std::cout << std::accumulate( std::istream_iterator<int>(std::cin), std::istream_iterator<int>(), 0) << "\n"; }
5,224,154
5,224,518
Application crash with no explanation
I'd like to apologize in advance, because this is not a very good question. I have a server application that runs as a service on a dedicated Windows server. Very randomly, this application crashes and leaves no hint as to what caused the crash. When it crashes, the event logs have an entry stating that the application...
If your app is evaporating an not generating a dump file, then it is likely that an exception is being generated which your app doesnt (or cant) handle. This could happen in two instances: 1) A top-level exception is generated and there is no matching catch block for that exception type. 2) You have a matching catch b...
5,224,350
5,224,415
How to get size of an array using metaprogramming?
Possible Duplicate: Use templates to get an array's size and end address Can someone explain this template code that gives me the size of an array? (the first answer includes obtaining the value as a compile time constant) How to get size of an array using metaprogramming? Multidimensional would be also appreciated. ...
For one dimensional Arrays, template<typename T, size_t N> size_t size_of_array(T (&)[N]) { return N; } int arr[]={1,2,2,3,4,4,4,54,5}; cout << size_of_array(arr) << endl; A a[] = {A(),A(), A(), A(), A()}; cout << size_of_array(a) << endl; Output: 9 5 Full Demo at Ideone : http://ideone.com/tpWk8 EDIT: Ano...
5,224,381
5,227,169
MingW Netbeans 6.9.1 problem
I have one problem with MingW(mingw-get-inst-20110211) and Netbeans 6.9.1. I installed MingW and add it to Netbeans without problem, but when I try to run one simple cpp app, throws this error mkdir -p build/Debug/MinGW-Windows make[2]: mkdir: Command not found make[2]: [build/Debug/MinGW-Windows/main.o] Error 12...
It's was kind of messy but finally get a way. 1° Install MinGW (C/C++ en my particular case) 2° Install MSYS (Answer two or three question at the end of installation, refering where MinGW is installed) 3° Add to Netbeans(Tools>Options>C/C++) the "\MinGW\bin" adress. It should look like this It should be it regarding i...
5,224,733
5,225,087
What is the correct implementation of AVL Tree Rotation?
When inserting 50,49,48 into an AVL Tree, it prints out. The root is: 50 50 Level: 0 Height: 0 49 Level: 1 Height: 0 50 Level: 0 Height: -1 50 Level: 0 Height: 0 -->> Rotation did not work? Here are my functions. Rotate Left: void AVLTree::rotateLeft(AVLNode* node) { AVLNode* otherNode = node; otherNo...
The node parameter to your rotateLeft function is a local variable in rotateLeft. In other words, when you assign a value to that variable in rotateLeft, the n variable in insert is not modified. You need to pass n to rotateLeft either through a pointer or through a reference, i.e. either void AVLTree::rotateLeft(AVLNo...
5,224,751
5,225,975
Using Glew in multiple files
Somehow I can't get Glew in multiple header files. It is just complaining about Gl is already defined before GLEW. I have the following file structure in short: Program.h includes: <GL/glew.h>, <GL/freeglut.h> and "SceneManager.h". SceneManager.h includes: "GameObject.h" GameObject.h includes: <GL/glew.h>, <GL/freeglu...
I did it a bit different myself right now: I created a precompiled header with glew and freeglut in it. It looks like this: #ifndef _STDAFX_H_ #define _STDAFX_H_ #include <GL/glew.h> #include <GL/freeglut.h> #endif Could someone confirm if this is a solid and well know method to do so?
5,224,825
5,225,141
Analysis of the usage of prime numbers in hash functions
I was studying hash-based sort and I found that using prime numbers in a hash function is considered a good idea, because multiplying each character of the key by a prime number and adding the results up would produce a unique value (because primes are unique) and a prime number like 31 would produce better distributio...
I think it's easier to see if you use 2 instead of 26. They both have the same effect on the lowest-order bit of h. Consider a 33 character string of some character c followed by 32 zero bytes (for illustrative purposes). Since the string isn't wholly null you'd hope the hash would be nonzero. For the first character, ...
5,225,044
5,225,511
Terrain collision with .X file
I have been looking for example of terrain collision that is in C++ but i haven't found anything. I found one example that uses .RAW file it is in toymaker.info so don't mention it. How do you detect collision between object can terrain against every triangle. I know it will be slow. How you detect collision between...
Here is one method: Draw a line from the origin through the center of a sphere you wish to test collision of. Now do a ray triangle intersection using the line, or ray, you have just created. You now know if the ray has passed through the triangle or not. If it has passed through the triangle then get the point it...
5,225,459
5,225,560
Asynchronous socket questions
Alright, I found out in this question that polling sockets does not scale, so I've decided to look into asynchronous sockets, and I have several questions. If I have several hundred clients all trying to send data to their partner, what would be the best async method to use? select() poll() or can I just call recv() o...
The choice of polling method is OS dependent. On linux, use epoll, preferrably edge-triggered. On FreeBSD, use kqueue. On Windows, use e.g. WSAEventSelect and WSAWaitForMultipleEvents. Your main loop should simply be: for (;;) { epoll(); // blocking poll until an event happens, optionally with a timeout // iterate ...
5,225,480
5,225,614
Activemq-cpp BytesMessage
I'm working with activemq-cpp and I am attempting to send binary data using BytesMessage. I have a producer and a consumer set up to send and receive the message. The connection and session is working properly because I am able to publish to a topic and allow the consumer to pick up the message using TextMessage. After...
Have you read the API docs for cms::BytesMessage, its summed up fairly well in there. Basically you need to allocate the amount of space in the vector you want it to fill. Since your vector is not sized it returns nothing, you could create the vector using the getBodyLength method of BytesMessage. The API docs are lo...
5,225,493
5,225,547
Which programming style is better? from an optimization perspective
Having a large integer 32/64bit, I'm modifying several bit positions. Style 1 Integer64 = Modify(Integer64); Style 2 Modify(Integer64); Style 3 Using the same style as the 1st, but inline function 1st) returns a 64bit modified value 2nd) a backup buffer is created and the original value is copied, too. the calculat...
Don't pick a style from an optimization perspective. Pick the one that, when read by future maintainers, will most clearly indicate what's happening. Then if your program has performance problems you can profile and see if the method is causing problems, and if so then consider your options at that point.
5,225,543
5,225,572
Calling 32 bit lib files from 64 bit targeted application
I am writing a 64 bit targeted c++ program. I need to call commands from a 3rd party .lib file that is targeted towards a 32 bit environment, however when trying to do so I get a LNK2001 error. Is it possible to do this?
Not directly, no; you can't link 32-bit code into a 64-bit executable. Perhaps you could create a separate 32-bit process to host your static lib and write a stub API in your 64-bit program that uses interprocess communication to have the 32-bit process execute the code on your behalf.
5,225,579
5,227,585
Crash reporting for MinGW applications
I have a c++ application compiled with MinGW for which I've been receiving crash complaints from customers. So, besides heavily logging in the parts that might be crashing (before releasing a new version), I've been looking for a crash reporter that will help me find out the stack trace and any other useful debugging i...
Actually the problem is not so much getting the crash reports to work. That is rather trivial with the DbgHelp library functions and most prominently there MiniDumpWriteDump. Remember, however, to redistribute the DbgHelp library on older systems and observe the version requirements for the functions you intend to call...
5,225,588
5,225,609
Abstract class without abstract methods
Is it possible to make a class abstract in C++ without declaring any abstract methods? Currently, I have a Sprite class with a StaticSprite and DynamicSprite subclass. I would like to make the Sprite class abstract. The problem is that there aren't any methods they share. Well, both StaticSprite and DynamicSprite might...
You can declare your destructor as pure virtual, since all classes have one. class AbstractClass { public: virtual ~AbstractClass() = 0 ; } ; However, you will need to define this destructor elsewhere. AbstractClass::~AbstractClass() {}
5,225,635
5,225,740
What is an RPC Callback Thread?
I am using Visual Studio 2008. The Threads window shows two RPC Callback Threads for my application. What are these? More specifically, are they suppose to do?
They are Remote Procedure Call Threads: http://en.wikipedia.org/wiki/Remote_procedure_call Here is an msdn article on how Remote Procedure Call works on windows: http://msdn.microsoft.com/en-us/library/aa373935%28v=vs.85%29.aspx The articles only deal with RPC over a network, but it is also used for inter-process commu...
5,225,680
5,321,006
How do I interpolate over tif file image using itk?
This only goes out to those who knows the itk package well. I just started using itk package recently to try to play with images using it, and I have a question. I have two tif image files(dicom images), and I want to divide the image into 4, then combine two images into one(two images have same pixels and dimensions, ...
I don't have any example code handy, but I wonder if this isn't what you are looking for: http://www.itk.org/Doxygen/html/classitk_1_1BinaryFunctorImageFilter.html#_details Hope that helps -
5,225,820
5,225,902
Compare two vectors C++
I was wondering is there any function to compare 2 string vectors to return the number of different(or the same) elements? Or i have to iterate over both of them and test item by item. Thanks.
std::sort(v1.begin(), v1.end()); std::sort(v2.begin(), v2.end()); std::vector<string> v3; std::set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(v3)); Or, if you don't want to sort: std::set<string> s1(v1.begin(), v1.end()); std::set<string> s2(v2.begin(), v2.end()); std::vector<string> v...
5,225,914
5,226,726
Optimization: Preallocate a chunk of heap memory prior to use by multiple objects - GAINS?
Are there large gains in PERFORMANCE to be made by allocating heap memory in advance and filling it incrementally? Consider the VERY simplified example below: byte * heapSpace = malloc (1 000 000); int currentWriteSpot = 0; struct A { int x; byte * extraSpace; int extraSpaceLength; }; //a1 needs 10 bytes of e...
First of all, doing this does not increase complexity; it decreases it. Because you have already determined at the beginning of your operation that malloc was successful, you don't need any further checks for failure, which would at least have to free the allocations already made and perhaps reverse other changes to va...
5,225,996
5,226,134
Blowfish C++ does not correctly encrypt/decrypt.. why..?
I have this piece of test code that uses Blowfish (openssl/blowfish.h) to encrypt, then decrypt a string. But when it comes out again, it hasn't been decrypted properly. Can anyone tell me why please? (copied from OP's original at http://pastebin.com/AaWSF5pX) #include <stdlib.h> #include <cstdio> #include <string.h> #...
Blowfish operates on 64-bit blocks: that is, multiples of 8 bytes. BF_ecb_* processes a single such block. That's the first 8 characters of your string. The rest is ignored by BF_ecb_*. If you want to encrypt something longer, apply BF_ecb_* to one block after another in a loop if you're really happy to use the ECB mod...
5,226,241
5,226,318
Searching huge sorted chunks of data
I have a huge set data records in disk that arranged in sorted order based on some key(s). The data is read into memory a block (thousands of records) at a time. I have to search and display all records matching a key. I was thinking of some binary search based algorithm, but I have some restrictions here. Records ca...
You could build a secondary array that consists of the first entry in each block then run binary search on that array. The indices for the array should corresponding directly with the block indices making it an O(1) lookup to get the corresponding block. It cuts the worst case from O(n) to O(logn) and is still relativ...
5,226,352
5,226,402
Declare an array of objects using a for loop c++
Okay. So I have declared an array of objects, and I have manually defined them using this code: Object* objects[] = { new Object(/*constructor parameters*/), new Object(/*constructor parameters*/) }; Is there anyway to use some kind of a loop (preferably a for loop) to declare these? Something like: Object* o...
I strongly suggest using a standard library container instead of arrays and pointers: #include <vector> std::vector<Object> objects; // ... void inside_some_function() { objects.reserve(20); for (int i = 0; i < 20; ++i) { objects.push_back(Object( /* constructor parameters */ )); } } This pr...
5,226,387
5,226,497
c++: stringstream to vector
I'm trying to store the data that is in a stringstream into a vector. I can succesfully do so but it ignores the spaces in the string. How do I make it so the spaces are also pushed into the vector? Thanks! Code stub: #include <iostream> #include <sstream> #include <vector> using namespace std; int main() { strin...
Why are you using a stringstream to copy from a string into a vector<unsigned char>? You can just do: vector<unsigned char> vec(line.begin(), line.end()); and that will do the copy directly. If you need to use a stringstream, you need to use stream >> noskipws first.
5,226,427
5,226,476
Flood fill algorithm in c++
I'm trying to write code that will do a flood fill of a color on an image, and I'm using Stacks. (Still new to stacks and queues, so I'm not sure which one would be a better idea). Anyway, I think I got the basic idea down, but there's a flaw with my code: animation DFSfill(BMP& img, int x, int y, colorPicker & fillCol...
In the stack you are supposed to save the coordinates, not the color. Instead of saving *img(x+1,y) you need to save just x+1,y. you can do this possibly with a struct that holds both coordinates. Saving the coordinates allows you to travel across the region you're filling. Saving the color doesn't really make any sens...
5,226,521
5,226,830
boost test case for function taking user input
I have a function that takes in user input via std::cin: std::getline(std::cin, in); and creates a corresponding data structure by matching it with a regular expression. The function then returns this data structure. I'm using boost.test and I want to create a unit test to check that the output data type is correct gi...
If you have access to the source code of the function that calls std::getline, then the easiest solution is to rewrite it as a wrapper of another function having the same signature and implementation, but taking an additional std::istream& parameter that is used in place of std::cin. For example, if you currently have:...
5,226,558
5,226,620
Why is overloading operator->() useful?
I saw the following example in book of the C++ Programming Language class Ptr { X* operator->( ); }; voide f(Ptr p) { p->m=7; X* q1 = p->; X* q2 = p.operator->(); } The book claims that 1)Objects of class Ptr can be used to access members of class X in a very similar manner to the way pointers are ...
This design is extremely useful when we want to create a class that behaves like a pointer; this is the case of smart pointers (objects that have a pointer-like interface but that provide additional "services", e.g. automatic deallocation on destruction, ownership transfer, reference counting, ...). Notice that often ...
5,226,696
5,234,367
How to specify the default selected Radiobutton in MFC?
I have two radiobuttons on my dialog. I set up the tabstop order correctly and turned the group property on on one of them and added an int member variable which I can read. What I'm wondering now is: How can I preselect a default option? Right now, when the dialog gets created, no radiobutton ist visually selected. Do...
Use the CheckRadioButton to set the state of the radio buttons.
5,226,838
5,229,025
Why does pthread_create() sometimes give EAGAIN on Cygwin port?
What does it mean when pthread_create() returns errno 11 (EAGAIN), "Resource temporarily unavailable"? I am porting my application to Cygwin from it working great on Centos 4. Every once in a while, the application fails in its call to pthread_create(), but most of the time it works fine. What does this mean is going ...
From pthread_create() man page : The pthread_create() function shall fail if: EAGAIN The system lacked the necessary resources to create another thread, or the system-imposed limit on the total number of threads in a process {PTHREAD_THREADS_MAX} would be exceeded. You can try again, after releasing some resources.
5,226,901
5,226,948
Cross-process interaction under C++
Please help, how can I organize the process-process data exchange (in Windows, if that matters)? I have process1.exe which calls process2.exe with a few command line arguments. I want to track "progress" of process2 from process1 (say, some int value). It (that int value) can be accessed from process1 permanently or ea...
OTOH: stdin/stdout redirection Named pipe (CreateNamedPipe) Anonymous pipe (CreatePipe) Sockets (socket, connect, bind) Shared memory (CreateFileMapping, MapViewOfFile) Windows messages (e.g. WM_APP) Pick one - Windows messages or shared memory may be the easier ones.
5,227,334
5,227,379
Script programming strategies for high-load servers
I have a MMORPG server in C++, I've never done scripting before and from my point of view I think it would be degrading to the overall performance of the server if I parse scripts on the go (I haven't tested though), but I would like to have such functionality. What good scripting techniques for multi-threaded environm...
I believe the majority of commonly used scripting languages perform parsing as a separate step to execution, so that wouldn't be a significant performance cost. Usually they compile to some kind of bytecode format (Python, Lua and Perl all do this for example), and often that format can be serialised and loaded directl...
5,227,546
5,227,556
why destruction is called?
I don't know why the destruction of an object in vector is called at the following point of time. class Something { public: Something() {} ~Something() { cout << "destruction called" << endl; } }; int main() { std::vector<Something> vec; Something sth1 = Something(); Something sth2 = Somethi...
Because the vector has to resize its capacity to be able to store two elements instead of one. It allocates a new buffer, it copies the old buffer to the new one, removes the old buffer, and then adds the new object.
5,228,070
5,228,482
Alternatives to virtual functions for wrapping SDL and OpenGL drawing methods
I am trying to write some boilerplate code for a game in C++. I want to draw using both SDL and OpenGL. For example, I would like to have 2 versions of the functions "DrawPixel" written in both OpenGL and SDL. I can't use both SDL and OpenGL for rendering at the same time, but I would like a common interface for the dr...
Before I get into answering your question, have you considered making this a compile-time flag, e.g. #define -- That would let you decide on either GL or SDL, without wasting space or requiring a virtual call. Definitely go for this solution if you can. Virtual functions are just an extra pointer lookup, calling a poin...
5,228,269
5,228,307
Check if two vectors are equal
How can I check whether the first "n" elements of two vectors are equal or not? I tried the following: #include <iostream> #include <vector> #include <iterator> using namespace std; typedef vector<double> v_t; int main(){ v_t v1,v2; int n = 9; for (int i = 1; i<10; i++){ v1.push_back(i); ...
Use the std::equal function from the <algorithm> header: if (std::equal(v1.begin(), v1.begin() + n, v2.begin())) std::cout << "success" << std::endl; Note that both vectors must have at least n elements in them. If either one is too short, behavior of your program will be undefined. If you want to check whether the ...
5,228,765
6,396,857
Difference between Named Equivalence and Structured Equivalence?
I've been hunting and searching for a way to understand Named Equivalence vs. Structured Equivalence and everything I find has Ada, ALGOL or Pascal examples. I'm more of a C#/Java/C++ developer so their examples aren't getting through to me. I don't know if I'm right, but this is how I think it works: struct One { in...
You are spot on with that. Thats all there is to it actually. C doesn't have structural equivalence, it supports only name equivalence. Code like if ( A == B ) Will give you an error in languages that don't support structural equivalence. This isn't much of an answer, you're already on the right track.
5,229,039
5,229,111
How can I enumerate all the file in a directory in POSIX/c c++?
I need to enumarate all the file in a dir and then navigate to the subdir and do the same. Ideally the algorithm should work in the same way on linux macos [windows(obsolete) no more]. UPDATE: I'm now aware of VFS but I'm puzzled to use VFS for enumerate dir. Any suggestion ? Should I open a dir as file ?
POSIX.1-2001 specifies opendir, readdir, and closedir, seekdir, rewinddir, and telldir. Your platform likely has man pages describing how to use them. These are reportedly not supported directly by MS libraries, instead apparently preferring to use FindFirst and FindNext over there, but there's supposedly several emul...
5,229,224
5,229,288
C++ -- why we have to define this friend template class
template<class T> class auto_ptr2 { public: explicit auto_ptr2(T *p = 0): pointee(p) {} template<class U> auto_ptr2(auto_ptr2<U>& rhs): pointee(rhs.release()) {} ~auto_ptr2() { delete pointee; } template<class U> auto_ptr2<T>& operator=(auto_ptr2<U>& rhs) { if (this != &rhs) reset(rh...
Why we have to define this friend class I'm fairly sure you don't; as far as I can see, nothing is referencing the private member of a different template instantiation. You would need it if the copy constructor or assignment operator manipulated rhs.pointee directly, rather than just calling rhs.release(). I cannot ...
5,229,482
5,229,751
Accessing Members of Containing Objects from Contained Objects
If I have several levels of object containment (one object defines and instantiates another object which define and instantiate another object..), is it possible to get access to upper, containing - object variables and functions, please? Example: class CObjectOne { public: CObjectOne::CObjectOne() {...
When you pass a pointer that points back to the container object, this pointer is sometimes called a back pointer. I see this technique being used all the time in GUI libraries where a widget might want access to its parent widget. That being said, you should ask yourself if there's a better design that doesn't involve...
5,229,622
5,229,796
How to get through the 120 bytes limit?
This is actually a SPOJ problem: WAYS Now this is a very easy task what we need to do is to compute the Central binomial coefficients. However the problem setter includes a very notorious source limit of 120 bytes, so my question is how to get past that source code limit in the languages that are allowed?
Assuming, that C(2n,n) = (2n)!/(n!)^2 = (2n(2n-1)/n^2) * C(2(n-1),n-1) = ((4n-2)/n)*C(2(n-1),n-1) here is function, which calculates central binomial: int f(int n) { return n==1? 2 : f(n-1)*(4*n-2)/n; } Edit: Here is probably shortest code: int f(int n){return n<2?2:f(n-1)*(4*n-2)/n;} It is only 44 characters.
5,229,644
5,229,657
Why Compilation Speed Differs a lot in C++ and C#?
Possible Duplicate: Why does C++ compilation take so long? Coming from C# background, I can't help but notice that the speed of compilation for C++ and C# code differs a lot-- C# is very fast to compile, but C++ is comparatively slow-- very slow, in fact. Why is this so?
Two big reasons: C++ has to go and #include and parse all the header files (which means reading text files and interpreting them -- including templates -- and then expanding them right into your code) whereas C# uses pre-compiled information in the assembly DLLs. The potential C++ optimizations are way more far-reachi...
5,229,729
5,229,765
c++ creating object of second class in the constructor of first class - multithreading
I have two classes one and two . Both run threads. class Two is to thread a function declared in class one . this is done by calling it in the run method of the second class. I am trying to call/start the thread Two in constructor of one so that both these threads run together. i get scope error .due to missing syntax....
Your error are caused by compiler trying to instantiate class/type that hasn't been declared. You should split your declaration and implementation into separate file, preferably the widely used .h and .cpp format. Then include the type's header in cpp where you need them.
5,229,745
5,229,992
C++ Question - Can anyone help?
Would you mind helping me to solving the following question? Thanks. Question: The percentage of rolling 3 dices of face 6 in one go can be found out mathematically or simulation. The Monte Carlo method is a computer process to find out the solution of a problem by computer simulation. Write a program that roll three d...
Also, when calculating rand() you need to realize it is not all that random as we hope. From the documentation at: http://www.cplusplus.com/reference/clibrary/cstdlib/rand/ "Notice though that this modulo operation does not generate a truly uniformly distributed random number in the span (since in most cases lower numb...
5,230,147
5,230,456
Passing Structure from C# to C++
I have the following structure in C++: extern "C" __declspec(dllexport) struct SnapRoundingOption { double PixelSize; bool IsISR; bool IsOutputInteger; int KdTrees; }; And this is my function declaration in C++: extern "C" __declspec(dllexport) void FaceGenerationDummy(SnapRoundingOption snapOption); ...
The problem here is how you are marshalling the bool fields. These are single bytes in C++ and so need to be marshalled so: [StructLayout(LayoutKind.Sequential)] public struct SnapRoundingOption { public double PixelSize; [MarshalAs(UnmanagedType.U1)] public bool IsISR; [MarshalAs(UnmanagedType.U1)] ...
5,230,314
5,230,344
How to split a string?
Possible Duplicate: Is There A Built-In Way to Split Strings In C++? i have one string variable which contains: string var = "this_is.that_alos" how i can separate only "that_alos" from it. i.e. i need only second part after "that_alos"
std::string var = "this_is.that_alos"; std::string part = var.substr(var.find_first_of('.')); If you want to exclude the '.', just add 1: std::string part = var.substr(var.find_first_of('.') + 1);
5,230,338
5,230,553
How to simply reconstruct numbers from a buffer in little endian format
Suppose I have: typedef unsigned long long uint64; unsigned char data[BUF_SIZE]; uint64 MyPacket::GetCRC() { return (uint64)(data[45] | data[46] << 8 | data[47] << 16 | data[48] << 24 | (uint64)data[49] << 32| (uint64)data[50] << 40 | (uint64)data[51] << 48| (uint64)data[52] << 56);...
Nothing much wrong with what you have there to be honest. It will work and it's quick. The thing I'd change would be to format it a little better for readability: uint64 MyPacket::GetCRC() { return (uint64) data[45] | (uint64) data[46] << 8 | (uint64) data[47] << 16 | (uint64) dat...
5,230,444
5,231,375
c++ qthread starting 2 threads concurrently
I have two threads One and Two. defined by their respective classes in the header file.I want to start the second thread when the first thread is started. creating and starting the second thread in the constructor of the first produced unexpected result. my header file "header.h" #ifndef HEADER #define HEADER #include...
I believe you've perhaps misunderstood some threading concepts. It sounds like you want to start two threads, then from one thread context make a function call to another thread context, which is not how threads work. When you start these two threads, they execute independently of each other. They can share access to d...
5,230,463
5,230,498
what does this function declaration mean in c++
virtual const char* what() const throw() { } AFAIK it's a function that will return a constant pointer to a mutable char. The rest I am not sure. Could anybody help?
Regarding the const throw() part: const means that this function (which is a member function) will not change the observable state of the object it is called on. The compiler enforces this by not allowing you to call non-const methods from this one, and by not allowing you to modify the values of members. throw() mean...
5,230,621
5,230,968
Checking Who Won Tic Tac Toe More Efficient C++
I'm writing a Tic Tac Toe Game and I would like to know how I can make an efficient function to check who won. A two dimensional array congaing X's, O's, or blank spaces represents the board. char CheckWin(const char board[][NUM_COLS], int& sum) // tic tac toe board - IN { char tmp; int lcv; tmp = ' '; ...
You could convert the array into two nine-bit values, one for the O positions and one for the X position, and a count of blank spaces: x_mask = 0 y_mask = 0 empty_count = 0 mask = 1 for each square if x then x_mask |= mask if y then y_mask |= mask if empty then empty_count++ mask <<= 1 Then compare the x_mask ...
5,230,650
5,230,685
how to append two string?
i have one string variable svcName="serviceName" and i have to append "Base" this string at the end of svcName string. and store into another string.
#include <string> std::string s = "abc"; s += "def";
5,230,845
5,230,971
How to get the value out of a multi index
I am trying to do one multi map(4 variables) using boost- multi index. Can I know how to get the value of a particular index like tmp_Container.get<name>().find("aaa")->firstVariable EDIT struct EnumStruct { int microsoftEnum; std::string microsoftEnumString; int localEnum; std::string localEnumString...
You need the project function. See http://www.boost.org/doc/libs/1_39_0/libs/multi_index/doc/tutorial/basics.html#projection and http://www.boost.org/doc/libs/1_46_0/libs/multi_index/doc/reference/multi_index_container.html#projection. Thus: tmp_Container.project<0>(tmp_Container.get<name>.find("aaa")).
5,231,096
5,231,118
Time complexity of power()
I implemented this function power() which takes two arguments a and b and computes ab. typedef long long int LL; LL power(int a,int b) { int i = 1; LL pow = 1; for( ; i <= b ; ++i ) pow *= a; return pow; } Given : ab falls in the range of long long int. Problem : How to reduce the time complexity o...
Exponentiation by Squaring. A non-recursive implementation LL power(int a, int b) { LL pow = 1; while ( b ) { if ( b & 1 ) { pow = pow * a; --b; } a = a*a; b = b/2; } return pow; } This algorithm requires log2b squarings and at most log2b ...
5,231,186
5,231,820
Simplest way to create a HWND
I need a dummy window in MSVC++, this will never be visible and is created even before the app's main window. It's required by a rendering engine. So I'd rather not have to register a class if possible. For testing it would be better to make it visible to prove it is there - can I use a static or a button or something?...
I submit my own test code for critique: HWND dummyHWND = ::CreateWindowA("STATIC","dummy",WS_VISIBLE,0,0,100,100,NULL,NULL,NULL,NULL); ::SetWindowTextA(dummyHWND,"Dummy Window!"); It seemed to work...
5,231,334
5,231,354
What does this quote about char pointers mean?
I've read a paragraph but I can't understand what does it mean....can anyone please explain? the paragraph is : processing a single character as a char*string can lead to a fatal runtime error. a char* string is a pointer probably a large integer. however a character is a small integer(ascii 0-255). on many ...
It means you shouldn't do something like: char *pCh = 'A'; // this is the value 0x41 (assuming ASCII). char Ch = *pCh; // probably not what you wanted. because there is a vast difference between a character and a character pointer. In fact, a decent compiler should give you a warning when you attempt to do somethin...
5,231,680
5,231,750
shared pointer forward declaration
I have an interface Interface. I also have a .h file InterfaceFwd.h which looks something like #ifndef Blah #define Blah #include <boost/shared_ptr.hpp> class Interface; typedef boost::shared_ptr<Interface> InterfacePtr; #endif I also have Interface.h #ifndef SomeOtherBlah #define SomeOtherBlah class Interface { vi...
The one definition rule doesn't apply to typedefs. A typedef (on its own) doesn't define a new variable, function, class type, enumeration type or template. You are explicitly allowed to redefine a previous typedef-name to refer to the type that it already refers to. 7.1.3 [dcl.typedef]: In a given non-class scope, a ...
5,231,781
5,232,069
Efficient / elegant two dimensional container
Need for two dimensional array of objects that could be something like: myContainer<myObject*> *a = new myArray<myObject*>( 20, 20 ); // passing int's as width & height later accessing values would be done with methods such as: mylist<myObject*> getRow( int ); mylist<myObject*> getColumn( int ); mylist<myObject*> get...
STL has the valarray container which can be viewed as row and columns using slices, but you have to do it manually or wrap it into a wrapper class. Also the slices represents the values of the valarray (they are not a copy), but it is designed to be used with numbers and to be a bit optimized, it doesn't have any itera...
5,231,823
11,744,404
vs2010 c++ tail call optimization
Consider the following code: int fac_aux( int x, int res ) { if( x == 1 ) return res; else return fac_aux( x - 1, res * x ); } int fac( int x ) { return fac_aux( x, 1 ); } int main() { int x = fac( 50 ); std::cout << x; return 0; } According to generated asm file everything is ok, tail call ...
when the original is compiled, the assembly at the callsite has partial inlining of fac_aux, specifically the x - 1 part, which is required for the tail recursion, but using fac_aux prevents the partial inlining and thus the tail recursion optimization: TestThin.fac_aux 013B1000 CMP ECX,1 013B1003 ...
5,232,011
5,248,824
Please provide me a stub of boost-multi-index - with std::cout
I am digging the net & head for multi index, but I didn't find any easy example. Can anybody provide me a small code like multi_index_container with-single_index- find something and cout the value?
I'll just copy and paste the code from your other, near-duplicate question: #include <string> #include <boost/multi_index_container.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/member.hpp> struct EnumStruct { EnumStruct(int const me, std::string const& mes, int const le, std::str...
5,232,026
5,232,234
Loading lots of image data (10^9 pixels) into memory
I'm extracting frames of video to a Surface array to be rearranged into a new video, trading the x dimension with time. Here are some examples of different kinds of effects that come out: http://www.youtube.com/view_play_list?p=B2540182DE868E85 The app always crashes with std::bad_alloc when I try to store 1280 frame...
First off, on a 32-bit platform, your hard limit for address space usage is going to be somewhere around 2GB (but possibly much less) - assuming you keep it all mapped at once. It's best to assume you won't be able to get more than maybe 512MB in contiguous memory, and 1-1.5GB or so in noncontiguous memory (ie, by maki...
5,232,067
5,245,119
Protect data within single program
In Windows would it be possible to protect data within a single program? I have been looking into CryptProtectData but whis is by user basis I would like something simular but on program basis. My program will have multiple users that require access to the same data, but the data is sentitive and I dont want any user t...
First of all, if your user has administrator privileges, there is no definite way to keep them out. Second, even if they didn't, you'd have to implement part of your software at ring 0, so it would have a higher privilege than the user, which would make it harder for them to get access to the process' memory or execut...
5,232,198
5,232,342
How does the capacity of std::vector grow automatically? What is the rate?
I had been going through the Book: C++ Primer, Third Edition By Stanley B. Lippman, Josée Lajoie, found 1 mistake in the program given under the Article 6.3 How a vector Grows Itself, this program missed a "<" in the couts: #include <vector> #include <iostream> using namespace std; int main() { vector<int> ivec; ...
The rate at which the capacity of a vector grows is required by the standard to be exponential (which, IMHO, is over-specification). The standard specifies this in order to meet the amortized constant time requirement for the push_back operation. What amortized constant time means and how exponential growth achieves th...
5,232,408
5,232,443
Trying to Learn C++, Tic Tac Toe program not working
I'm trying to learn C++ and I'm writing a Tic Tac Toe program. I'm really confused and it's late, but I just want to figure out what is going wrong so I can feel like I accomplished something. Any help would be great. Here's the full code not working at all. Thanks! http://codepad.org/fuC4JxBE These are the errors I ge...
The compiler error tells you anything you need to know. Add a , in line 82 after char whoWon edit regarding your new problem: you cannot pass multidimensional arrays like that. Remove the 3 in those brackets and the numCols in the declarations/definitions. If you really need to pass the array size, you need to pass it ...
5,232,712
6,491,196
questions regarding shared_from_this
I have a function which takes a shared_ptr<MyClass>. In some member function memfun of MyClass, I need to pass this to that function. But if I write void MyClass:memfun() { func(shared_ptr<MyClass>(this)) } I am assuming that after the call has ended the reference count will reach 0 and this will be attempted to be...
1) It depends on what you mean by "do this" as to whether or not you can. You can always construct a shared_ptr from a raw pointer such as this, but it won't share the reference count with another shared_ptr instance that was separately constructed from a raw pointer. You will thus need to use a custom deleter on one o...