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
4,422,493
4,423,324
how to force linker to use shared library instead of static library?
This is a quote from Linux programming book: % gcc -o app app.o -L. –ltest Suppose that both libtest.a and libtest.so are available.Then the linker must choose one of the libraries and not the other.The linker searches each directory (first those specified with -L options, and then those in the standard directories...
You could use -l option in its form -l:filename if your linker supports it (older versions of ld didn't) gcc -o app app.o -L. -l:libtest.so Other option is to use the filename directly without -l and -L gcc -o app app.o /path/to/library/libtest.so
4,422,507
4,422,554
Superiority of unnamed namespace over static?
How are unnamed namespaces superior to the static keyword?
You're basically referring to the section §7.3.1.1/2 from the C++03 Standard, The use of the static keyword is deprecated when declaring objects in a namespace scope; the unnamed-namespace provides a superior alternative. Note that this paragraph was already removed in C++11. static functions are per standard no long...
4,422,549
4,422,653
Best way to read a whole file opened in text mode into a string variable
These are the things I cannot change: The language is C++ However, the file is opened with the good old fopen() The file is not opened in binary mode This is what I have to do: Write a function that loads the entire file into a std::string. Lines should be separated only by \n and not other variants. This is what I...
After fread returns that it was unable to read the requested number of bytes, you should simply check ferror(mFile). If it's 0 (false) then fread just stopped at the end of the file and you should not tread this as an error. You should switch the two arguments though so you can get the number of bytes actually read: si...
4,422,560
4,422,579
how to use strcopy in c++
in c++ , i have a file named "Student.h" class LinkedList { private: class Student { public: int stId; char stName [20]; char stMajor[20]; double stAverage; Student * next; Student() { next = 0; } Student(int stId, char stName [20], char stMajor[20], double stAverage) { ...
this is a pointer in C++, not a reference as in Java. Plus what you need is strcpy() not strcopy() Try this strcpy(this->stName, stName); strcpy(this->stMajor, stMajor); P.S : In C++ it is always recommended to prefer std::string over C-style arrays A much cleaner version of your code would be something like ...
4,422,608
4,422,622
reallocating memory for an array c++
I was looking on C++ reference and found the dynamic memory management and was looking at the function that reallocate memory and I was wondering if this function could be used to make an array bigger I think that is what they mean but I really don't understand this line more_numbers = (int*) realloc (numbers, count *...
Only if the memory for the array was allocated via malloc(), calloc(), or realloc() earlier. Otherwise you're asking for trouble.
4,422,816
4,422,886
C++ crazy typedef : what is the point of allowing this syntax by the Standard?
The old familiar one: typedef int cute_int; //cute : common and familiar syntax. This syntax is perfect. No problem. Now, when we can write typedefs like above, then what is the point of allowing this syntax: int typedef crazy_int; //crazy : uncommon and unfamiliar syntax. Just to confuse programmers? Is this synta...
"The flip side of this is that you have to deal with old mistakes and with compatibility problems. For example, I consider the C declarator syntax an experiment that failed. Nevertheless, I adopted it for C++. The alternatives and improvements I considered at the time would not have improved matters. I rate is as a min...
4,422,893
4,422,937
Boost - unordered_set tutorial/examples/ANYTHING?
I'd like to use unordered_set in a project. However, documentation for it is either incomplete or just a technical reference, no examples. Can anyone provide links to online resources which deal with it? Books also welcome, preferably free. Google searching returned nothing of value. Thanks!
There's little docs on it because it behaves exactly like std::set, with the exception that it requires a hashing and equals function instead of a comparison function. Just look up examples for std::set, and replace them with std::unordered_set and you should be fine. If you need to write a hashing function, there are ...
4,422,933
4,422,997
Random access priority queue
Continuing List to priority queue I'm implementing a improved priority_queue with random access. template <class T, class Container = std::vector<T> > class Heap { public: Heap() {} Heap(const Container& container) { container_ = container; std::make_heap(container_.begin(), container_.end()); ...
Doesn't look that great to me: The unary constructor should take argument by const reference. The assignment operator doesn't check for self-assignment. The getContainer() method shows a lack of clarity in the interface - why would you simply expose the implementation detail like that? Most importantly: why do you wan...
4,423,079
4,423,110
C++ Decrease memory page size from 4096 bytes
Now on my system (debianx64)the page size is 4096 bytes. Is there any possibilty to decrease it? I would like to store in memory many small pieces but even for 1 byte reserved I can't use another 4095 because of thing added in 1st message here. Is it true or am I wrong? Is it possible to do it? Thx for replies.
No. 4096 is the smallest page size provided by the x86 platform. This is a limitation imposed by the CPU. It offers larger sizes (up to 4MB, depending on the mode), but this is normally selected by the operating system at boot time. What you can do is make a relatively large allocation as the backing store for an objec...
4,423,166
4,423,451
Translate to Objective-C from Objective-C++
I have this code in a .mm void MyMIDINotifyProc(const MIDINotification *message, void *refCon); which goes with this line MIDIClientCreate((CFStringRef)@"MidiMonitor MIDI Client", MyMIDINotifyProc, self, &client); and then the MyMIDINotifyProc gets called from CoreMIDI. Without changing the file extension to .m, I tran...
MIDIClientCreate expects an ordinary C function as its callback. You can't pass it an Objective-C method because the calling convention is different (in C terms, the first two parameters to an Objective-C method are self and _cmd - the selector - which will not be there for an ordinary C function). The usual way aroun...
4,423,361
4,423,401
Constructing a vector with istream_iterators
I recall once seeing a clever way of using iterators to read an entire binary file into a vector. It looked something like this: #include <fstream> #include <ios> #include <iostream> #include <vector> using namespace std; int main() { ifstream source("myfile.dat", ios::in | ios::binary); vector<char> data(is...
You want the std::istreambuf_iterator<>, for raw input. The std::istream_iterator<> is for formatted input. As for the end of the file, use the stream iterator's default constructor. std::ifstream source("myfile.dat", std::ios::binary); std::vector<char> data((std::istreambuf_iterator<char>(source)), ...
4,423,417
4,423,439
C++, function that loads text ignores last few lines with only some of the .txt files
I'm following theForger's Win API tutorial to load text files into an edit control. Sometimes the entire file is loaded correctly and sometimes the last part of it is left out, where 'part' is in one case 2 and a half lines and in another 10 lines o_O Here's how the files look: (I'm a new user so it's not letting me po...
Is it possible that your text file contains embedded NUL characters, and therefore the string pszFileText is terminated earlier than you expect? The SetWindowText() function stops reading after it encounters the first NUL terminator. Also, when reading from the file you will want to check that dwRead really is the numb...
4,423,497
4,423,521
Doxygen comments for private members and free functions?
Should I use Doxygen comments for private members and free functions? I come from the Java world, and I never added Javadoc for private members. Is this an acceptable practice in the C++ world?
I'd say it's pretty much language independent issue. You document members you want to have documented.
4,423,703
4,423,724
In C++, how does the expression, "*pointer++" work?
#include <iostream> using namespace std; int main () { int value = 1, *pointer; pointer = &value; cout << *pointer++ << endl; cout << *pointer << endl; } Why does the ++ operator not increment value?
Post-increment (++) has higher precedence than dereference (*). This means that the ++ binds to pointer rather than *pointer. See C FAQ 4.3 and references therein.
4,423,708
4,426,170
Problem in building my own module in omnetpp
I'm trying to write an application using the UDP module included in the inetmanet framework in omnetpp. The problem is that the files that I have to include don't get included in the linking phase. The errors are: opp_makemake bedo@ethereal:~/omnetpp/samples/Basic-Broadcast-Simulation$ opp_makemake --deep -f -I../inet...
Solved. I modified the makefile in the root directory to a simpler one, leaving all the compile and linking duties to the src's makefile. Thanks everyone
4,423,820
4,424,007
How can I determine the Unicode block of a character, specifically a Qt QChar?
In Java, I was able to determine if a particular character was for example, a Japanese Kanji using Unicode.blockOf(Character). I'm trying to do the same for a QChar, but couldn't find a relevant function to do this. I'm wondering if I just missed it, or will I have to roll my own, and if so - how?
There is QChar::Category however it does not provide everything you need. For checking whether a char is in certain range, you could write a function like this: bool inRange(QChar c, ushort b, ushort e) { return (c.unicode() >= b) && (c.unicode() <= e); } You could then use it like this: inRange(c, 0x3040, 0x309F...
4,423,989
4,424,390
Header imports and includes failing in XCode, cmath, objc-class.h, etc
I keep having issues with including basic headers such as cmath. It is most prevalent when using example projects. Example: #include <cmath> for instance gets a file not found, even though I can verify that the SDK I'm using has it: /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.2.sdk/usr/include/c++/...
What is the extension of your sourcecode file? .m or .mm? If it's .m, the compiler will assume you have a regular objective-C file, whereas .mm would imply an objective-C++ file. If its not a .mm file, the compiler may not be looking for C++ includes.
4,424,024
4,443,054
Using libcurl on visual c++ to login to a website
I'm using libcurl to open/save a remote file and parse html files and everything is going great. I was wondering if it's possible to use c++ and curl to login to a website (not a ssl one) and from there maybe manipulate the html that is generated? I would love to do that within my executable (not to use php). Thanks in...
I figured there is a way if anyone stumbles upon this. there's an example here: http://www.hackthissite.org/articles/read/1078 the website has a some what black hat approach but the example provided was useful.
4,424,141
4,424,259
C++ using for std and boost namespace best practice
Possible Duplicate: Do you prefer explicit namespaces or 'using' in C++? I am a C# developer, but my friend is a C++ one. He has shown me the code which is filled with calls like std::for_each and boost::bind. I used in C# and thought that using directives would rock for readability of the code and generally faster d...
First of all, let's make two distinctions: 1) There are using directives like using namespace std; and using declarations like using std::cout; 2) You can put using directives and declarations in either a header (.h) or an implementation file (.cpp) Furthermore, using directives and declarations bring names into the na...
4,424,168
4,424,208
Using boost::numeric_cast<>
When I want to convert between different integer types, it seems the best syntax is to use boost::numeric_cast<>(): int y = 99999; short x = boost::numeric_cast<short>(y); // will throw an exception if y is too large I have never used that; however the syntax is pretty straightforward, so all is well. Now suppose I wa...
You could probably do something like this: #include <limits> template<typename Target, typename Source> Target saturation_cast(Source src) { try { return boost::numeric_cast<Target>(src); } catch (const boost::negative_overflow &e) { return std::numeric_limits<Target>::lowest(); /* Or, befor...
4,424,216
4,424,239
C++ equivalent of "super"?
In Java, instead of using the scope operator, super is used ex: C++ -> GenericBase::SomeVirtualFunction(); Java -> super.someVirtualMethod(); Is there something like this in C++ or does this not make sense in C++ because of multiple inheritance? Thanks
There is a convention of defining a super typedef in every class.
4,424,309
4,590,551
Repeating groups in quickfix/c++
I am writing a program that uses the quickfix library. The documentation is very poor, so I am requesting the help of SO fellows. I have seen in the Group class that there are iterators. So I suppose that there is some STL-ish way of parsing repeating groups. Am I wrong? Can anybody provide a simple example for doing ...
There are iterators in FieldMap class which is a super class of Message and Group class. I'm not sure what do you mean by parsing repeating groups. Fix engine parses raw fix messages for you when they arrive and your callback gets parsed FIX message - which has internal maps of tags (key/value) for tags in message hea...
4,424,374
4,424,392
Determining if a number is prime
I have perused a lot of code on this topic, but most of them produce the numbers that are prime all the way up to the input number. However, I need code which only checks whether the given input number is prime. Here is what I was able to write, but it does not work: void primenumber(int number) { if(number%2!=0) ...
You need to do some more checking. Right now, you are only checking if the number is divisible by 2. Do the same for 2, 3, 4, 5, 6, ... up to number. Hint: use a loop. After you resolve this, try looking for optimizations. Hint: You only have to check all numbers up to the square root of the number
4,424,512
4,424,527
Kruskal's Algorithm in C++
I am looking for C++ Kruskal implementations to benchmark against my own... If you know a few good ones, please share!
There's boost::kruskal_minimum_spanning_tree. Prim's algorithm is there too if you want to compare against that.
4,424,531
4,425,241
Timing and Benchmarking
If I want to compare the speed of two algorithms, what's the best way? I am familiar with the mathematical way, and I know I don't full master it yet =/ I'm interested in knowing how to time two algorithms with good precision on Windows. What are the best APIs to use, is time() from stdio.h reliable or do I need someth...
Unfortunately this is not such an easy task. As previously mentioned QueryPerformanceCounter is a viable choice. Other possibilities are: - GetTickCount (not advisable, since its accuracy is worse than 30ms) - timeGetTime: By default it has a 15ms accuracy. This corresponds to the default time allocated by the task sch...
4,424,579
4,424,658
std::vector versus std::array in C++
What are the difference between a std::vector and an std::array in C++? When should one be preferred over another? What are the pros and cons of each? All my textbook does is list how they are the same.
std::vector is a template class that encapsulate a dynamic array1, stored in the heap, that grows and shrinks automatically if elements are added or removed. It provides all the hooks (begin(), end(), iterators, etc) that make it work fine with the rest of the STL. It also has several useful methods that let you perfor...
4,424,671
4,424,994
dynamic configuration with boost program_options
Is there a way to load a dynamic INI file like the one below. [basic] number_of_servers=3 [server1] ip=10.20.30.40 password=sdfslkhf [server2] ip=10.20.30.41 password=sdfslkhf [server3] ip=10.20.30.42 password=sdfslkhf Here the idea is that the servers that are defined here is very specific to the software's de...
Another, potentially more standard way, would be like this: [basic] number_of_servers=3 [server] name=server1 ip=10.20.30.40 password=sdfslkhf [server] name=server2 ip=10.20.30.41 password=sdfslkhf [server] name=server3 ip=10.20.30.42 password=sdfslkhf This way you don't need to worry about undefined section na...
4,424,709
4,424,805
randomized quick sort [crashes on some inputs]
I removed the codes because it's homework. If you actually needs the help, you can either look at the discussion I had with George B (below), or PM me. Hi guys. This is a homework assignment. I have tested it against other sorting algorithms, and Q.S. is the only one that is crashing on some random inputs. The program...
Hint: q is unsigned (the result of the partition function) so, q-1 is also unsigned what if q is zero? (It is homework so you have to figure it out I guess :) )
4,424,741
4,424,961
Aligned types and passing arguments by value
Passing aligned types or structures with aligned types by value doesn't work with some implementations. This breaks STL containers, because some of the methods (such as resize) take their arguments by value. I run some tests with Visual Studio 2008 and not entirely sure when and how pass by value fails. My main concern...
I think the only safe way to do this in general is to pass by reference. Some platforms (e.g. Xbox 360) support passing vector arguments in registers, but I don't think this is possible on x86. For the std::vector case, you'll need to make sure that the memory allocated is aligned to 16 bytes; otherwise you'll get cras...
4,424,793
4,424,846
Can someone help me understand this? int *& pr
I found this in a final exam: int a = 564; int* pa = &a; int *& pr = pa; cout << *pr; According to the multiple choice answer, the code is valid, and displays the value of a. But I'm confused about evaluation and precedence for line 3. Order of operations for C states that * and & have the same order. So, would it the...
It's a reference to a pointer. In C, you would express that as a pointer to a pointer. You could write something like this: // C++ style void update_my_ptr(int*& ptr) { ptr = new int[1024]; } // C style void update_my_ptr_c(int **ptr) { *ptr = malloc(1024 * sizeof(int)); } int main() { int *ptr; update_my_ptr(p...
4,424,818
4,424,865
What is an xtree is Visual C++?
I'm learning about the various data structures and templates available in C++. While include the header for vectors, I came across a header called xtree. I can't find any documentation on this header file from Microsoft (using VS10). My question is what exactly is this header used for and what does it contain? Is it ev...
AFAIK, it contains helper stuff used for implementing std::set and std::map, which have (this is the only sane way to achieve the required big-O performance characteristics and provide the required functionality) a tree structure internally. I can't guess why <vector> would need it - were you just browsing around in th...
4,424,825
4,425,221
Packing data into arrays as fast as possible
Im starting with an array of 100,000 bytes where only the lower 6 bits in each byte have useful data. I need to pack that data into an array of 75,000 bytes as fast as possible, preserving the order of the data. unsigned int Joinbits(unsigned int in) {}
// 00111111 00111111 00111111 00111111 // 000000 001111 111122 222222 void pack6( register unsigned char o, register unsigned char const *i, unsigned char const *end ) { while(i!=end) { *o++ = *i << 2u | *(i+1) >> 4u; ++i; *o++ = (*i & 0xfu) << 4u | *(i+1) >> 2u; ++i; *o++ = ...
4,424,915
4,424,921
Integers to const c++, c
I have integers which I put in a matrix in order to use them in a specific function in openCV. The matrix that I created is only cvMat and I want to use this matrix in the function. I'm getting an error: error: cannot convert ‘CvMat’ to ‘const CvMat*’ So how can I convert these ints to const in order to create that m...
" error: cannot convert ‘CvMat’ to ‘const CvMat*’ " The important thing there is the asterix at the end. That means the function you are calling wants a pointer. you can just take the address of your matrix and pass that, instead somefunction(myMatrix) it needs somefunction(&myMatrix). Don't worry about the const....
4,424,990
4,425,002
How do I make define and declare a variable using the default constructor in C++?
From my understanding of declarations and definitions, at the global scope: MyClass instance();//Declares a function that returns a MyClass MyClass instance;//Declares an instance of MyClass Is it possible to declare a variable and define it to use the default constructor at global scope? What if I was using a structu...
MyClass instance; will invoke the default constructor (i.e. the constructor with no parameters). This is counter-intuitive, because to invoke an overloaded constructor with parameters you would do the following: MyClass instance(param1, param2); Logic would tell you that you pass in an empty argument list to invoke t...
4,425,039
4,425,158
Locking via inheritance rather than composition
In most code I have written or reviewed, locking is achieved via composition, where a class owns a critical section or mutex: class MyClass { Mutex mMutex; }; and when mutable members can potentially be accessed via multiple threads, we acquire and release the lock via RAII like this: void MyClass::Method() { ...
Private inheritance might make a little more sense for this, since private inheritance is more or less a way to implement composition. however, I unless there's a need to inherit from Mutex (like if Mutex had protected members that needed to be accessed), I think that the more standard composition approach of making i...
4,425,050
4,425,069
Array of Int and *Char - C++
I want to use LZO to compress a array of int or byte. So I need to copy the int array to a *char then I will compress and save to file. And after i need do reverse operation. I will open the file read it with *Char and the decompress to array of int. I don't want to do a look in the *char to convert each int. Is the an...
You can treat the integer array directly as a (binary) character buffer and pass it to your compression function: char *buffer = reinterpret_cast<char *>(my_int_array); And similarly when you decompress into a character buffer, you can use it as an integer array: int *array = reinterpret_cast<int *>(my_char_buffer); ...
4,425,099
4,425,132
Binary Search Tree Questions
I'm trying to write a function to search a binary search tree for a value and return the TreeNode with the value. struct TreeNode { int value; struct TreeNode *pLeft, *pRight; }; TreeNode* SearchTree(int query); (For any node: this->pLeft contains nodes less the this->value, this->pRight contains nodes greate...
it would be something along the lines of: treenode* SearchTree(int query, treenode* node) { if(node == NULL) return NULL; else if(query == node->value) return node; else if(query < node->value) return SearchTree(query, node->pLeft); else if(query > node->value) return Sea...
4,425,102
4,425,820
Approach Using a Front Controller and IIS Serving Static Files?
Background An IIS ISAPI filter routes all requests to a front controller Java CMS for response. No physical file corresponds to a given URL. Motivations: Securing URLs Enforcing SSL This is a performance bottleneck serving static files such as audio and video. And, pooled application server processing threads are oc...
I believe that you should allow IIS to serve the static files. You can have HttpModule (or your filter) transferring the control back to IIS - it means that security enforcement code may have to be replicated. Yet another approach can be to make application server transfer control back to IIS to serve the file (securit...
4,425,212
4,425,493
Custom comparator via explicit constructor for sorting std::set
I've got a set of pointers which I would like to iterate over in a deterministic manner. Obviously if I use the default sort order for set, this will be based on the pointers memory addresses which can be different each time the program runs. So I define a custom comparator which I want to use, but I don't want to chan...
All the above is valid. A possible solution is to customise std::less itself using template specialisation: namespace std { template<> struct less< TestClass*> { // functor for operator< public: bool operator()( TestClass* const &_Left, TestClass* const &_Right) const { // apply ...
4,425,323
4,425,406
What is (are) the standard key(s) for a gui widget's action?
I know on Widows, this key is space, for example, space will perform the button's click which is its action,same for radio buttons etc. Is this the standard. If not, what is? Thanks
Yes, on a MS Window system these keys are handled by windows OS for navigation. TAB move input focus to the next control. TAB + SHIFT move input focus to the previous control. ENTER Activate a button/menu. SPACE check/uncheck a checkbox. ALT activate the first menu group. Use arrows to navigate in menu. UP/DOWN in a ...
4,425,356
4,436,765
What other data structures are available in the C++ STL?
I'm already aware of the following: arrays bitsets hash maps and sets regular maps and sets iterators lists pairs tuples queues, deques, and priority queues stacks valarrays vectors Is there any other type of data structure available in the C++ library. What I'm specifically looking for is graphs, but I'd also like t...
The STL is divided into three parts: Containers Iterators Algorithms You have obviously found the containers part and you have probably used the iterators associated with the containers. But there is even more to the iterators than you have found. The algorithms sections is linked to the containers via iterators. But...
4,425,422
4,425,427
Why parentheses are important in function pointer declaration?
I don't understand why the declaration below is accepted: typedef void (*_tStandardDeclaration)(LPVOID); while the following doesn't: typedef void *_tDeclarationWithoutParenthesis(LPVOID); typedef void* _tAlternateDeclaration(LPVOID); I am using MSVC6 (I know it's obsolete and non-standard, but it's needed to...
The pointer symbol binds to the type by default, so the function pointer needs the parenthesis to indicate that the pointer is actually on the name and not on the return type.
4,425,761
4,426,496
Can I create a new struct on the heap without defining a constructor?
I understand that there are very few differences between structs and classes in c++ (two?). Be that as it may, I've been instructed to use structs to define simple little things like nodes that might not need member functions (despite the fact that I could technically include include member functions). For instance I m...
In this case, however, is it possible to create a new instance of this struct on the heap, or would I need to define a constructor? Is there a way to create things on the heap without the new operator? As answered before, you can create a new instance on the heap either via new or with malloc. Or, better yet: is it ...
4,425,764
4,426,061
What are some good free, open sourced, cross platform game engines?
I have a great idea for a 3D game, but I do not want to start from scratch with OpenGL. I also do not want to reinvent the wheel. I found OGRE, and it seemed like it was perfect for my needs, except it lacked physics and audio. I do not need crazy graphics, shaders or high polygon counts, but the world will be very big...
Have a look at some of the answers from this question. You may find some useful libraries listed. If you're open to alternatives to C++, you can check out this answer on the game development stack exchange website. The answer covers lots of options for game engines, physics engines and Graphics/Sound engines. Most list...
4,425,901
4,426,077
Blitting a transparent .PNG image onto a screen
Hi there I have a image with a black rectangle drawn on it, and its background is transparent. This file is saved as a png (clear.png). Then I have another image which is just a solid red background saved as a jpeg (background.jpeg). What I was trying to do is make so that the black rectangle in clear.png show up on to...
Make sure to init SDL_image and blit both bitmaps to the screen: /*Transparent image*/ #include "SDL/SDL.h" #include "SDL/SDL_image.h" #include <iostream> using namespace std; int main(int argc,char *argv[]){ SDL_Surface *screen = NULL; SDL_Surface *background = NULL; SDL_Surface *transparentimage = NULL; ...
4,425,965
4,426,107
Destructor not called after destroying object placement-new'ed
I had no clue why this doesn't work. The following Function is created by placement new. A function is provided that checks whether it should be destructed, and if so, calls its destructor manually. Here is the testcase where it seems the destructor is never called: /* Represents a function at runtime */ class Functi...
This is because ~Function(); in not a destructor call syntactically here. Use this->~Function(); instead. ~Function(); is parsed as an operator ~ and creation of the Function object on the stack. Function class has an operator bool that's why this will be compiled.
4,425,981
4,425,993
What is platform useragent of the windows platfom?
I am posting the requesting request uisng "POST" method, In mac platform uaser agent is 10.6.2. But the in windows waht is platform user agent.
The user agent string depends solely on the browser or whatever client you are using to make the request. It has nothing to do with the operating system, though most browsers will include some information about the OS version. For example, on my version of Firefox it is: Mozilla/5.0 (Windows NT 5.1; rv:2.0b7) Gecko/201...
4,426,131
4,436,206
Maximum Weight / Minimum Cost Bipartite Matching Code in Python
I'm searching for Python code for maximum weight / minimum cost matching in a bipartite graph. I've been using the general case max weight matching code in NetworkX, but am finding it too slow for my needs. This is likely due to both the fact that the general algorithm is slower, and the fact that the NetworkX soluti...
After some further investigation, I've found the following two modules particularly helpful (http://pypi.python.org/pypi/pyLAPJV/0.3 and http://pypi.python.org/pypi/hungarian). They are both algorithms implemented in C++ with Python bindings, and run much faster than the NetworkX matching implementation. The pyLAPJV ...
4,426,141
4,426,194
asynchronous function call C++0x
I am testing on the std::async function with the code from http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-8-futures-and-promises.html int calculate_the_answer_to_LtUaE(){ sleep(5); cout << "Aaa" << endl; } std::future<int> the_answer=std::async(calculate_the_answer_to_LtUaE); t...
If you read the section of the thing you linked to about 'launch policies' you'll see that I'm exactly right in my comment. The behavior you're seeing is perfectly permissible. You can force what you want using the launch policy like so: std::future<int> the_answer=std::async(std::launch::async,calculate_the_answer_to...
4,426,290
4,426,300
C++ Library Does Not Link in Release Configuration (VS2010)
I've been trying to get static libraries (.lib files) to work in VS2010, and I have it working perfectly in the debug configuration. When I try to compile it under the release configuration, however, I get the error error C1083: Cannot open include file: 'Library.h': No such file or directory. Here's the current scena...
Not sure about VS2010... but the debug and release modes probably have different library settings... You can inform the compiler to link thru code by specifying the following #pragma comment(lib, "library.lib") // no ; is needed That will make it link in both debug and release
4,426,303
4,426,311
Invoking Destructor Approach Comparison
I'm just curious to know if there is any significant/serious difference in these three approaches of invoking destructor. Consider the following code. Please also consider the two cases mentioned in main(). class Sample { public: ~Sample() { cout << "destructor called" << endl; } void destroyAp...
Yes, there is a huge difference between these approaches: In destroyApproach1, you only call the destructor of the object; you don't actually free the memory that it occupied. In destroyApproach2 and destroyApproach3 you call the destructor of the object and you free the memory that the object occupied (by using the...
4,426,474
4,426,487
Is passing pointer argument, pass by value in C++?
Is passing pointer argument, pass by value in C++? Since i see that any change to the pointer as such is not reflected outside the method. The changes i do by dereferencing the pointer is reflected though. In that case, is it acceptable/standard procedure to use pointer to pointer as argument to a function to modify t...
Yes to both. Pointers are passed by value as anything else. That means the contents of the pointer variable (the address of the object pointed to) is copied. That means that if you change the value of the pointer in the function body, that change will not be reflected in the external pointer that will still point to t...
4,426,476
4,426,485
Seeing what class an object is
If I have a pointer to a base class A in C++, how would I be able to tell in my code that the pointer is to a derived class B or C?
Assuming the base class A is polymorphic (i.e. it has at least one virtual function), you can use dynamic_cast. Given an A* ap;: if (B* bp = dynamic_cast<B*>(ap)) { // the object is a B } else if (C* cp = dynamic_cast<C*>(ap)) { // the object is a C }
4,426,802
4,426,831
Boost Asio async_wait handler
The boost asio deadline_timer async_wait function is taking handler of the form : void handler(const boost::system::error_code& error) How could I define a handler which takes in const boost::system::error_code& error and also an argument of type int ? boost::asio::deadline_timer t(io_service); t.async_wait(handler);...
You could use Boost.Bind to provide a value for the first argument : t.async_wait(boost::bind(handler, 0, _1)); Here, the handler will be called with a 0 as its first argument and the error_code will simply be forwarded as a second argument.
4,426,944
4,426,977
error C3646: 'closure' : unknown override specifier
I got the following error: error C3646: 'closure' : unknown override specifier The code: void BaseOperator::mousebutton_cb(EventObject* sender, EventArgs* calldata, void* closure) { xd3D::Operation::Operator::BaseOperator* operator = (xd3D::Operation::Operator::BaseOperator*)closure; MouseButtonEventArgs* e = ...
operator is a keyword. The sequence operator = tries to declare an assignment operator which in your case would have a pointer parameter type. And your compiler wants to parse the very last closure as a special specifier like override (afaik an extension of MSVC), const or such. Rename the variable to something else, ...
4,427,144
4,427,204
Does specifying a method/constructor explicit mean that it can't be called implicitly?
Does specifying a method/constructor explicit mean that it can't be called implicitly? I mean if a constructor is specified as explicit, can't it be called implicitly by some operator like = or other methods like converter constructor? In that case, does specifying a method/constructor to be explicit have any importanc...
class MyClass { int i; MyClass(YourClass &); }; class YourClass { int y; }; void doSomething(MyClass ref) { //Do something interesting over here } int main() { MyClass obj; YourClass obj2; doSomething(obj2); } In the example since constructor of MyClass is not specified as explicit,...
4,427,228
4,427,272
declaration as condition - adding parentheses causes errors
Why is this ok: if(int i = 1) { } ...whereas the following produces errors? if((int i = 1)) { } Under g++ (4.4.5) the latter gives: test.cpp:7: error: expected primary-expression before ‘int’ test.cpp:7: error: expected ‘)’ before ‘int’ test.cpp:9: error: expected ‘)’ before ‘else’ test.cpp:13: error: expected...
It's because of the C++ standard, 6.4 p1. Selection statements choose one of several flows of control. selection-statement: if ( condition ) statement if ( condition ) statement else statement switch ( condition ) statement condition: expression type-specifier-seq declarator = assignment-expression
4,427,244
4,427,292
Rationale for difference in "default" access-specifier for a base class
I know that there're few differences between struct and class in C++. I also understand the reason(s) for few of the difference(s). Like this one, Members of struct are public by default; members of class are private by default. The reason why members of struct are public by default, is to make C++-struct compatible w...
I'm not sure why you think it's a twist, you have consistency with member sub-objects and base class sub-objects. They are both public for classes declared with struct and private for classes declared with class. Simple and easy to remember.
4,427,308
4,427,867
Assigning an array of arrays in C/C++
Hi I'm not a "native" C/C++ programmer. I'm able to write some basic things and do a coding that is common to other languages. But I have this problem and I don't know even how to ask different then explaining it (thus google searching won't fit me). I've got in my code typedef float point3[3]; And now I'm initilizin...
I'd like to expand Robin Welch's answer in a way which allows to stay compatible with the point3 typedef: typedef float point3[3]; struct Point { Point(float x, float y, float z) : x_(values_[0]), y_(values_[1]), z_(values_[2]) { values_[0] = x; values_[1] = y; values_[2] = z; ...
4,427,634
4,427,801
need help to generate keystrokes into existing application in Linux environment using C++
I need help to generate keystrokes in my existing application in LINUX environment. I am fully aware that there are libraries in Dev C++ which do exactly what I want but in Windows and I need something like that in Linux. I have googled a lot, but could not able to find any solution. Below are the code of Dev C++ libr...
What you want is create and initialize XKeyEvent struct and send it with XSendEvent. Be sure to check man xkeyevent and man xsendevent From man xkeyevent: typedef struct { int type; /* KeyPress or KeyRelease */ unsigned long serial; /* # of last request processed by server */ ...
4,427,683
4,427,855
Template function's priority is different between vs2005 and vs2010
class Foo { friend class SquirrelVM; public: Foo() { cout << "Ctor" << endl; } virtual ~Foo() { cout << "Dtor" << endl; } Foo(const Foo & o) { cout << "const Ctor" << endl; } template <typename _ty> Foo(const _ty & val) { cout << "T const Ref" << endl; } template <typename _ty> Foo(_ty & val) { cout << "T Ref"...
Foo(_ty & val) with _ty being Foo is a better match because it will have parameter type Foo& matching a non-const Foo lvalue, while the other has a const that will make it a bit worse match. There was some confusion during the made-up process of C++0x and before as to whether templates can be used to copy an object of ...
4,427,738
4,427,791
Allocate memory for a vector
Can someone give me an example of how to allocate memory for a vector? A couple of lines is all I need. I have a vector that takes in 20-30 elements.. but when i try to cout it and compile it i only get the first couple of entries..
An std::vector manages its own memory. You can use the reserve() and resize() methods to have it allocate enough memory to fit a given amount of items: std::vector<int> vec1; vec1.reserve(30); // Allocate space for 30 items, but vec1 is still empty. std::vector<int> vec2; vec2.resize(30); // Allocate space for 30 it...
4,427,759
4,427,888
In C++, why struct is in fact class?
The other topic and responses there made me ask this question: Why does C++ allow struct to behave just like class? At one hand, C++ made it compatible with C-struct by making it's members public by default (just like in C), while on the other hand, it made it look-like class by allowing it to be inherited from classe...
From a language point of view, structures and unions are just types of class. It makes the language specification simpler if there are fewer concepts (with a small letter 'c') and it also makes specifying the language less error prone as it is less easy to miss something 'obvious' out if every common property had to sp...
4,427,763
4,430,742
Any tools to monitor the changes made by an application?
I want to monitor the changes made by my installer, and I found the processmonitor is useful, But it just get too many information, and really hard to retrieve what I need. Is there any better solution on monitoring ? Like what folder, file, registry the application created ? Thanks !
I often used InCtrl 5 (it's old but usefull).
4,427,897
4,427,924
Get the decimal point
How to get decimal point of a number? For example: If I have 1.5 how to get the 5 number?
int result = static_cast<int>(fmod(number, 1)*10); EDIT: or simpler and probably faster: int result = static_cast<int>(number*10)%10; EDIT: to make it work also for negative numbers you may do: int result = abs(static_cast<int>(number*10))%10;
4,428,023
4,428,083
enable_shared_from_this (c++0x): what am I doing wrong?
I'm just toying around with the smart pointers in the upcoming new c++ standard. However I fail to grasp the usage of the shared_from_this function. Here is what I have: #include <iostream> #include <memory> class CVerboseBornAndDie2 : public std::enable_shared_from_this<CVerboseBornAndDie2> { public: std::string ...
It is a precondition of using shared_from_this that there must exist at least one shared_ptr which owns the object in question. This means that you can only use shared_from_this to retrieve a shared_ptr that owns an object to which you have a reference or pointer, you cannot use it to find out if such an object is owne...
4,428,509
4,428,612
How to create derived classes from a base class using template programming in C++?
I need to create a number of classes (more than 50) from a base class, where the only difference is in the names of the derived classes. For example, my base class is defined as: class BaseError : public std::exception { private: int osErrorCode; const std::string errorMsg; public: int ec; BaseError ()...
I suppose you want to create a class hierarchy so that you can use dynamic dispatch in your catch clauses (relying on the compiler to find out the correct type) to implement custom error handling. You could do this by keeping the BaseError class as it is and then adding a template class for which you then provide multi...
4,428,535
4,428,704
Performance consequence of volatile member functions
I found a 2001 article on Dr Dobbs: volatile - Multithreaded Programmer's Best Friend. I've always found 'volatile' somewhat useless - at least as a qualifier on variables - as access to variables shared between threads always go through some kind of library layer anyway. Nonetheless, marking class instances, and metho...
No, local variables will not be assumed as volatile in a volatile method, pretty much the same way as the local variables are not assumed const in a const method. All the members of the class will be treated as volatile within the volatile method, pretty much the same way as all nonmutable members are treated const i...
4,428,589
4,428,622
Is it possible to put a function declaration within an unnamed namespace?
I have a file with a set of functions. For one of the functions, I want to write a helper function which basically takes a char * and skips all whitespaces. Here's how I thought it should be done: namespace { const int kNotFound = -1; void SkipWhitespace(const char *s); // forward declaration - doesn't seem to...
You have to define it in the anonymous namespace as well: namespace { ... void SkipWhitespace(const char *s); // forward declaration - doesn't seem to work? } void foo(const char *s1, const char *s2) { ... } namespace { void SkipWhitespace(const char s*) { for (; !isspace(s); ++s) {} } } ...
4,428,819
4,428,858
C++ arrays as pointers question
Why this is possible: char buf[10], *pbuf = buf, **ppbuf = &pbuf; and this isn't: char buf[10], **ppbuf = &buf; As I understand, the second line is just a shorthand of the first one.
&buf has the wrong type. &buf is a pointer to an array of 10 char. ppbuf has to be initialized with a pointer to a pointer to a char. In the first initialization, while buf denotes an array, it decays to a char* pointing to its first element so the initialization is valid. You also can't do: char buf[10], **ppbuf = &(&...
4,429,040
4,628,944
Enumerating audio adapters in WinAPI
What's the best way to enumerate audio adapters (sound cards) in Windows Vista and above using WinAPI (C++)?
The simplest way i found is using WMI with this query "SELECT * FROM Win32_SoundDevice".
4,429,056
4,429,082
Bit manipulation for big integer classes?
I'm having a problem coming up with an algorithm for a big integer class in C++. My initial idea was using arrays/lists, but it's very inefficient. I then discovered about things like the following class: http://www.codeproject.com/KB/cpp/CppIntegerClass.aspx However, I find that approach really confusing. I don't know...
Start by reading up on binary numbers in general. That page shows how the common arithmetic operations (addition, subtraction etc) work on binary numbers, i.e. how the numbers are manipulated bit by bit to get the desired result. Mapping that into a programming language such as C++ should be pretty straight-forward o...
4,429,141
4,429,917
a DLL need to access symbols of its application
In C++, is it possible for a DLL to access some symbols of the application that loaded it ? I have an application that load plug-ins (dll), and these plug-ins need to access some API of the application. Is it possible to achieve this without creating a new DLL that share this API ? Is a struct of function pointers suit...
Another vote for passing a callback interface into the plug-in DLL. I.e. the callback interface... class IHostApplication { public: virtual bool Log(const wchar_t* ip_log_string) = 0; }; The DLL plugin interface class IPlugin { public: virtual void InitializePlugin(IHostApplication *ip_host) = 0; ...
4,429,272
4,429,286
C++: Function variable declarations, how does it work internally?
This has been bothering me for a long time now: Lets say i have a function: void test(){ int t1, t2, t3; int t4 = 0; int bigvar[10000]; // do something } How does the computer handle the memory allocations for the variables? I've always thought that the variables space is saved in the .exe which the co...
Local variables like those are generally implemented using the processor's stack. That means that the only thing that the compiler needs to do is to compute the size of each variable, and add them together. The total sum is the amount to change the stack pointer with at the entry to the function, and to change back on ...
4,429,326
4,429,381
Strassen matrixes multiplication source code
I need to Strassen source code.Please help me.
If you need to Strassen your source code, you should first check if doing that is legal in your jurisdiction. Then you need to verify whether you need to be a licensed practitioner to do so. If a license is required and you are not one, you need to find a licensing practitioner - I would recommend Yellow Pages or Googl...
4,429,401
4,429,512
Lua C++ development files on Linux (/usr/bin/ld: cannot find -llua5.1)
I am building a C++ application that embeds the Lua scripting engine. I am developing on Linux (Ubuntu). I have already installed Lua on my dev machine (by imstalling the lua5.1 package). I can run the Lua intepreter succesfully (via the cmd line). However, when building, I get the following link error: /usr/bin/ld: ...
Install the liblua5.1-dev package, and if that does not work compile Lua from sources. Or you can try -llua instead of -llua5.1.
4,429,417
4,430,166
What's the best strategy for typedef'ing shared pointers?
I have a quick question regarding the use of typedefs for lengthy templates. The crux: I've found myself in something of a pickle—there doesn't seem to be a good place to place typedefs except local to client functions. While there are similar SO questions (see here for example), none seem to address this exactly. Plea...
I don't like a library dictating the use of a particular smart pointer, but I tolerate it if it is necessary. If you wish to force users to always use a shared_ptr to manipulate a widget, it's impossible, so don't even bother trying. On the other hand, if you have a method from Widget which returns a boost::shared_ptr<...
4,429,739
4,429,776
c++ include redeclaration
I have two libraries in my include path: /usr/local/include/lib1/ /user/include/lib2/ Both define a header file "vec.h" and I get the following error: /usr/local/include/lib1/vec.h:22: error: redeclared with... How to handle this?
You do: #include "lib1/vec.h" #include "lib2/vec.h" Your makefile should then have include paths up to the lib1 and lib2. -I /usr/local/include /user/include You should ensure that the headers have guards around them to make sure they don't get declared twice. You should see something like: #ifndef MYHEADER_H_ab2592...
4,429,881
4,430,005
Removal of special character in string in C++
I have the followoing string myStr = "myname-abc"; string myStr1 = strstr(myStr.c_str(), "-"); now in myStr1 i have -abc. But i don't want "-" infront of it i want to have "abc" how do i do that using string data type. Thanks for help.
size_t pos = myStr.find('-'); if (pos != std::string::npos) { myStr1 = myStr.substr(pos + 1); }
4,430,045
4,430,083
How to get iterators if template type is a template itself?
My first template class try for a simplified converter from some boost compressed_matrix to PETSc Sparse AIJ format but I am running into problems with the iterator typedef declerations at the very start. So T is compressed_matrix, naively using the below code does result in compile time errors, how should one define t...
You have to explicitly tell the compiler that T::iterator1 is a type name (as opposed to a static variable, or something along those lines). typedef typename T::iterator1 i1_t;
4,430,172
4,432,102
FFTW: signal consists of noise after IFFT
After doing FFT and IFFT I can hear only noise in my headphones... Here is the code: double* spectrum = new double[n]; fftw_plan plan; plan = fftw_plan_r2r_1d(n, data, spectrum, FFTW_REDFT10, FFTW_ESTIMATE); fftw_execute(plan); fftw_destroy_plan(plan); plan = fftw_pla...
I don't see where you are normalizing your output. You must divide your output values by the number of elements in the data array to normalize the data back to original range of values. See the FFTW Manual 4.8.2, last paragraph (I have V3.2 manual).
4,430,223
4,430,404
Initialize member references correctly
class Temp { public : Temp(X& x): x_(x) {} Temp(X& x, Y& y) : x_(x), y_(y) {} ... private: X& x_; Y& y_; } I got the error because in case of Temp(X& x): x_(x) the reference y_ is not initialized. What is the common practice to write such a class correctly ?
I will suggest another approach, even though that may be not what you are looking for. It doesn't use reference variables (memory pointers instead), it also doesn't use boost, but it will allow you to keep both constructors without spending any more memory resources. #include <iostream> class Temp { public : ...
4,430,388
4,431,638
Access violation in a multithreaded application, C++
I am not very good in multithreading programming so I would like to ask for some help/advice. In my application I have two threads trying to access a shared object. One can think about two tasks trying to call functions from within another object. For clarity I will show some parts of the program which may not be very...
The address of the access violation is a very small positive offset from 0xcdcdcdcd Wikipedia says: CDCDCDCD Used by Microsoft's C++ debugging runtime library to mark uninitialised heap memory Here is the relevant MSDN page. The corresponding value after free is 0xdddddddd, so it's likely to be incomplete initializa...
4,430,504
4,430,528
C++ method that can/cannot return a struct
I have a C++ struct and a method: struct Account { unsigned int id; string username; ... }; Account GetAccountById(unsigned int id) const { } I can return an Account struct if the account exists, but what to do if there's no account? I thought of having: An "is valid" flag on the struct (so an empty one...
You forgot the most obvious one, in C++: bool GetAccountById(unsigned int id, Account& account); Return true and fill in the provided reference if the account exists, else return false. It might also be convenient to use the fact that pointers can be null, and having: bool GetAccountById(unsigned int id, Account* acco...
4,430,571
4,430,641
Non voluntary context switches: How can I prevent them?
I have a small application that I was running right now and I wanted to check if I have any memory leaks in it so I put in this piece of code: for (unsigned int i = 0; i<10000; i++) { for (unsigned int j = 0; j<10000; j++) { std::ifstream &a = s->fhandle->open("test"); char temp[30]; a.getl...
Voluntary context switch occurs when your application is blocked in a system call and the kernel decide to give it's time slice to another process. Non voluntary context switch occurs when your application has used all the timeslice the scheduler has attributed to it (the kernel try to pretend that each application has...
4,430,780
21,827,261
How can I extract the file name and extension from a path in C++
I have a list of files stored in a .log in this syntax: c:\foto\foto2003\shadow.gif D:\etc\mom.jpg I want to extract the name and the extension from this files. Can you give a example of a simple way to do this?
To extract a filename without extension, use boost::filesystem::path::stem instead of ugly std::string::find_last_of(".") boost::filesystem::path p("c:/dir/dir/file.ext"); std::cout << "filename and extension : " << p.filename() << std::endl; // file.ext std::cout << "filename only : " << p.stem() << std::endl...
4,430,839
4,431,174
SSE: convert __m128 and __m128i into two __m128d
Two related questions. This is what my code needs to do with fairly large amount of data. It is done inside inner loops and the performance is important. Convert and array of __int32 into doubles (or convert __m128i into two __m128d). Convert and array of floats into doubles (or convert __m128 into two __m128d). Basi...
The intrinsics _mm_cvtepi32_pd and _mm_cvtps_pd convert the values to double. This should be the loop: __m128i* base_addr = ...; for( int i = 0; i < cnt; ++i ) { __m128i epi32 = _mm_load_si128( base_addr + i ); __m128d v0 = _mm_cvtepi32_pd( epi32 ); epi32 = _mm_srli_si128( epi32, 8 ); __m128d v1 = _mm_c...
4,430,906
4,430,973
Avoiding RTTI in a design
I have a Visual Studio 2008 C++ application with several types of objects that derive from a common base. For example: class Base { public: std::string Time() const { /*return formatted time*/; }; private: SYSTEMTIME time_; }; class Foo : public Base { public: const char* FooFunc() const { return "Hello fr...
First, there is a problem with the Bar class. Since you're using a std::vector< Base >, you're object are sliced (that is a copy of the Base part of the object is inserted in the vector, not you're object). You'll want to use a std::vector< Base* >, that is a vector of pointers. Secondly, to do what you want, you can u...
4,430,976
4,431,044
How to stop large float numbers from being output in exponential form. (scientific notation?)
I have a program that calculates population growth. It seems to be working but after when the population exceed 1 million it is output as a decimal number raised to a power of ten. (is this called scientic notation? exponential form? i forget.) Is there anyway to output the data as a full number? Here is the code for t...
The std::fixed manipulator, used in conjunction with std::setprecision should help you (remember to #include <iomanip>).
4,431,149
4,431,164
Releasing a pointer that points a static array
I have the following array declared inside a header file. static const float elementsArray[300] = { ... }; I want to do: float *elementsPointer = &elementsArray[0]; I'm sure I can do that, but... Do I need to release elementsPointer with delete? Do I need to do anything else? Thank you.
No. The memory that elementsPointer points to is statically allocated and does not require a call to free.
4,431,256
4,431,299
Am I missing something in my function?
This is what I have so far and I keep getting an error. Any help? void ReverseString(char* string) { int len = strlen(string); for(int i = 0; i < len; i++) { string[i] = string[len-i]; } }
When i is 0 you'll be accessing string[len] which is incorrect as the valid index in an array of length len are [0,len-1] If I understand you intent correctly you are trying to reverse the string but I can see a few things missing: You are not swapping. Also the swapping should happen for one half of the array, not...
4,431,332
4,431,454
Strange integer reading from file C++
Really tried to look around, used search. Used Google, tried many ways, but I can't figure this out. (And I guess it's really easy for anyone who 'speaks fluent C++'.) It's a really easy homework, but I have no idea why does it work this way. Here is the code: int temp; string fname; cout << "Kerem a fajlnevet: "; ...
you have stuff like: for (int i=1; i <= szam_helyseg; i++) { for(int j=1; j <= szam_madar; j++) { f >> matrix[i*szam_madar + j]; } } But array indices count from 0, so the easiest way to do stuff is for (int i=0; i < szam_helyseg; i++) { for(int j=0; j < szam_madar; j++) { f >> matr...
4,431,505
5,749,285
SSE2: Double precision log function
I need open source (no restriction on license) implementation of log function, something with signature __m128d _mm_log_pd(__m128d); It is available in Intel Short Vector Math Library (part of ICC), but ICC is neither free nor open source. I am looking for implementation using intrinsics only. It should use special ra...
Take a look at AMD LibM. It isn't open source, but free. AFAIK, it works on Intel CPUs. On the same web page you find a link to ACML, another free math lib from AMD. It has everything from AMD LibM + Matrix algos, FF and distributions. I don't know any open source implementation of double precision vectorized math func...
4,431,522
4,431,606
Given 2 16-bit ints, can I interleave those bits to form a single 32 bit int?
Whats the proper way about going about this? Lets say I have ABCD and abcd and the output bits should be something like AaBbCcDd. unsigned int JoinBits(unsigned short a, unsigned short b) { }
#include <stdint.h> uint32_t JoinBits(uint16_t a, uint16_t b) { uint32_t result = 0; for(int8_t ii = 15; ii >= 0; ii--){ result |= (a >> ii) & 1; result <<= 1; result |= (b >> ii) & 1; if(ii != 0){ result <<= 1; } } return result; } also tested on ideone here: http://ideone.com/lXTq...
4,431,624
4,432,351
C++ with D3DX9 - Memory size keeps increasing at a rate of 10 MB/sec - Why?
I'm working on a 3D engine as school project. I've installed virtual leak detector to get rid of memory leaks (and it worked, since I'm not getting any of those dumps anymore). Recently, I accidentally left my app running for 5 minutes... And my PC got slow as hell. I've tracked down the issue by commenting out lines a...
As Sanjit says, you must use delete[] to delete arrays - and as DeadMG says, a RAII container is the best-practice way not to mess up freeing your resource. However, although it's not instantly obvious from the docs, apparently all Direct3d resources (including the IDirect3d9Texture that D3DXCreateTextureFromFile creat...
4,431,637
23,676,662
Hiding mouse cursor with glfw
I'm working with a game made with glfW and running in Ubuntu. My problem is that hiding the mouse cursor with the line glfwDisable(GLFW_MOUSE_CURSOR); causes some machines to simply disregard the mouse input, and thus breaks the game. Has anyone faced this problem? If so, what was your workaround?
Since glfw 3.0 the API call has changed, you must use glfwSetInputMode with a pointer of your window. glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); For more information see http://www.glfw.org/docs/3.0/moving.html
4,431,644
4,431,735
C++ big header files (4.5MB or more) with huge static arrays
I have three big header files (4.5MB and more), with huge static arrays inside. I need to add these header files to a C++ Android native code project and I don't know if this is the right way. I'm thinking that these are big files and contains big arrays. I don't know if they will generate a big lib.so and if arrays wi...
I would strongly advise against defining static arrays (i.e., actually specifying static int foo[8056]) in header files. It's much better to declare them as extern in the header file, and define them in a single C or C++ source file. Every source file in which those headers are included (even indirectly) will generate...
4,431,693
4,432,592
Using function objects in parallel_for
I just barely learned how to use a function in parallel. The following line of code calculates the square value of an index and places it in an array (called squares) at that index. The parallel_for function is available in Visual Studio 2010, as part of the Concurrency namespace under the header. parallel_for(static_...
Any lambda expression can be thought of as an anonymous version of the corresponding function object. In your example, your functor works just fine, as below: parallel_for(static_cast<size_t>(0), count, Squares); From the MSDN docs: A lambda expression is a programming technique that is related to anonymous fun...
4,431,964
4,431,984
WaitForSingleObject Does Not Time Out - C++
My console application calls WaitForSingleObject in the parent thread with a timeout value of 5 seconds. dwObjectWaitState = ::WaitForSingleObject( s_hRxDataEvent, 50000L ); After configuring the physical environment (i.e. no code changes), so that the event will never get signaled, I set a breakpoint at the following...
The timeout is in milliseconds. 50000 is 50 seconds, not 5 seconds.
4,432,005
4,432,652
Are Visual C++ library DLLs localized?
We include the Visual C++ runtime libraries when deploying our c++ application on Windows, i.e. using merge modules like Microsoft_VC90_CRT_x86.msm. Do we need a localized version of those libraries when targeting other languages (Spanish, Portuguese, German, etc.), or are they generic? If you could provide a link "str...
The CRT is not localizable. There are a handful of error messages, all hard-coded in English with #define statements. You'll find them in crt\src\cmsgs.h The only one that a user is ever liable to see is This application has requested the Runtime to terminate it in an unusual way. Please contact the applicatio...