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,580,189
4,580,208
Subclass casting, and pointer address changes
I've been using multiple inheritance in c++ for quite a long time, but only realised today that this could imply that the pointer addresses could be different when referencing them as one of the subclasses. For example, if I have: class ClassA{ public: int x; int y; ClassA(){ c...
That's a perfectly standard use of multiple inheritance, and it will work on any compliant compiler. You should however note that an explicit cast in unnecessary in the first case, and that the 'C style cast' could be replaced by a static_cast in the second. Is it possible to force the order in which the subclass loca...
4,580,416
4,580,451
Libraries for making a voice chat application
My development team is going to build a voice chat application. Our plan is to use a pre-made library just for this purpose, but we haven't found any good one after days of searching the internet, so I thought I would consider a question here! So the question is: What library / project do you recommend? We are deadly ...
Did you have a look at libjingle ? Its the base library for Google Talk.
4,580,772
4,580,869
C++ crossplatform UI framework for both Mac and Win?
I'm looking for an UI framework that will let me create a C++ application looking/behaving native on both mac and win. By native I mean the approach similar to, say, IBM's AWT/SWT on Java. Six years ago there was no such thing around, is there something now? Thank you in advance.
Qt and wxWidgets are good. But as far as I know, there is really no library that gives a entirely native look and feel. If it is really important, I suggest you create a native application for each system and factor out the common code.
4,580,794
4,580,851
win32 c++ detecting 'enter' in a edit control withot subclassing?
Basically I want an Enter to trigger a message I can catch when a edit control har focus and a user press enter. All solutions online seems to be about subclassing, but I was wondering if there was another way around it? For example, my button has an identifier ID_BUTTON_SEND. Here's how I imagine it; case WM_COMMAND: ...
Best way to catch this is before TranslateMessage gets called. So, if using MFC, override CWnd::PreTranslateMessage. If using only Win API, then just check in your message pump what the message contains before the call to TranslateMessage.
4,580,834
4,581,238
Best box selection method for a Minecraft clone
I'm making a Minecraft clone as my very first OpenGL project and am stuck at the box selection part. What would be the best method to make a reliable box selection? I've been going through some AABB algorithms, but none of them explain well enough what they exactly do (especially the super tweaked ones) and I don't wan...
Working with boxes as primitives is overkill in memory requirements and processing power. Cubes are fine for rendering and even there you can find more advanced algorithms that give you a better final image (Marching cubes). Minecraft's graphics are very primitive in this sense as voxel rendering has been around for a ...
4,580,969
4,581,204
Does C++ require a destructor call for each placement new?
I understand that placement new calls are usually matched with explicit calls to the destructor. My question is: if I have no need for a destructor (no code to put there, and no member variables that have destructors) can I safely skip the explicit destructor call? Here is my use case: I want to write C++ bindings for...
If I understand your question correctly you have a C object in memory and you want to initialize a C++ object with the same layout "over the top" of the existing object. CppObject* cppobject = new (cobject) CppObject; While there is no problem with not calling a destructor for the old object - whether this causes reso...
4,581,056
4,581,088
C++ reusing same variable name in .h file in function (this.variable = variable error?)
I have a name of a variable in my .h file which a function has the same name... for example: //computer.h class Computer{ private: string computerName; int cores; } //computer.cpp Computer::Computer(string computerName, int cores) { ... } I want to assign the values from the .cpp fun...
Instead of assignment, use initialization Computer::Computer(string computerName, int cores) :computerName(computerName), cores(cores) { ... } Yes that works. Constructor initializer lists have that exact purpose.
4,581,176
4,581,190
C++: Unnitialized(?) Array on the Stack (example regarding OpenGL)
What is the contents of an array that is created on the stack, but has no values put in it? Like this: int array[4] cout << array[2]; I ask this because I have always seen in OpenGL when textures are generated, it is done like this: GLuint textures[4]; glGenTextures(4, &textures[0]); glBindTexture(GL_TEXTURE_2D, text...
The contents could be anything. Often it's something left there by a previous function, but no guarantees are made. glGenTextures fills in its second argument, which is passed by pointer. Nothing is using the uninitialized value. Just like textures[0] = 0;, it's overwriting whatever garbage was present.
4,581,229
4,582,011
Bitmap font rendering and kerning
I am attempting to create a bitmap font renderer, however, I am having problems rendering the actual individual letter placements. I will obtain the font character information via GetCharABCWidthsFloat and GetTextMetricsW, however, I am unsure how to use the ABC width's properly ... or do I need more information to do ...
The documentation for KERNINGPAIR seems pretty straightforward. If both the current character and the following character occur in the table via the wFirst and wSecond members, add the iKernAmount to the number of pixels you advance for the next character. I would suggest creating a std::map<std::pair<wchar_t,wchar_t>,...
4,581,241
4,581,906
What level of seperation should my UI elements and model objects have?
I'm building a desktop app in QT (although that may be irrelevant) and I'm having a hard time working through the class structure and layout. The data model is fairly simple with a root container with a number of containers of items. Consider the following representation: Root + Parent + Child The UI is fairly simpl...
I'd suggest following a standard MVC pattern and ensure there are no dependencies from the model to the view; in your case this would mean that while there is a widget for every model item, the model items do not reference their corresponding widgets. While the MVC pattern has many flavours, one way to accomplish this...
4,581,305
4,581,396
error while loading shared libraries: libboost_system.so.1.45.0: cannot open shared object file: No such file or directory
I am building a C++ executable on Linux. The executable links into some boost libraries. This is the output when I attempt to run the binary: root@yourbox:~/work/dev/c++/projects/testfgci/dist/Debug/GNU-Linux-x86$ ./testfgci ./testfgci: error while loading shared libraries: libboost_system.so.1.45.0: cannot open share...
The library cannot be found. Libraries are by default looked for in /lib, /usr/lib and the directories specified by /etc/ld.so.conf. Usually system libraries (like boost, if you installed it via your package manager) are located in /usr/lib, but it's probably not your case. Where are your boost libraries located on you...
4,581,476
4,581,516
Using boost thread and a non-static class function
So I have done some research, and have found you can create a boost::thread object and have it start with a non-static class function by using "this" and boost::bind etc. It really doesn't make much sense to me and all the examples I could find had the boost::thread object launched within the same class as the functio...
The this keyword is used with boost::bind when the function object you're creating is bound to a object member function. Member functions can't exist apart from instances, so when creating a functor object out of a member function with boost::bind, you need a pointer to an instance. That's exactly what the this keywo...
4,581,512
4,581,528
Selective enabling of Template class function
I have a template class, inside which i have a normal function. But i want to enable this normal function only for certain instantiations of a template class. I looked at boost::enable_if and it doesn't suit my need exactly / may be i am not able to use it for my need. typedef boost::mpl::vector< bool, int, double > ...
enable_if is usually used to discriminate among different definitions of a function. In a certain sense, it is a more powerful way of overloading. It seems you are trying to enable a function only if a condition holds, and give a compilation error otherwise, since you have a single definition of init. If that's correct...
4,581,521
4,585,827
C# or C++ game: many 16 color images loaded into RAM. Efficient solution?
I am in the planning stages of creating a fighting game and am unsure how to handle one issue relating to memory. Background info: - Still debating whether to use C# (XNA) or C++. We do not want to commit to either until we have explored how to solve this problem in both languages. - Using a max of 256MB RAM would be g...
If you want to target the XBox 360 and don't have a proper (full blown) devkit, then C# is your only option. When starting out XNA certainly makes doing things a lot easier for you, especially if you're just doing 2D for now (and takes care of a lot of other things you don't need to worry about right now). As for the m...
4,581,584
4,581,592
Shuffling an array in c++
Possible Duplicate: How exactly should I implement a shuffle or random-number algorithm for an array to display quotes in random order? I have a small array that I need the values to be randomly shuffled around within the array. I can do this in python using random.shuffle(), but I can seem to figure out how to do i...
You can use std::random_shuffle from <algorithm>. Here's a basic example from the page: #include <algorithm> #include <vector> ...
4,581,606
4,581,613
In NONCLIENTMETRICS, what's the difference between status font, message font, and caption font?
Ok, just found out that using DEFAULT_GUI_FONT is the wrong thing to actually use as a default GUI font.... there's a NONCLIENTMETRICS structure that I've been told to use instead, but I'm not sure which of the fonts returned there I should use -- i.e. what's the difference between the status font, message font, and ca...
The description is pretty clear, isn't it? lfMenuFont A pointer to a LOGFONT structure that contains information about the font used in menu bars. lfStatusFont A pointer to a LOGFONT structure that contains information about the font used in status bars and tooltips. lfMessageFont A pointer to a LOGFONT st...
4,581,803
4,581,806
No matching function call to class member
I have implemented a generic list and I am trying to retrieve the data from a certain position in the list. umm... but I am getting an error: no matching function for call to 'List::retrieve(int&, Record&)' Below is the code of main.cpp and a snippet of function retrieve from List.h.#include Main.cpp #include <iostrea...
data, which you are trying to pass as the second argument to retrieve, is of type Record. The second parameter of retrieve is of type List_entry, not Record. When the compiler says "no matching function," that usually means that it found a function with the name you used but one or more of the arguments that you are ...
4,581,817
4,581,865
C++11 initialization syntax issue (with gcc 4.5 / 4.6)
What is wrong with the following C++11 code: struct S { int a; float b; }; struct T { T(S s) {} }; int main() { T t(S{1, 0.1}); // ERROR HERE } gcc gives an error at the indicated line (I tried both gcc 4.5 and an experimental build of gcc 4.6) Is this not valid C++11, or is gcc's implementation inc...
According to proposal N2640, your code ought to work; a temporary S object should be created. g++ apparently tries to parse this statement as a declaration (of a function t expecting S), so it looks like a bug to me.
4,581,961
4,581,971
C++ -- How to overload operator+=?
Given the following code snippet, class Num { public: Num(int iNumber = 0) : m_iNumber(iNumber) {} Num operator+=(const Num& rhs) { this->m_iNumber = (this->m_iNumber + rhs.m_iNumber); return *this; } private: int m_iNumber; }; //====================================================...
Returning by reference would be better Num& operator+=(const Num& rhs){ this->m_iNumber += rhs.m_iNumber; return *this; }
4,582,005
4,582,776
What are reasonable ways to improve solving recursive problems?
I like solving algorithm problems on TopCoder site. I can implement most of the basic recursive problems such as backtracking, dfs... However, whenever I encounter a complex recursion, it often takes me hours and hours. And when I check the solution of other coders, I feel so shame on myself. I've been programming for ...
This is a very good question. The best answer I have is factoring: divide and conquer. This is a bit tricky in C++ because it doesn't support higher order functions well, but you can do it. The most common routines are things like maps and folds. [C++ already has a cofold called std::accumulate]. The other thing you ha...
4,582,012
4,582,026
Maximum number of parameters in function declaration
I know that minimum number of parameters in function definition is zero, but what is the maximum number of parameters in function definition? I am asking the question just for the sake of knowledge and out of curiosity, not that I am going to write a real function.
Yes, there are limits imposed by the implementation. Your answer is given in the bold text in the following excerpt from the C++ Standard. 1. C++ Language Annex B - Implementation quantities Because computers are finite, C + + implementations are inevitably limited in the size of the programs they can successfu...
4,582,027
4,582,034
How to use ostream_iterator<> for a generic container at compile time?
I would like to use copy() to print out the content of a container of type T. I tried: template<typename T> void print_con( const T& con, const string& sep = ", ", const string& ms = "" ) { cout << ms << endl; copy( con.begin(), con.end(), ostream_iterator<?>( cout, sep ) ); } What should I replace ? with? Thanks, ...
You can look up the type of a container as the type typename T::value_type In this case, I believe what you want is copy( con.begin(), con.end(), ostream_iterator<typename T::value_type>( cout, sep.c_str() ) ); Hope this helps!
4,582,038
4,582,059
How do I get visual themes on Win32 dialogs generated from resource files?
I've got a dialog defined in a resource file. However, it's using the Windows 95 style buttons and such. How do I use visual themes (i.e. those added in XP and later) for these controls?
You need to embed a manifest file into the executable that tells Windows you want the version of the controls that have themes enabled (there's MSDN documentation specifically for this topic). This is really for compatibility reasons because some people really like to write programs that mess around with the internal d...
4,582,240
4,582,249
C++ Game Programming Resources
Where can i get some advanced game programming resources for c++?
At http://gamedev.stackexchange.com ? More specifically, this question and lots of others tagged with c++
4,582,346
4,588,386
Is it okay to cast a pointer-to-member-variable in this instance?
I've been refreshing/updating my knowledge of C++ lately, and learning about strict aliasing has made me a bit wary of casting pointers of one type to another. I know that this following code sample works in practice on my compiler, but I want to make sure that it conforms to current standards: #include <iostream> us...
Use of reinterpret_cast is almost never portable. On top of that, the only valid use of pointer to member casts are the implicit cast from Type Derived::* to Type Base::* and careful uses of the static_cast from Type Base::* to Type Derived::*. Since you want to change the type of the member, not the type of the obje...
4,582,364
4,582,424
using find() to find elements in a vector
I have a vector which stores some integers. In this vector, there can be all numbers except 10, 12, 31 cannot appear together or in pairs i.e., 10 and 12, 10 and 31, 12 and 31, 10 12 and 31 are invalid. I have come up with the following approach: int main(){ int a[] = {10,2,31}; //can be of any size vector<int> v(a, a...
How about count: template <class InputIterator, class T> typename iterator_traits<InputIterator>::difference_type count ( ForwardIterator first, ForwardIterator last, const T& value ); (see http://www.cplusplus.com/reference/algorithm/count/) or, count_if (which only traverses the list once): template <class Inp...
4,582,398
4,582,438
Writing a simple equation parser
What sorts of algorithms would be used to do this (as in, this is a string, and I want to find the answer): ((5 + (3 + (7 * 2))) - (8 * 9)) / 72 Say someone wrote that in, how could I deal with so many nested parenthesis?
You can use Shunting yard algorithm or Reverse Polish Notation, both of them are using stacks to handle this, wiki said it better than me. From wiki, While there are tokens to be read: Read a token. If the token is a number, then add it to the output queue. If the token is a function token, then push it on...
4,582,846
4,584,678
C++: does boost::asio:write() not support UDP sockets?
Trying to use boost::asio::write() to write to a boost::asio::ip::udp::socket object. While I'm busy re-reading the docs to see if I've gone wrong somewhere, can someone confirm if maybe this is not supported? I'm now thinking boost::asio::write() only supports tcp::socket objects, not udp::socket. This is what I get...
Assuming you want synchronous behavior, you need to use the send or send_to member methods of the boost::asio::ip::udp::socket class. The boost::asio::write free function uses the SyncWriteStream type requirement, which a UDP socket does not meet.
4,582,910
4,582,931
C/C++ GUI apps using Visual Studio but with/without .NET
I want to learn C/C++ GUI Windows/Linux programming. Which IDE is more suitable? If I go with Visual Studio.NET, what are the pros and cons of it. Any IDE that supports both Windows and Linux?
The Qt Creator IDE works for both Linux and Windows. If you want a more versatile development environment, Qt can integrate with Eclipse.
4,582,978
4,582,996
Why is it bad to have a local functor?
For example, whats wrong with declaring the class doubler within the main function, if the predicate will only be used once? #include <list> #include <algorithm> #define SIZE 10 int main() { std::list<int> myList; for(int i=0; i<SIZE ;++i) { myList.push_back(i); } class doubler { pu...
The problem with this setup is that, at least in C++03, you cannot use a local functor as a template argument because it doesn't have external linkage. This means that technically speaking, the above code isn't legal. However, they're fixing this in C++0x since it's a pretty silly restriction, and since VS2010 has ru...
4,583,125
4,583,240
char array as storage for placement new
Is the following legal C++ with well-defined behaviour? class my_class { ... }; int main() { char storage[sizeof(my_class)]; new ((void *)storage) my_class(); } Or is this problematic because of pointer casting/alignment considerations?
Yes, it's problematic. You simply have no guarantee that the memory is properly aligned. While various tricks exist to get storage with proper alignment, you're best off using Boost's or C++0x's aligned_storage, which hide these tricks from you. Then you just need: // C++0x typedef std::aligned_storage<sizeof(my_class)...
4,583,200
4,584,299
Why does my code fail to create a directory in "C:\Program Files" under Windows 7?
I am using Windows 7 and I have to run one program in that windows but that program working in Windows XP. This is a Visual C++ program and I am using Visual Studio 2008 for this. When I am running my application, it does not throw any errors, but it does not create a directory in "c:\program files\". So can anyone hel...
[edit] I edited the code in the question for readability and removed the commented out code (to see the wood for the trees). It is now obvious that nothing initialises szAppPath before calling strcat(), and calling ExpandEnvironmentStrings with NULL as the first argument is undefined (and certainly useless). Calling...
4,583,288
4,584,046
Accessing C++ class member in inline assembly
Question: How can I access a member variable in assembly from within a non-POD class? Elaboration: I have written some inline assembly code for a class member function but what eludes me is how to access class member variables. I've tried the offsetof macro but this is a non-POD class. The current solution I'm using ...
This is all you need: __asm__ __volatile__ ("movl $4,%[v]" : [v] "+m" (var_j)) ; Edited to add: The assembler does accept Intel syntax, but the compiler doesn't know it, so this trick won't work using Intel syntax (not with g++ 4.4.0, anyway).
4,583,310
4,583,346
How to negate a predicate function using operator ! in C++?
I want to erase all the elements that do not satisfy a criterion. For example: delete all the characters in a string that are not digit. My solution using boost::is_digit worked well. struct my_is_digit { bool operator()( char c ) const { return c >= '0' && c <= '9'; } }; int main() { string s( "1a2b3c4d" ); s.e...
You should be able to use std::not1. std::unary_negate<my_is_digit> operator!( const my_is_digit& x ) { return std::not1( x ); } For this to work you have to #include <functional> and derive your my_is_digit functor from the utility class std::unary_function< char, bool >. This is purely a typedef helper and adds ...
4,583,409
7,215,641
Add number (double/float) as attribute to RapidXML node
I'm pretty new to RapidXML. I want to construct an Xml document and print it to a file. Everything works but I'm not sure if I'm doing one part of the process right: Adding an attribute to a node that is a double. I'm using std c++ stuff: double value = 1.0; std::ostringstream strs; strs << value ; std::string str = ...
I know that's an old topic, but don't have a conclusive answer. To convert values with more efficient function, prefer the old C sintax (printf), over the C++ streaming, that's more efficient. I implemented by this way: declare the function for conversion... char* double2char(double value) { char tmpval[64]; sp...
4,583,623
4,583,726
USB and a personal-created device interfacing in Windows using C/C++
I know how to interface using the parallel port and also have a little idea on serial port interfacing. But is there a way to interface using the USB port in Windows? Or any links that would give tutorials on how to do this? Specifically, I wanted to know the programming side of it. I don't know how to start. I have se...
USB programming is considerably more complex than serial or parallel port programming. For writing USB drivers for Windows, you'll probably need the Windows WDK. However, for a device you build yourself you can start with implementing a serial port class driver in your device, so that it shows up as a new serial port i...
4,583,628
4,583,649
Inline array initialization
I was used to using new int[] {1,2,3,4,5}; for initializing array. But it seems nowadays, this does not work anymore, i have to explicitly state how many elements there are, with new int[5] {1,2,3,4,5}; so compilers forgot how to count ? And to make this a closed question, is there a way to omit the number of element...
This has never worked in the current version of C++, you have only been able to zero-initialize (or not initialize) dynamically allocated arrays. What has always worked is non-dynamically allocated array initialization: int myarray[] = {1, 2, 3, 4, 5}; Perhaps you are confusing it with this? Even in C++0x it is not le...
4,583,680
4,583,773
Graphic editor opensource project example on c++ underlying composite pattern
Can you tell me where I can see a some opensource project (only project on C++ language), which is simple graphic editor, сontaining following primitive (for example): an ellipse, a rectangle, a line. And desirable, that to be able to group this primitive in one primitive (for example, Word Grouping -> Group). Composit...
In the GoF book "Design Patterns : Elements of Reusable Object-Oriented Software", there is a Case-Study that shows how to employ the patterns. They namely describe the way to use the Composite design pattern for graphical purpose. (Using Glyphs, a glyphs being a graphical component). They base their case-study on a re...
4,583,993
4,596,561
GDB - Accessing real and imaginary parts of a complex number
When debugging a program which uses (either C or C++), gdb displays complex numbers as _M_value = xxx + yyy*I (with a type of complex double). While debugging, I need to print that number multiplied by a factor. The following does not work: print a * 8.0 I get Argument to arithmetic operation not a number or boolean...
If you use the standard C++ complex template then complex::real() and complex::imaj() should work. my2c Note : Was a comment ^^
4,584,061
4,586,790
Virtual Game Controller Driver
Is there any way that I can map a virtual game controller like ppjoy with c++? I will be receiving orientation data from a phone, and I want to use this as x and y axes. I don't need anything advanced, I just want maximum compatibility on windows.
I found a dll that lets me control ppjoy so I'm going to use that.
4,584,111
4,584,670
Win32 api call via C# fails!
I have a C++ function exported as api like this: #define WIN322_API __declspec(dllexport) WIN322_API char* Test(LPSTR str); WIN322_API char* Test(LPSTR str) { return "hello"; } the function is exported as API correctly by the .DEF file, cause i can see it in Dependency Walker tool. Now i have a C# tester program: [Dl...
Make sure that you have the correct calling convention. Your DLL may use Cdecl, while C# defaults to StdCall. It's better to always explicitly define the calling convention. Especially when using Windows functions which exist in an ANSI and wide char version (those with an A or W prefix), explicitly specify the CharSet...
4,584,112
4,584,228
matrix = *((fxMatrix*)&d3dMatrix); //Evil?
I've been using matrix = *((fxMatrix*)&d3dMatrix); for quite a while. It worked fine until my screen turned black and received a bucket of frustration on my desk. fxMatrix contains 4 fxVectors. fxVector used to be 16 bytes, but now it was suddenly 20. This was because it inherited fxStreamable, which added the vTable....
If you do this, add an assert or compile-time test: assert(sizeof(fxMatrix) == sizeof(D3DMatrix)); BOOST_STATIC_ASSERT(sizeof(fxMatrix) == sizeof(D3DMatrix)); For bonus points, it's also possible to check that each value is in the same place. But yeah, it's kind-of evil (like nuclear power), so you should either hand...
4,584,318
4,584,610
draw relative to camera position
recently my boss told me to modify an opengl application. It uses gluLookAt to set the camera position. I'd have to draw a toolbar relative to that position so that the user could always see it. I'm almost a complete beginner in openGL, so I don't really know what would be easier, doing all the translations and rotati...
What might be easier instead is to change the projection and modelview matrices after drawing the 3D scene. Change the projection matrix to a glOrtho2D, and the modelview so that it scales to fit the screen and then draw the toolbar. See the answers here for specifics: Opengl drawing a 2d overlay on a 3d scene problem
4,584,518
4,585,037
one to one association
What is the best way to represent one-to-one object association in C++? It should be as automatic and transparent as possible meaning, that when one end is set or reset, the other end will be updated. Probably a pointer-like interface would be ideal: template<typename AssociatedType> class OneToOne{ void Associate(...
Untested, but you could use a simple decorator template <typename A1, typename A2> class Association { public: void associate(A2& ref) { if (_ref && &(*_ref) == &ref) return; // no need to do anything // update the references if (_ref) _ref->reset_association(); // save this side _ref = ref; ...
4,584,561
4,584,840
Multiset without Compare?
I want to use multiset to count some custom defined keys. The keys are not comparable numerically, comparing two keys does not mean anything, but their equality can be checked. I see that multiset template wants a Compare to order the multiset. The order is not important to me, only the counts are important. If I omit ...
You cannot use std::multiset if you don't have a strict weak ordering. Your options are: Impose a strict-weak ordering on your data. If your key is a "linear" data structure, it is usually a good idea to compare it lexicographically. Use an unordered container equivalent, e.g., boost::unordered_multiset. For that, you...
4,584,614
4,584,709
C++ operator overloading synthetic conversion
This example is from "Thinking in C++", I have one question regarding compiler synthesizing the operator conversion function. Question When object of class Four is passed (in the function call f()), the overload operation () is called. But I am not able to make out the logic used (compiler synthesizes the operation cal...
First of all, class Four does not contain an operator(), but it does have an operator Three(), which is a conversion operator. In the line g(four); the compiler needs to convert four to an object of class Three and synthesises a call to operator Three() to perform that conversion. The synthesised conversion is equival...
4,584,637
4,584,707
double or float, which is faster?
I am reading "accelerated C++". I found one sentence which states "sometimes double is faster in execution than float in C++". After reading sentence I got confused about float and double working. Please explain this point to me.
Depends on what the native hardware does. If the hardware is (or is like) x86 with legacy x87 math, float and double are both extended (for free) to an internal 80-bit format, so both have the same performance (except for cache footprint / memory bandwidth) If the hardware implements both natively, like most modern I...
4,584,685
4,585,073
Vector of std::function<>
Say want to store the following: typedef std::function<void(int)> MyFunctionDecl; ..in a collection: typedef std::vector<MyFunctionDecl> FunctionVector; FunctionVector v; This is possible, but if I want to find something using std::find: FunctionVector::const_iterator cit = std::find(v.begin(), v.end(), myFunctionDec...
Have you looked at Boost Signals? It may already be doing what you want to do. Anyway, a simple way of wrapping the function would be to use a shared_ptr. If you do typedef std::shared_ptr<std::function<void(int)> > MyFunctionDecl; and make sure that the function is wrapped immediately inside the shared_ptr when you ...
4,584,898
4,585,165
Solving normal equation system in C++
I would like to solve the system of linear equations: Ax = b A is a n x m matrix (not square), b and x are both n x 1 vectors. Where A and b are known, n is from the order of 50-100 and m is about 2 (in other words, A could be maximum [100x2]). I know the solution of x: $x = \inv(A^T A) A^T b$ I found few ways to ...
This is a least squares solution, because you have more unknowns than equations. If m is indeed equal to 2, that tells me that a simple linear least squares will be sufficient for you. The formulas can be written out in closed form. You don't need a library. If m is in single digits, I'd still say that you can eas...
4,585,129
4,585,179
boost variant comparator
I need to compare two variables of type boost::variant and I want to compare the values inside the variant for equality. What would be the best way to implement this? My variant looks like this: typedef boost::variant<int, float, double, long, bool, std::string, boost::posix_time::ptime> variant;
From variant docs: EqualityComparable: variant is itself EqualityComparable if and only if every one of its bounded types meets the requirements of the concept. So variant already implements equality if all the types are comparable. So in your case you should be able to just use the operator ==. In general, you can i...
4,585,356
4,585,369
Why is virtual function not being called?
//GUITEXT class guitext : public entity { public: guitext(graphics *gfx, std::string _text, float _x, float _y, float _size, float timeToLive); bool update(float deltaTime, gameworld *world); void draw(graphics *gfx); }; void guitext::draw(graphics *gfx) { printf("draw"); } //ENTITY class entity...
You made a vector of entity. Those objects always have type entity. If you want to invoke polymorphism, they need to be pointers or references. How can a vector of entity store a guitext? There's not enough space, it doesn't know how to destroy it, etc etc.
4,585,446
4,585,536
Passing constant Arrays with different sizes as function parameters in C++
I have constant multi-dimensional arrays of different sizes. I would like to pass them to a function. However, I would get the error missing subscript, the sizes of the arrays are different so I can't put the subscript in the array parameter. What is the solution to this problem? Here is an example code. The actual arr...
You could use a template. template<size_t first, size_t second, size_t third> double SomeFunction(const double (&arr)[first][second][third]) { return first + second + third; } This function takes a reference to a three-dimensional array of doubles where all dimensions are known at compile-time. It's actually poss...
4,585,928
4,585,954
Member-function templates and overloading operator() in C++
The following code snippet works for me: class Foo { public: template <class T> T& get () { ... } }; Foo foo; foo.get<int>() = ...; However, the following code snippet does not work for me: class Foo { public: template <class T> T& operator() () { ... } }; Foo foo; foo<int>() = ...; The errors being: expect...
If you need to explicitly specify the template argument, you would need to use the operator syntax: foo.operator()<int>() There isn't any way to specify the arguments using the function-call syntax. If you can't deduce the template arguments from the arguments to the function, it's better to use a member function tha...
4,586,002
4,586,095
Tagging/Encoding Pointers
I need a way to tag a pointer as being either part of set x or part of set y (ie: the tag has only 2 'states'), I'm that means one can assume untagged = x and tagged = y. Currently I'm looking at using bitwise xor to do this: ptr ^ magic = encoded_ptr encoded_ptr ^ magic = ptr but I'm stumped at how to determine if th...
Most solution will be platform specific. here a few of them: 1) A pointer returned by malloc or new will be aligned (4, 8, 16, 32 bytes, you name it). So, on most architectures, several LSB bits of the address will be always 0. 2) And a Win32 specific way: unless your program uses 3GB switch, values of all usermode poi...
4,586,499
4,586,554
usage of static member as a class typein C++
Based on "c++ primer", the type of a static data member can be the class type of which it is a member: class Bar { public: // ... private: static Bar mem1; // ok }; However, I have a hard time imagining a scenario in which such a feature is useful. I mean, why do you need a variable to be the class type? ...
The only time that this would really be useful would be in implementing the "Singleton" pattern (or "Simpleton" to those of us who despise it).
4,586,594
4,586,723
Mix and match class in C++/MFC
I'm trying to re-factor a code base, and there is some common functionality among unrelated classes that I'd love to unite. I would like to add that functionality in common base class, but I'm not sure if it's clean and good approach. Say I have CMyWnd class and CMyDialogEx class, both different, so they cannot inherit...
You're experiencing problems because of the design of COnOkBtnFunctionality, which wants you to use inheritance just for code reuse. A quick reminder: Inheritance is not designed for code reuse, it's designed for introducing abstraction. Or in other words: Is your CMyWnd a specific kind of COnOkBtnFunctionality, or doe...
4,586,744
4,586,771
Why is the following code giving me an error about an abstract class?
#include <iostream> using namespace std; class Vehicle { public: Vehicle() {}; virtual ~Vehicle() {}; virtual void Move() = 0; virtual void Haul() = 0; }; class Car : public Vehicle { public: Car() {}; virtual ~Car() {}; virtual void Move(int m) { cDist = m; cout << "Vehicle moves " <<...
The Move function in your derived classes have a different signature (they both take an int). To fix it, add an int parameter in the base class as well. virtual void Move(int m) = 0
4,586,768
4,586,845
How to iterate a boost property tree?
I am know approaching to boost property tree and saw that it is a good feature of boost libs for c++ programming. Well, I have one doubt? how to iterate a property tree using iterators or similar? In reference there is just an example of browsing the tree through: BOOST_FOREACH But is there nothing more? Something lik...
BOOST_FOREACH is just a convenient way for iterating that can be done by iterator, begin() and end() Your_tree_type::const_iterator end = tree.end(); for (your_tree_type::const_iterator it = tree.begin(); it != end; ++it) ... And since C++11 it's: for (auto& it: tree) ...
4,586,812
4,587,030
Convert Date/Time (as Double) to struct* tm in C++
I get a date/time as double value from C# (DateTime.ToOADate(), which is a OLE Date Time). It contains the passed days from 1899/12/31, with the fraction being the passed part of the day. Multiplied with 86400 I get the seconds and from that finally the day's time. Getting the date however is harder. I still don't have...
I believe you can use the VariantTimeToSystemTime function to convert into a SYSTEMTIME.
4,586,813
4,586,824
C++ Simple UDP Server
What is the simplest way to have a udp server in c++ and be able to receive its messages?
boost asio example: http://www.boost.org/doc/libs/1_45_0/doc/html/boost_asio/example/echo/async_udp_echo_server.cpp
4,586,969
4,587,318
Which function pair in QString to use for converting to/from std::string?
I'm working on a project that we want to use Unicode and could end up in countries like Japan, etc... We want to use std::string for the underlying type that holds string data in the data layer (see Qt, MSVC, and /Zc:wchar_t- == I want to blow up the world as to why). The problem is that I'm not completely sure which...
The documentation is a bit disconcerting here (on QString). However, the docs on QTextCodec don't seem to note any problems. It does however return QByteArray instead of a std::string. You can of course easily convert QByteArray to a std::string. But if you look at the source for QString you'll see that toStdString do...
4,587,048
4,587,096
Capturing keyboard input without focus on the programwindow
I am doing a VoIP client and I want to start/stop on WM_KEYDOWN and WM_KEYUP messages for a certain input, say K. When the main window has focus, this is np, but how do I enable it outside of the window? For example, if the window is not in focus and I'm just looking at the desktop or am in a videogame. How does one pe...
You need to install keyboard hooks: http://msdn.microsoft.com/en-us/library/ms644990(v=VS.85).aspx This can be very troubling though for every running application if something steals its keyboard messages.
4,587,049
4,587,124
Implementing Zoom on an orbit camera
I wish to zoom in on the target of an orbiting camera. The camera is manipulated using a function like this: moveCamera(x,y,z); Depending on angle the values x,y,z should be different to get a correct zoom feature but I cant figure out an way to do it. I use functions like getCameraposx, getTargetposy etc.. to get the...
Subtract the target position from the camera position, then scale it, then add the target position in again. camera_position -= target_position; camera_position /= zoom_factor; camera_position += target_position; Regarding your second problem. My guess is that it's due to lack of precision in floats. When you get do...
4,587,653
4,587,812
output format for mac address (C++, stringstream)
I found code: static void PrintMACaddress(unsigned char MACData[]) { printf("MAC Address: %02X-%02X-%02X-%02X-%02X-%02X\n", MACData[0], MACData[1], MACData[2], MACData[3], MACData[4], MACData[5]); } this function prints MAC address like 00-53-45-00-00-00 My quesion: How to make such format while printing ...
Perhaps a little off topic, but I would personally use Boost.Format : boost::format fmt("%02X-%02X-%02X-%02X-%02X-%02X"); for (int i = 0; i != 6; ++i) fmt % static_cast<unsigned int>(MACData[i]); std::cout << fmt << std::endl;
4,588,356
4,620,401
Does LVS_EX_DOUBLEBUFFER correctly not double buffer when running on a remote session?
One is supposed to use double buffering when running locally, but to not use double buffering when the window is on a remote session, if one wants to have the best performance of each mode. The ListView control has an extended style, LVS_EX_DOUBLEBUFFER, which automatically double buffers the contents of the ListView. ...
The ListView does not automatically adjust itself to whether you're running remote or local. It respects the value of the extended style flags that you set when the control is created; if you set LVS_EX_DOUBLEBUFFER then the display will be double buffered, and if you don't it won't. I'm sure Raymond Chen would agree t...
4,588,376
4,588,880
CLR C++ VS C++ (pstsdk)
Considering Simon Mourier's answer to this question: Processing Microsoft Office Outlook 2003/2007 email messages… I plan to use the PST File Format SDK which is written in C++. I would take this opportunity to learn more about C++ and to renew with it, since it's been quite 15 years since the last time I used it. I ha...
If you want to use a .NET (Windows Forms, or maybe even the newer WPF) user interface, the simplest approach is to build an object model in C++/CLI, implemented in terms of the native code but having a .NET interface. Then write the UI in C# and call the C++/CLI object model (which differs from using the .NET base clas...
4,588,392
4,588,425
Creating A GUI from scratch in c++ or assembly
I have had numerous bad experiences with GUI library so I would like to know how to create a window from scratch in c++ I am not talking about win32, what I mean is basically create it myself without any external library is there any way to maybe use a picture or something to create a window yes I know how hard this wi...
In order to create a window you'll need to interface with whatever windowing system is currently present on your operating system. This will either require system calls if the window manager runs in kernel space (as is the case in Windows) or some sort of interprocess communication for user space window managers (like...
4,588,978
4,589,090
prohibiting instantiation as a temporary object (C++)
I like using sentry classes in c++, but I seem to have a mental affliction that results in repeatedly writing bugs like the following: { MySentryClass(arg); // ... other code } Needless to say, this fails because the sentry dies immediately after creation, rather than at the end of the scope, as intended. Is there...
I can't think of an automatic way to detect if you make this mistake or not. You could always create a macro that expands to the correct thing and use that to declare the sentry instead if you keep using it wrong. #define MY_SENTRY_CLASS(_X) MySentryClass _sentry(_X) and then use MY_SENTRY_CLASS(arg); or put a post-i...
4,589,056
4,593,286
templates, typename, lambda -> dependent names not dependent?
Consider: template < typename Something > boost::function<void()> f() { typedef typename Something::what type; return [](){}; } In this code you need the typename because 'what' is a dependent name. But consider this: template < typename Something > boost::function<void()> f() { return []() { typedef typ...
That's a very interesting question. From my understanding, the first 'WTF' (the one with typename in the lambda body) should be the correct according to N3225 5.1.2/7 : The lambda-expression’s compound-statement yields the function-body of the function call operator, but for purposes of name lookup, determining the ...
4,589,105
4,652,278
Compute Content-MD5 from libcurl for HTTP POST
I am using libcurl to build up an HTTP POST, using struct curl_httppost with curl_formadd, etc. I need to be able to compute an MD5 hash value for the entire contents as they will be posted, including the boundary markers, etc. That MD5 then needs to be uploaded as the HTTP header "Content-MD5". Is there a way to get ...
Apparently the answer is to retrieve the content through curl_formget. From there, I can compute the MD5 hash and set the header. http://curl.haxx.se/libcurl/c/curl_formget.html
4,589,180
4,595,297
Using OpenSSL's CMS implementation in C++
So my project today has been to create a C++ class that consolidates a lot of our commonly used crypto tasks. Got lots of things working but ran into a bit of a snag here. For reference, I'm using XCode 3.2.5 on OS 10.6.5. I'm attempting to utilize some of OpenSSL's CMS functions. OpenSSL's MAN Page for one of the fun...
So what I ended up doing was to create a new SDK and calling, ./Configure darwin64-x86_64-cc --prefix=/path/to/sdk/usr --openssldir=/System/Library/OpenSSL enable-cms shared To update the version of OpenSSL included in that SDK. That's seemed to work.
4,589,226
4,589,292
Type checking in C++
In C++, I want to know whether the actual type of the object is from the same class, not the same class or a derived one. This is similar to the following C# code: Class Base { } Class Child:Base { } Base childObject = new Child(); If (childObject.GetType() == typeof(Child)) { // do some code } Thanks!
There are two ways that you can do this. First, you can use the typeid operator, which returns a type_info structure containing information about the type of the object. For example: Base* ptr = /* ... */ if (typeid(*ptr) == typeid(DerivedType)) { /* ... ptr points to a DerivedType ... */ } Notice that you have ...
4,589,237
4,589,256
In this specific case, is there a difference between using a member initializer list and assigning values in a constructor?
Internally and about the generated code, is there a really difference between : MyClass::MyClass(): _capacity(15), _data(NULL), _len(0) { } and MyClass::MyClass() { _capacity=15; _data=NULL; _len=0 } thanks...
Assuming that those values are primitive types, then no, there's no difference. Initialization lists only make a difference when you have objects as members, since instead of using default initialization followed by assignment, the initialization list lets you initialize the object to its final value. This can actual...
4,589,294
4,589,304
release version of app throwing c1083 cannot open include file error
I have a project that I have been running in debug mode and compiles and works fine. However, when I try and do a release version I now get the following error: "fatal error C1083: Cannot open include file: 'QtCore/qchar.h': No such file or directory f:\testing_dev\repo\hello_test\Qt\4.6.0\src\corelib\tools\qstri...
The compiler settings are different for each build configuration. You have probably set the Additional Include Directories setting in the Project Properties for the Debug configuration but not for the Release configuration.
4,589,297
4,589,513
How do I pass an excel range into a c++ function that expects a double ptr
I am new to vba and excel programming, so excuse me if this is a stupid question. I have a c++ dll with a function double foo(int n_bar, double* bar); which I would like to call from excel using vba. I have declared the function in vba as Declare Function foo Lib "mylib" (ByVal n_bar As Long, bar As Double) As Double...
Ok, I figured it out, but it ain't pretty: Function wrapper(a As Range) As Double Dim tmp() as Double Redim tmp(a.Rows.Count -1) For Counter = 1 To a.Rows.Count tmp(Counter-1) = a.Cells(Counter,1).Value Next Counter wrapper = foo(a.Rows.Count, hist(0)) End Function Why do ranges start at 1,...
4,589,299
4,589,637
Display a QMessageBox from C code running in a QThread
I have the main (GUI) thread which creates a QThread. In the QThread, I am calling a C function that needs to display a QMessageBox. So far, I simply used: void notify(char *str) { QMessageBox::information(0, "", QString(str)); } in the C++ code and called it from the C code. This worked fine without threads, but no...
Assuming you have a QWidget or QMainWindow derived class for your GUI, you could add the following to it: class MyWidget : public QWidget { Q_OBJECT; public: MyWidget() { connect(this, SIGNAL(notify_sig(QString)), this, SLOT(notify_slot(QString)), Qt::QueuedConnec...
4,589,353
4,589,356
What is the minimum set of operators I need to overload?
which operators of the comparison (<=, >, ==, etc.) do You usually implement as your basic operators, which You can after use to implement the rest comparison operators or to make all possible comparisons among the classes?
You can implement all six of the operators in terms of == and < using the following equivalencies: a != b => !(a == b) a > b => b < a a >= b => !(a < b) a <= b => !(b < a)
4,589,406
4,589,523
Java equivalent of C++ sf_readf_double()
I'm manipulating .wav audio files in Android. So far things are going well (I can record a .wav file from the mic, add echoes etc.), but I'd like to mimic the behaviour of sf_readf_double() and sf_writef_double as per libsndfile in C++ to implement more complex filters. I have a com.sun.media.sound.WaveFileReader and W...
Try this: What should I use in Android when porting C++ code written with libsndfile? Check this: android-ndk
4,589,463
4,589,486
initialize array size from another array value
#include<iostream> using namespace std; const int vals[] = {0, 1, 2, 3, 4}; int newArray[ vals[2] ]; //"error: array bound is not an integer constant" int main(){ return vals[2]; } //returns 2 if erroneous line is removed Why doesn't this work?
The C++ compiler can only allocate an array with a size known at compile time. If you want to allocated a variable size piece of memory, use the new operator.
4,589,475
4,589,496
c++ connect() keeps returning WSATIMEDOUT over internet but not localy
For some reason, my chat application always gets WSATIMEDOUT when trying to connect to another person over the internet. int len_ip = GetWindowTextLength(GetDlgItem(hWnd,ID_EDIT_IP)); char ipBuffer[16]; SendMessage(GetDlgItem(hWnd,ID_EDIT_IP),WM_GETTEXT,16,(LPARAM)ipBuffer); long host_ip = inet_addr(ipBuffer); int...
Firewalls and/or Nat-routers perhaps? You will need hole punching: http://en.wikipedia.org/wiki/Hole_punching
4,589,512
4,589,545
_wfreopen works on c:/path/file.txt but not with c:\path\file.txt?
TCHAR finalpath[MAX_PATH]; GetCurrentDirectory(MAX_PATH,finalpath); TCHAR filename[] = TEXT("\\lista.txt"); wcscat(finalpath,filename); wprintf(L"List will be saved to %s", finalpath); So this basically confirms me that finalpath is indeed c:\somepath\lista.txt but _wfreopen(TEXT(finalpath),TEXT("w"),stdout); If i jus...
You don't use the TEXT macro with variables. I'm surprised that _wfreopen(TEXT(finalpath),TEXT("w"),stdout); even compiles. Try _wfreopen(finalpath,TEXT("w"),stdout);
4,589,543
4,589,574
C++: Making method return the same object every time
I would like to have a function that loads a file (in this case an OpenGL texture), but only actually loads the file once, and every time it is called after that it just returns what it initially loaded. What would be a good way to do this? Thanks.
You need some place to store that state. That can be either inside an object or as a static variable. Let's say: class TextureLoader { public: TextureLoader() {} GLuint loadTexture(std::string const & filename){ std::map<std::string, GLuint>::iterator it = m_loadedTextures.find(filename); if(it ...
4,589,622
4,589,659
Simplifying const Overloading?
I've been teaching a C++ programming class for many years now and one of the trickiest things to explain to students is const overloading. I commonly use the example of a vector-like class and its operator[] function: template <typename T> class Vector { public: T& operator[] (size_t index); const T& operator[...
How about simply breaking it down into smaller steps? const Vector<T>& const_this = *this; const T& const_elem = const_this[index]; T& mutable_elem = const_cast<T&>(const_elem); return mutable_elem; You can even eliminate the static_cast this way, although you could leave it in if you think it would be clearer.
4,589,917
4,590,410
Vector is pointing to uninitialized bytes when used in recvfrom call
In a function that I am writing I am trying to return a pointer to a vector of unsigned chars. The relevant code is below. std::vector<unsigned char> *ret = new std::vector<unsigned char>(buffSize,'0'); //Due to suggestions... int n = recvfrom(fd_, ret, buffSize, &recvAddress, &sockSize); //Forgot to include this in t...
This line is wrong: int n = recvfrom(fd_, ret, buffSize, &recvAddress, &sockSize); It should be: int n = recvfrom(fd_, &(*ret)[0], buffSize, 0, &recvAddress, &sockSize); You're reading data directly onto the std::vector data structure, which is typically 3 pointers (beginning, end, and end-of-storage). So, you're ov...
4,590,075
4,590,954
Efficiently computing vector combinations
I'm working on a research problem out of curiosity, and I don't know how to program the logic that I've in mind. Let me explain it to you: I've four vectors, say for example, v1 = 1 1 1 1 v2 = 2 2 2 2 v3 = 3 3 3 3 v4 = 4 4 4 4 Now what I want to do is to add them combination-wise, that is, v12 = v1+v2 v13 = v1+v3 v14 ...
In C++, given the following routine: template <typename Iterator> inline bool next_combination(const Iterator first, Iterator k, const Iterator last) { /* Credits: Thomas Draper */ if ((first == last) || (first == k) || (last == k)) return fals...
4,590,297
4,590,309
Why does system() complain that cwd is not known?
I am using system() to run some Unix commands from my application with code like the following: std::stringstream command; command << "rm -rf /some/directory"; int rmResult = system(command.str().c_str()); if (rmResult != 0) { clog << "Error: Failed to remove old output directory '" << command.str() << "' (...
Apparently, this was due to having a directory that is now gone on my pushd stack, even though it was not the current working directory. Cleaning out my stack of the now gone directory, caused the messages to go away.
4,590,419
4,590,433
C++: cleaning up code
I'm going to restart working on a project I put on pause some months ago. The overall design isn't that bad, don't need to rewrite it from scratch, however there are many things that I don't like, this is mostly because I wrote it in a hurry (no comments and magic numbers everywhere ...) and because the way I use C++ t...
CPD, the Copy-Paste Detector: http://pmd.sourceforge.net/cpd.html I use this to look for duplicated code, so I can clean it up. This helps to follow the DRY principle - Don't Repeat Yourself.
4,590,472
4,590,505
implement string class with custom behavior
In one of our class sir said that template allows one to customize behavior of class, and then he gave example of string class, that with few lines of code we can customize string class from STL, as in, we can make it to treat 'a' and 'z' same, 'b' and 'y' same, 'c' and 'x' same and so on. Similary 'A' and 'Z' same etc...
It's very tricky. All you need to write your own traits class, specifically you need to derive it from char_traits<> class template, and redefine eq() and compare() function (Note: only redefining eq() would not work; even though there is no change in the redefinition of compare(), you've to write it in your derived cl...
4,590,492
4,593,233
g++ throws Skeleton wxwidget project "undefined reference to main" errors
Target Platform : Linux mint 9 (Ubuntu Lucid Distribution) Compiler : g++ 4.4.3 wxwidget : 2.8 Project Title : BareBones Files : BareBonesApp.cpp , BareBonesApp.rc , BareBonesFrm.h BareBonesApp.h , BareBonesFrm.cpp , BareBonesFrm.wxform IDE : Nil (Made ...
Try adding BareBonesApp.cpp: g++ BareBonesFrm.cpp BareBonesApp.cpp `wx-config --cxxflags` `wx-config --libs` -o BareBones
4,590,497
4,590,528
Problem - TCHAR as LPARAM to a window that belongs to another process/thread
So i am playing/implementingtomyown with windows via c book examples and there is something about dll injection part that boggles me and i can't solve it. I created a dialog that belongs to another thread/process and i am trying to send it TCHAR variable so it can then use that var in some function(both the function a...
I think that your problem is that you're typecasting the LPARAM to a TCHAR instead of an array of TCHARs (TCHAR*). Try changing that and see if it fixes things.
4,590,626
4,590,776
C++: Static variables in multithreaded program
What is the problem with having static variables (especially within functions) in multithreaded programs? Thanks.
To pick an illustrative example at random, take an interface like asctime in the C library. The prototype looks like this: char * asctime(const struct tm *timeptr); This implicitly must have some global buffer to store the characters in the char* returned. The most common and simple way to accomplish this would be...
4,590,650
4,590,787
Efficient search in a directed graph
I have a directed graph with millions of vertices and edges. A set of vertices are given, let's assume that they are called "START_POINTS". Another set of vertices, called "END_POINTS" are also given. The problem is to find which END_POINTS can be reached from which START_POINTS. Here is an example: START_POINTS: S1 S2...
Just prune the graph to get rid of all nodes that don't appear in Start Nodes or End Nodes, replacing them by edges from their inbound nodes to their outbound targets. Once that is done, go through all the other nodes (that are Start or End nodes), and add edges from their inbound nodes to their outbound nodes, without...
4,590,730
4,590,748
C/C++: Constant array of constant arrays
What would be the syntax for creating a constant array of constant arrays? I am wanting a function argument to be a constant array of constant char* strings.
You do this by putting const on the right of the first asterisk, e.g. void f(const char *const *argument) or equivalently void f(const char *const argument[]) For more dimensions, simply add more *consts (I would not use the [] alternative in this case): void f(const char *const *const *argument) // 2D array of strin...
4,590,850
4,591,154
Should we allocate memory for an object on heap when its internal memory already allocated in heap?
If I use std::vector<> or std::string, do I need to allocate them in heap as well. For example: int main() { std::vector<int>* p = new std::vector<int>(); delete p; } In Java and C#, objects are always allocated in heap using this syntax. I wonder is it efficient to do the same thing in C++? Because whenever I...
You should avoid creating objects with large size on stack, because casual stack overflow on stress (large input data) is rarely revealed by testing and so will make your end users unhappy that your software crashes. About string and vector and other STL containers you should not worry, because they use dynamic allocat...
4,590,854
4,591,251
Win32 Window Menu is appearing along left side instead of across top of window
I think I may be using a wrong window style or something or maybe just adding the menu to the window incorrectly. I'll post a link to an image here so you can see what I mean about the menu not diplaying correctly: http://img707.imageshack.us/img707/4828/wtfmenu.jpg And here's a link to the code that creates the menu ...
The MF_MENUBREAK flag you use when adding the popups causes this—that flag is only required if you want the menu item to appear on a new line in the menu bar. Take out both of the MF_MENUBREAK flags and all will be well.
4,590,901
4,591,041
Scheduling Packet Retransmission
I'm programming a network protocol over UDP, using C/C++ in Linux. The protocol must provide reliability, so I'm going to simulate something like TCP retransmission over UDP. This can be done using pthreads or fork, but I believe that's an overkill and consumes a lot of system resources. A better approach is to exploit...
Here's a sample of how to accomplish asynchronous coroutines with Boost. Boost manages the overhead of creating a thread to run the coroutine in this case so that you don't need to. If you would like the kernel to manage your interrupts, you can use alarm & setitimer, but they're very limited in what they can do. Any s...
4,591,076
12,473,310
C++ SDL on macosx without Xcode
System: black Macbook running Mac os X 10.5.5 (Leopard) I want to compile an SDL hello-world application using only g++. Xcode is good for macintosh but I want cross-platform compatibility, so I won't use any of the coaca framework (no menus, no buttons, etc). Also, porting Xcode projects to other os's is not something...
Took me a little while to figure this out myself, only I was already using SDL and was transitioning from C to C++ on Lion. Its not just the makefile that is the issue here, its probably your source file as well... Download SDL-version.tar.gz Extract and run at prompt ./configure --prefix=/home/user/SDL && make && make...
4,591,219
4,591,221
c++ string comparison
If I have two pieces of character data, what is the best way to compare them (test for equality with ==)? That is, which type is best for this comparison? A const char*, a string? Thanks very much
If your goal is simply to compare strings for equality then it doesn't really matter whether you use null-terminated strings or some string container like std::string. You can use std::strcmp to compare two null-terminated strings just as easily as you can use operator== to compare two std::string objects. The overl...
4,591,330
4,606,661
Matching between product and customer personal information
I writing some application that find ( according to some question ) information about some person ( lets say that the information are weight, height and age of the person ). In the other hand i have product list ( can be very big one ) and according to the product information i need to find the best matching between th...
This might be very similar to something called "The Nearest neighbour problem". Imagine you could turn each field/attribute into a number. Then each person and each product can be represented as a point in an N dimensional space. So if your two attributes were weight and height then you could make the person an (x,y) ...
4,591,579
4,591,713
Object as key in CMap
I have a class named error_code. I use it as key for std::map and CMap (MFC). I am able to make it work for std::map, but not CMap. May I know how I can do so? // OK! std::map<error_code, int> m; m[error_code(123)] = 888; // error C2440: 'type cast' : cannot convert from 'error_code' to 'DWORD_PTR' CMap <error_code, ...
A quick trace shows that template function belows is causing the error : template<class ARG_KEY> AFX_INLINE UINT AFXAPI HashKey(ARG_KEY key) { // default identity hash - works for most primitive values return (DWORD)(((DWORD_PTR)key)>>4); } A quick fix would involve adding implicit conversion function to the u...