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,169,208
4,194,723
Can I somehow access d_func() of QTableView from its subclass?
I'm trying to fix strange QtableView behaviour: if one delete row but not commit data, it stays visible in grid. So, I need to retrieve data about deleted rows and know when we discard changes. Info I need is stored in d->cache[row].op of qtableview. Can I somehow get it from there in my subclass? If no, can I someho...
I can't. It's by design. Only thing I can is reimplement class from QSqlTableModel, which has open pimpl header.
4,169,225
4,169,271
Understanding pointers and references in C++
Would someone explain the below code? A{} C{public: begin(&a); private: A *a;} begin(&a) { a = &a; } B{private: A *a; C *c; start(); } start(){ c->begin(&a); } => In B, the object A is created and in C the object A is referenced to the object a in B. then I got this problem: no matching function for call to...
Are you just trying to get the syntax correct? class A {}; class B { std::auto_ptr<A> a; // This object owns A so use a smart pointer to indicate ownership. C c; B(B const&); // Disable copying. If you want copying use boost::shared_ptr B& operator=(B const&);// Disable copying. ...
4,169,302
4,217,215
OpenCV - SURF Feature Comparison
I am curious about how the OpenCV Feature descriptors are compared. For instance, I can use cvExtractSURF() to get a list of features and their 64-bit (or 128-bit) descriptors, where can I find out how two descriptor can be compared? In stepping through some sample code, to me it looks like two of my "matched" features...
In the OpenCV 2.1 sample file find_obj.cpp, two methods are presented: the built-in C++ Flann function(flann give aproximate solution and works faster), I don't know exactly how it works, but it is documented here. a simpler C function (findPairs()) which finds the nearest neighbor by computing a simple euclidian dist...
4,169,329
4,169,371
calculate running time of a huge c++ program
the suggested method of estimating the time is using the clock() function and then dividing the count of cpu cycles by cycles/second. My problem is that the program i am trying to run takes a lot of time (in hours). This means the clock() function (that returns a long int) returns a garbage value (because max long int ...
If the program is long running then sub-second accuracy is probably not particularly important. In that case, why not just call time()?
4,169,641
4,169,711
How to break this circular typedef?
I want to declare a couple of types (internal to a class templated on K and V and providing some caching behaviour): typedef std::map< long long, typename key_to_value_type::iterator // Ooops... not declared yet > timestamp_to_key_type; typedef std::map< K, std::pair<V,typename timestamp_to_key_type::iterator...
It's not possible, consider what the types would be: timestamp_to_key_type = map< long long, key_to_value_type::iterator > = map< long long, map< K, pair< V, timestamp_to_key_type::iterator > >::iterator > = map< long long, map< K, pair< V, map< long long, map< K, pair< V, map< long long, map< K, pair < V ... This is ...
4,169,732
4,171,217
OpenCV: in search for less CPU intensive frame capture+resize and into buffer way: how to optimize my code?
So I created a function (C++) void CaptureFrame(char* buffer, int w, int h, int bytespan) { /* get a frame */ if(!cvGrabFrame(capture)){ // capture a frame printf("Could not grab a frame\n\7"); //exit(0); } CVframe =cvRetrieveFrame(capture); // retrieve the captured frame /* always che...
Things you can do: Instead of taking images from the camera at the default resolution, choose what resolution you want. I think you can simply set buffer = destination->imageData These articles might be helpful: http://aishack.in/tutorials/efficiently-accessing-matrices/ http://aishack.in/tutorials/memory-layout-of...
4,169,924
4,170,131
Qt - Get system information
I'm looking for a (portable) way to get system information, i.e cpu clock and manufacturer, available memory, etc. Is there a way to do this with Qt or do I have to write OS specific code?
I don't think that there is anything built into Qt to get these kind of details. On linux, all of this is available through /proc/cpuinfo. If you are targeting other platforms, you may want to just go directly to using the cpuid instruction (assuming x86/x86-64).
4,170,002
4,170,018
Splitting a line in C/C++ using whitespace as delimiter
Possible Duplicate: How do I tokenize a string in C++? pseudocode: Attributes[] = Split line(' ') How? I have been doing this: char *pch; pch = strtok(line," "); while(pch!=NULL) { fputs ( pch, stdout ); } and getting a non-written, stuck, exit file. It's something wrong with this? Well, th...
This is not quite a dup - for C++ see and upvote the accepted answer here by @Zunino. Basic code below but to see the full glorious elegance of the answer you are going to have to click on it. #include <iostream> #include <string> #include <sstream> #include <algorithm> #include <iterator> int main() { using nam...
4,170,038
4,170,199
Using pthread.h on a windows build
I have a codebase that makes extensive use of pthread.h. On a windows visual studio project, this obviously doesn't work since pthreads is a unix utility. I know there exists pthread-win32 or something of the sort, but is there a way to have a codebase use this, without replacing all of the pthread code? edit: I'd pre...
Try http://sourceware.org/pthreads-win32/. While I've never used that particular library, I've had luck using some windows ports/abstraction layers of POSIX APIs.
4,170,126
4,170,184
Should I use throw() when implementing non-throwing swap?
When implementing the non-throwing swap idiom, should I use throw()? namespace A { struct B { void swap( B& other ) throw() { /* fancy stuff that doesn't throw */ } }; void swap( B& lhs, B& rhs ) throw() { lhs.swap(rhs); } } namespace std { template<> void swap( A::B& lhs, A::B& rhs ) t...
In C++03 you can put it there, but if it's true that the fancy stuff doesn't throw, it's basically just documentation. It may or may not affect performance by adding the equivalent of try / catch(...) { std::unexpected(); } around calls to the function: it's up to the implementation whether it can do it without affecti...
4,170,135
4,170,144
How can I implement encryption between server side in (php/python) and C++ (Win32/Native Windows)?
How can I implement encryption between server side in (php/python) and C++ (Win32/Native Windows)? I have to transfer data between server side (using php or python) and client side (C++ using Win32 APIs). I am not sure that what functions/APIs or Libs I can use on the both sides so that both sides should be able to com...
Use OpenSSL on client side and OpenSSL on server side. In other way you writing "I am not looking for some complicated" but if you don't want use some complicated then you don't have encryption. Easiest way is use cleartext transmission without encryption, if you searching something like this use for example ROT13 (str...
4,170,201
4,196,447
c++0x: overloading on lambda arity
I'm trying to create a function which can be called with a lambda that takes either 0, 1 or 2 arguments. Since I need the code to work on both g++ 4.5 and vs2010(which doesn't support variadic templates or lambda conversions to function pointers) the only idea I've come up with is to choose which implementation to cal...
A lambda function is a class type with a single function call operator. You can thus detect the arity of that function call operator by taking its address and using overload resolution to select which function to call: #include <iostream> template<typename F,typename R> void do_stuff(F& f,R (F::*mf)() const) { (f....
4,170,243
4,170,895
pass a 2D array from a C++ class to a CUDA function
I am a Java guy jumping into CUDA and the syntax is tripping me. I'm trying to create a matrix in the .cpp file then pass that off to the .cu file to be processed. I see examples where the CUDA function expects the 2D array to come in looking like void handleMatrix(float* A){ // do stuff } when I create the matrix...
You can do handleMatrix(table[0]); or, equivalently, handleMatrix(&table[0][0]); That's if 'handleMatrix' is host code. If it's device code, you can't allocate the buffer like that. You'll want to assemble an array in local memory, fill the entries, allocate another array in the device memory using cudaMalloc() or cu...
4,170,249
4,170,256
int num = *(int *)number; What does this do?
I was looking at some c++ code, and I saw this: int num = *(int *)number; I had never seen this before? it was in a function labeled as such: void *customer(void *number){ } What does that even do? Is there a different way to show this? Thanks, this isn't homework btw I was just confused at what this does?
The (int *) part casts the variable number to a pointer to an int, then the * in front dereferences it to an int.
4,170,313
4,170,324
Finally Block for Segmentation Faults (C++)
I'm using ncurses and whenever I get a segfault, ncurses doesn't properly release control of the terminal (because endwin() was never called). I set up a signal handler: void handler(int signum) { endwin(); exit(EXIT_FAILURE); } but the problem with this is that the segfault is ignored, as opposed to delayed u...
Segfault is undefined behavior. You must find it and fix it. Don't worry about ncurses not releasing the terminal, and find and fix the bug.
4,170,440
4,170,472
Regex: how to find the maximum integer value of a pattern?
Imagine I have the following string: "I'll have some %1%, some %42% and maybe some %5% as well." Basically, I am interested in knowing the maximum integer value that follow the pattern %(integer)%. I am not even sure it's possible to do with a regex. What regex could I use so that in the above example the answer w...
Find all values like this: %([\d]+)%, parse the back reference as an integer (using something like lexical_cast), and choose the highest value. (You can use something like std::max_element for this)
4,170,648
4,170,746
How can I add a mp3 track to a simple OpenGL game?
I'm writing a simple shooter, using basic opengl functionality (glut and glui). I'd like to add a couple of mp3 tracks to the game to play conditionally (level start, death, etc.)
If don't need any special features such as directional sound, the MCIWnd functions are a simple way to play audio files.
4,170,745
6,311,896
Serializing OpenCV Mat_<Vec3f>
I'm working on a robotics research project where I need to serialize 2D matrices of 3D points: basically each pixel is a 3-vector of floats. These pixels are saved in an OpenCV matrix, and they need to be sent over inter-process communication and saved into files to be processed on multiple computers. I'd like to seria...
Edit: Christoph Heindl has commented on this post with a link to his blog where he has improved on this serialisation code. Highly recommended! http://cheind.wordpress.com/2011/12/06/serialization-of-cvmat-objects-using-boost/ -- For whoever it may benefit: Some code to serialize Mat& with boost::serialization I haven'...
4,170,859
4,170,865
Deallocating an array of pointers to objects?
Consider the following situation: Class** array = new Class*[8]; array[1] = new Class(1,2); Is just doing "delete[ ] array" sufficient or should I precede the former with "delete array[1]". I am not completely comfortable with memory management.
Every time you call new[], you have to call delete[] on the pointer to deallocate. Every time you call new, you have to call delete. In your case, you call new twice. array[1] contains a pointer to a class allocated with new, so it must be deallocated with delete. And array is a pointer to an array allocated with new[]...
4,171,154
4,175,091
Hello World C++ CUDA Program in Visual Studio 2010 (Windows 7)
I am trying to compile this Hello World program in Windows 7 with Visual Studio 2010 installed, but I get the following error message when I run nvcc hellocuda.cu: nvcc fatal : nvcc cannot find a supported cl version. Only MSVC 8.0 and MSVC 9.0 are supported How can I compile this CUDA program ?
Visual Studio 2008 Express was needed. (Thanks sgolodetz) So with Visual Studio 2010 Professional (maybe 2010 Express works too?), NVIDIA Parallel Nsight, CUDA Toolkit, Developer Drivers, and GPU Computing SDK code samples (toolkit, drivers, and sdk can be downloaded here) I was able to run the example Hello World in C...
4,171,310
4,171,331
What is wrong with making a unit test a friend of the class it is testing?
In C++, I have often made a unit test class a friend of the class I am testing. I do this because I sometimes feel the need to write a unit test for a private method, or maybe I want access to some private member so I can more easily setup the state of the object so I can test it. To me this helps preserve encapsulatio...
Ideally, you shouldn't need to unit test private methods at all. All a consumer of your class should care about is the public interface, so that's what you should test. If a private method has a bug, it should be caught by a unit test that invokes some public method on the class which eventually ends up calling the bug...
4,171,344
4,171,364
Picking random coordinates without duplicates?
I want to choose random coordinates on a 8x8 board. The x and y coordinates can only be -8. -6, -4, -2, 0, 2, 4, 6, and 8. I want to choose random coordinates for 20 objects but I don't want any 2 objects to have the same coordinates. Program away in C++!
You've only got 9 possible values for each coordinate, so that's 81 possible points in all. The simplest solution would be to just enumerate all possible points (eg: in an array or vector), and then randomly select 20. You can randomly select 20 by picking an index from 0 to 80, swapping that element of the array with ...
4,171,397
4,171,566
Finding nearest RGB colour
I was told to use distance formula to find if the color matches the other one so I have, struct RGB_SPACE { float R, G, B; }; RGB_SPACE p = (255, 164, 32); //pre-defined RGB_SPACE u = (192, 35, 111); //user defined long distance = static_cast<long>(pow(u.R - p.R, 2) + pow(u.G - p.G, 2) + pow(u.B - p.B, 2)); th...
I would suggest not to check in RGB space. If you have (0,0,0) and (100,0,0) they are similar according to cababungas formula (as well as according to casablanca's which considers too many colors similar). However, they LOOK pretty different. The HSL and HSV color models are based on human interpretation of colors and ...
4,171,652
4,171,828
std::ios::failue (ios::badbit) problem with fstream.write()
I've been trying to debug my code for the past few hours and I couldn't figure out the problem. I eventually set my filestream to throw exceptions on failbit and I found that my filestream was setting the failbit for some reason. I have absolutely no reason why the failbit is being set, because all I'm doing is writing...
You must seekp between changing from reads to writes (and vice versa, using seekg). It appears your implementation allows you to avoid this some of the time. (You're probably running into implicit flushes or other buffer manipulation which hide the problem sometimes.) C++03, §27.5.1p1, Stream buffer requirements The...
4,171,653
4,172,137
Can I see the program output in Qt-Creator?
I am writing a simple OpenGL program with Qt Creator which basically creates a QGLWidget, shows it, and runs the application loop. I usually like debugging more with diagnostic messages turned on and off by preprocessor symbols that using an actual debugger and watches etc. In Qt Creator we have a tab called Applicatio...
Usually the Application Output pane works fine. Are you sure that you would see the output from cmd.exe (have you actually tried?)? It's usually turned off for UI applications to avoid console windows from popping up. Try CONFIG += console. Also check if you see qDebug() messages in the Application Output.
4,171,702
4,172,029
c to delphi conversion of structure
can somebody tell me does my conversation from c to delphi is well: c code struct nfq_data { /* packet_hdr - it HAVE to be the same as struct nfqnl_msg_packet_hdr */ struct { uint32_t packet_id; /* unique ID of packet in queue in network order */ uint16_t hw_protocol; /* hw protocol in network o...
uint8_t payload[0]; Is that really a pointer(as in your delphi-code) or an inplace array of size 0 used to represent data coming after the header And you should mark your records as packed. I don't think it makes a difference in your specific code, but it is good practice since the packing rules are easy to get wrong,...
4,172,068
4,172,099
Strange behavior with G++ CAS
Consider this code: #include <iostream> using namespace std; int main() { bool lock = false; lock = __sync_val_compare_and_swap( &lock, false, true ); cout << lock << endl; } I expect the result to be displayed as 1 but the o/p is 0. Just calling __sync_val_compare_and_swap( &lock, false, true ); (so the re...
From the GCC doco: bool __sync_bool_compare_and_swap (type *ptr, type oldval type newval, ...) type __sync_val_compare_and_swap (type *ptr, type oldval type newval, ...) These builtins perform an atomic compare and swap. That is, if the current value of *ptr is oldval, then write newval into *ptr. The “bool” version r...
4,172,124
4,172,156
java arraylist of arraylists
hi when I wanted to have something like vector of vectors (elements shall be ordered of course) I thought of having arraylist of arraylists but in C++ i would do this to access the element v.at(i).at(j)=5; and when i need to add new element v.at(i).push_back(value); so how do i do this in java ? because I can only acc...
Declare an ArrayList of ArraList<Integer>s: ArrayList<ArrayList<Integer>> v = new ArrayList<ArrayList<Integer>>(); v.add(new ArrayList<Integer>()); v.get(0).add(new Integer(5)); v.get(0).add(new Integer(10)); System.out.println(v.get(0).get(0)); // => 5 System.out.println(v.get(0).get(1)); // => 10
4,172,342
4,173,543
complexity of parsing C++
Out of curiosity, I was wondering what were some "theoretical" results about parsing C++. Let n be the size of my project (in LOC, for example, but since we'll deal with big-O it's not very important) Is C++ parsed in O(n) ? If not, what's the complexity? Is C (or Java or any simpler language in the sense of its gramm...
I think the term "parsing" is being interpreted by different people in different ways for the purposes of the question. In a narrow technical sense, parsing is merely verifying the the source code matches the grammar (or perhaps even building a tree). There's a rather widespread folk theorem that says you cannot parse ...
4,172,384
4,172,879
Get ram manufacturer
Does anyone know a way to programmatically retrieve the ram memory manufacturer? Thanks!
In WINAPI, you should be able to call GetSystemFirmwareTable to retrieve the SMBIOS table, and then parse the table to extract that information. See this http://msdn.microsoft.com/en-us/library/ms724379%28v=VS.85%29.aspx And this http://dmtf.org/sites/default/files/standards/documents/DSP0134_2.7.0.pdf The other option...
4,172,580
4,172,612
Interview question - Search in sorted array X for index i such that X[i] = i
I was asked the following question in my interview yesterday: Consider a Java or C++ array say X which is sorted and no two elements in it are same. How best can you find an index say i such that element at that index is also i. That is X[i] = i. As clarification she also gave me an example: Array X : -3 -1 0 3 5 7 ind...
This can be done in O(logN) time and O(1) space by using a slightly modified binary search. Consider a new array Y such that Y[i] = X[i] - i Array X : -3 -1 0 3 5 7 index : 0 1 2 3 4 5 Array Y : -3 -2 -2 0 1 2 Since the elements in X are in increasing order, the elements in the new array Y will be in...
4,172,704
4,172,760
Basic OpenGL lighting question
I think this is an extremely stupid and newbie question, but then I am a newbie in graphics and openGL. Having drawn a sphere and put a light source nearby, also having specified ambient light, I started experimenting with light and material values and came to a surprising conclusion: the colors which we specify with g...
If the lighting is enabled, then instead of the vertex color, the material color (well, colors - there are several of them for different types of response to light) is used. Material colors are specified by glMaterial* functions. If you want to reuse your code, you can use glEnable(GL_COLOR_MATERIAL) and glColorMateria...
4,172,759
4,172,779
g++ gives me strange function call in an *expected* error message
Here's the situation: void funct( unsigned u, double d, float f ) { u = 12; } void funct( double u, int d, void* asd, float f ) { u = 13; } int main() { const unsigned u = 123; double d = 123.123; float f = 123.123; funct( u, d, f, 123 ); return 0; } gives me:...
You're passing a real variable which can be assigned to (an "lvalue") to the function. Of course you pass it by value, not by reference - but the point is, in your function call you would be able to also pass it by reference, because it's an lvalue. Then: If you have a value of type int& (lvalue), you are allowed to se...
4,172,904
4,172,926
Is std::list better than std::vector if one is storing pointers?
I generally avoid std::list, but in a case where I'm storing pointers, would it be more advantageous to use a std::list since I could then randomly insert pointers without having to move all my other pointers? What advantages and disadvantages would this present over a std::vector<Some*> Thanks
Since copy construction of a pointer is trivial, the decision here is not about whether one or the other is better for storing pointers but which is better for your needs. If you really need to do lots of random inserts (and deletes?) then list could work better though it's not a simple decision - perhaps a vector wi...
4,173,023
4,173,041
call stack for code compiled without -g option (gcc compiler)
How do I analyze the core dump (using gdb) which is not compiled with -g GCC option ?
Generate a map file. The map file will tell you the address that each function starts at (as an offset from the start of the exe so you will need to know the base address its loaded too). So you then look at the instruction pointer and look up where it falls in the map file. This gives you a good idea of the locatio...
4,173,108
4,173,174
Unicode / Russian characters and Win32 api [C++]
I'm trying to catch Russian characters with GetAsyncKeyState() win32 api, but apparently it doesn't seem to work except with English. Any idea?? CODE: for(unsigned char c = 1; c < 255; c++){ SHORT rv = GetAsyncKeyState(c); if(rv & 1){ // on press button down ...
GetAsyncKeyState() lets you inspect virtual keys. A virtual key doesn't become a Russian glyph until the WM_KEYDOWN message is processed by Windows through TranslateMessage(), turning that message into a WM_CHAR based on the current keyboard layout. Mapping a glyph back to a virtual key is possible with VkKeyScanEx()....
4,173,224
4,173,265
Simulating C# indexer in C++
As you know in C# classes we can define an indexr with more than one argument. But in C++ operator [ ] can accept one argument. Is there a way to wrtie an indexer in C++ with more than one argument? indexer in C# : public AnyType this[arg1 , arg2 , .....] { get { ... }; set { ... }; } [ ] operator in C++ : Any...
You can return a temporary, which holds the first index and has a reference the data source. private: class BoundArg { private: Data& data; size_t i; public: BoundArg (etc.) value_type& operator [] ( size_t j ) { return data.get ( i, j ); } }; public...
4,173,254
4,173,298
What is the curiously recurring template pattern (CRTP)?
Without referring to a book, can anyone please provide a good explanation for CRTP with a code example?
In short, CRTP is when a class A has a base class which is a template specialization for the class A itself. E.g. template <class T> class X{...}; class A : public X<A> {...}; It is curiously recurring, isn't it? :) Now, what does this give you? This actually gives the X template the ability to be a base class for it...
4,173,306
4,200,132
Can I implement potential field/depth first method for obstacle avoidance using boost graph?
I implemented an obstacle avoidance algorithm in Matlab which assigns every node in a graph a potential and tries to descend this potential (the goal of the pathplanning is in the global minimum). Now there might appear local minima, so the (global) planning needs a way to get out of these. I used the strategy to have ...
boost::graph provides a list of Shortest Paths / Cost Minimization Algorithms. You might be interested in the followings: Dijkstra Shortest path, A*. The algorithms can be easily customized. If that doesn't exactly fit your needs, take a look at the visitor concepts. It allows you to customize your algorithm at some...
4,173,343
4,173,360
How do i push different datatypes into a void buffer?
I have the following data i need to add in the void buffer: MyStruct somedata; // some struct containing ints or floats etc. string somestring; How do i do this? This is my buffer allocation: void *buffer = (void *)malloc(datasize); How do i add first the somedata into the buffer (, which takes lets say 20 bytes), an...
memcpy(buffer, &somedata, sizeof(MyStruct)); strcpy(buffer + sizeof(MyStruct), somestring.c_str()); Which will copy the string as a c string.
4,173,384
4,173,576
How to make sure a function is only called once
Suppose I have a function named caller, which will call a function named callee: void caller() { callee(); } Now caller might be called many times in the application, and you want to make sure callee is only called once. (kind of lazy initialization), you could implement it use a flag: void caller() { static...
Thread-safe: static boost::once_flag flag = BOOST_ONCE_INIT; boost::call_once([]{callee();}, flag);
4,173,455
4,246,975
Help wanted on memory leak - having a multi-threading queue, char buffer and a structure
So I have a boosted queue class that helps multi-threading described here. In my class declarations I have //... struct VideoSample { const unsigned char * buffer; int len; }; ConcurrentQueue<VideoSample * > VideoSamples; //... struct AudioSample { const unsigned char * buff...
change your function to the below and do similar changes in other place where you are allocating memory. void VideoEncoder::AddFrameToQueue(const unsigned char *buf, int size ) { VideoSample * newVideoSample; if(!VideoSamples.try_pop(newVideoSample)) { newVideoSample = new VideoSample; } else { delete buff;...
4,173,584
4,173,625
matrix showing up empty when passed from cpp to CUDA
I've passed a 2D array from a C++ class to a CUDA function; however, once in the CUDA function the data in the matrix is gone. I'm still in the host, not the device so I don't understand what I've done wrong as this should be very straight forward. Here is the C++ int main() { const int row=8; const int column=8;...
Ha, needed a while to find it. Check the indexing in your matrix randomization code. :) You're using the wrong variables and never initialize the float values.
4,173,609
4,173,711
I will create a program Check stock with barcode, What do I need to learn
i will create a program check stock with barcode and database what do i need to learn What language should I use to development. And Should I use a database where. c/c++, java, Visual C# not experience but pretty spec check in, check out and check amount in stock Thank sorry for grammar
Any of those languages will work. Most Barcode scanners are serial (RS-232), so you need to have the ability to connect through your language. I would suggest C# on a windows platform because the .NET platform has a well-defined serial port. Also, GUIs are pretty easy to implement. As far as a database, you could sta...
4,173,636
4,173,727
Where can I learn how to interface with a graphics card using C++?
I'm learning c++ right now and I'd like to start interfacing with a graphics card and play with the basics of 3d graphics. I haven't found it in my book or in internet queries, and I actually have absolutely no idea where to start with this. Can c++ code run on a graphics card once it is compiled? I understand that I a...
OpenGL is a library. Your C++ code, which compiles into machine code (for your CPU, not GPU), calls OpenGL functions, which send data to your graphics card (GPU). The graphics card interprets that data, and uses it to do whatever you've asked it to do. The GPU does not run any of your C++ code. GLSL (OpenGL Shading Lan...
4,173,679
4,174,011
C++: tools to statically analyze code (and/or preprocess it)
Often I could use some tools to statically analyze my code in order to help me making it cleaner. Something like compiler warnings, but those are not enough. Every now and then I dream about writing one (using clang libraries or gccxml), but I guess it would take too much work. Some things that pop to my mind are: loo...
cppcheck is just wonderful.
4,173,774
4,174,082
What kinds of code need to be aware of rvalue references?
I see lots of people having problems understanding rvalue references. Will "ordinary" C++ code (e.g., that uses the standard library, but doesn't implement it) need to know about rvalue references once the new standard comes out, or can the people/code just pretend rvalue references don't exist? Do rvalue references pr...
I didn't see anything much to disagree with in GMan's (aka gmannickg) blog article on the subject: http://blackninjagames.com/?p=95 Summary: anyone who knows about copy-and-swap (and in general the rule of three), should know about move semantics (and hence rvalue references), because the best-practice idioms change as...
4,174,144
4,174,307
Default value for a reference to a pointer
I need to make last argument in my function to be a default argument and the type of this argument is *& (reference to pointer). For some reason this doesn't work for me: template<class T> void f(T*& = nullptr); I'm getting an error: Error 1 error C2440: 'default argument' : cannot convert from 'nullptr' to 'T *&...
Basically, if you need to call this function with nullptr (which means "I don't have a value to pass to the function, but want to call it anyway"), then you would want to take the argument per T**. See How to pass objects to functions in C++? for more on passing arguments.
4,174,343
4,174,354
Why use array of char instead of int for bitsets in C++
For a project I'm working on I need to create my own implementation for a bitset. I've taken a look at the STL library to see how they handle this and looked at a few other things online. It seems like it's pretty standard to use a char array. Is there a reason why everyone uses char arrays instead of the integer type?...
Simply because a char in C++ is a single byte, (or at least, it's guaranteed by the C++ standard to be less than or equal in size to int or short) whereas the size of an int is usually larger than a byte. (It's usually 32-bit, or 4-bytes, on most machines these days.) Since a single byte is the smallest addressable u...
4,174,427
4,174,548
Is there anyway to instead of doing explicit instantiation of a template code for DLL, deliver the code itself somehow implementation-hidden?
If a template code is about to be used for DLL the explicit instantiation should be applied to produce the binary but I want to know Is there anyway not to do explicit instantiation but to deliver the source-code somehow implementation-hidden to the end-user so that his/her compiler can does the instantiation itself ?
That's what the export keyword was invented for. Sadly, almost no compiler ever implemented it, and AFAIK, it will be deprecated in C++1x.
4,174,601
4,174,682
Disabling Exceptions for MSVC
I'm trying to disable exceptions completely in Visual Studio 2010, and to ensure that exception handling is disabled I have the following test: class CompilerFlagsTestExceptionConstructor { public: CompilerFlagsTestExceptionConstructor() { throw std::exception("Exceptions Enabled"); } ~CompilerFlagsTestExceptionConst...
I'm not sure your test makes sense. What should the behavior be if exceptions are disabled? throw just becomes a no op? That's what the test suggests the behavior is. I would expect for usefully disabling exceptions throw should be a compile error, or alternatively throwing with exceptions disabled should immediately ...
4,174,663
4,174,915
Readfile on HID sometimes gives wrong values
I have a connection for a WiiMote handle = CreateFile(didetail->DevicePath, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); if(handle != INVALID_HANDLE_VALUE) { opened = true; readReportEvent = CreateEvent(NULL, TRUE, FALSE, NULL); memset(&readOverlapped, 0, si...
There are some additional problems: Create manual reset event (CreateEvent(NULL, TRUE, FALSE, NULL)) instead auto-reset event (CreateEvent(NULL, FALSE, FALSE, NULL)). Check if ReadFile returned FALSE and the value of GetLastError is ERROR_IO_PENDING, and in this case wait for the event (WaitForSingleObject). If Wait...
4,174,671
4,174,702
What does this line of C code mean?
I'm converting some C code to Delphi. Can someone please explain to me what this line means? nResult = ( (pBuffer[ 0 ] << 8) & 0xFF00 ) | ( pBuffer[ 1 ] & 0x00FF ); Here is the rest of the code for context: USHORT UTIL_htons( USHORT hostshort ) { PUCHAR pBuffer; USHORT nResult; nResult = 0; pBuffer = (PUCHAR )&h...
Apparently (all those defines in uppercase make it hard reading) the functions are swapping the internal byte ordering of values that occupy 2 or 4 bytes. For example: UTIL_htons(0x1234); /* returns 0x3412 */ UTIL_htonl(0x12345678); /* returns 0x78563412 */ I have no idea how to write them in Delphi ... Hopefully they...
4,174,694
4,216,116
Pure virtual functions may not have an inline definition. Why?
Pure virtual functions are those member functions that are virtual and have the pure-specifier ( = 0; ) Clause 10.4 paragraph 2 of C++03 tells us what an abstract class is and, as a side note, the following: [Note: a function declaration cannot provide both a pure-specifier and a definition —end note] [Example: struct ...
In the SO thread "Why is a pure virtual function initialized by 0?" Jerry Coffin provided this quote from Bjarne Stroustrup’s The Design & Evolution of C++, section §13.2.3, where I've added some emphasis of the part I think is relevant: The curious =0 syntax was chosen over the obvious alternative of introducing a ne...
4,174,699
4,175,003
Selecting nearest RGB colour from std::map
I have a map of pre-defined colors and a given color to select one nearest match. If i will use distance formula, would I be calculating the distance from each pre-defined color in map rather than just finding a key if it is between the matching limit?
Colours are a bit more complex than 3D. You have to think about brightness as well as how red, green or blue the colour might be. So is 1,0,0 closer to 255,0,0 than to 0,1,0? So perhaps colours need to be thought of as four dimensional? In addition, human response to colours is not linear, so if you just look at th...
4,174,749
4,174,822
Linux console commands in C++ (gcc compiler)
How can I give commands to Linux console (Ubuntu) from my c++ program, and assign a value, which my command tells, to string variable? Please, give me an example, in which program gives simple command "uname -a" to console and writes result. Sorry for my bad English, I know it very little. I would be very happy, if som...
The command you need is popen. You can get information about it by typing man popen into your shell; if your Linux distribution runs its Russian translation, it should display the information about it in Russian. Basically, popen just opens a "file" (stream), with which you can work just like with a regular file. Her...
4,174,901
4,174,982
How do I return an array from a function?
I don't get a error message when I compile the code but I cant a proper result. #include <iostream> using namespace std; struct Coord{ int r; int c; }; struct CoordwValue{ Coord C; char Value; }; CoordwValue* getNeighbors(); int main (){ CoordwValue *k= getNeighbors(); for (int i=0;i<4;i++) cout<<(k[i].Val...
If you want to return an array of four objects, you don't necessarily need to use dynamic allocation or std::vector. You just need to wrap the array in a class so that you can return it. For example: struct GetNeighborsResult { CoordwValue Value[4]; }; GetNeighborsResult getNeighbors(); Boost, TR1, and C++0x al...
4,174,972
4,174,985
How does STL return 2 iterators with the same function?
I noticed that vector.begin() will return a const iterator, or an iterator based on what is given on the left. How is something like this implemented since the arguments given to the function are the same. Thanks
Its return-type is based on whether the vector itself is being accessed through a const reference (or pointer) or not. Also, an iterator can be implicitly converted to a const_iterator, which is why something like this works: std::vector<T> v; std::vector<T>::const_iterator it = v.begin();.
4,174,986
4,175,110
getting a subimage of a CImage
I've recently started learning how to use MFC in Visual Studio. My program uses many small 32x32 pixel images that for convenience are put together in one large .png. I've figured out how to load the big image into a CImage and display it on a CClientDC, but I can't find anything that helps me split the image into th...
You'll need to use the CImage::Draw() overload that lets you specify the source rectangle. So that you can clip the image that you want to paint from the original. There are two candidates, the Draw(HDC hDestDC, const RECT& rectDest, const RECT& rectSrc) for example. The other one is the first one listed on this doc...
4,175,194
4,175,208
How do I add Eclipse C++ to Eclipse classic?
I have Eclipse Classic for my Java classes, and I have Visual Studio as well, but I'd much rather keep using Eclipse. Can anyone help? I tried adding the addons from within Eclipse but it didn't work properly.
You need the Eclipse CDT project plugin. Having said that, unless you need platform independence, don't give up on Visual Studio. For C/C++ Visual Studio is way, way, way better and faster than Eclipse. (IMHO).
4,175,256
4,175,397
getting different values when inspecting an object with gdb
I'm using gdb to debug a c++ program which terminated with a segmentation fault. Looking at the stack, the first few frames are: #0 0x0041c496 in cDefaultList::doInsert (this=0x9c69708, obj=0x9c69348) at cdefaultlist.cc:119 #1 0x0041c86c in cDefaultList::take (this=0x9c69708, obj=0x9c69348) at cdefaultlist.cc:189 #2...
Are you sure you're not just looking at uninitialized (or freed and then re-used) memory? That could explain why your code is crashing as well.
4,175,362
4,175,402
What is the best way to handle event with SDL/C++
I am using SDL for the view parts of my game project. And I want to handle key press events without interrupting the main thread. So I decided to run an infinite loop in another view thread to catch any events and inform the main thread. However, I am not sure that this is the best since this may cause a workload and d...
Don't bother with another thread. What's the point? What does your main thread do? I imagine something like this: Update Logic Render Goto 1 If you receive input after (or during) the update cycle then you have to wait till the next update cycle before you'll see the effects. The same is true during rendering. You mi...
4,175,535
4,175,567
Where can I see the code used in C++ standard libraries?
When I compile a program with #include where can I see the contents of that file, and also since that file contains declarations, where can I see the actual code used in those functions? Is it open to everyone or is it not available to the public?
The actual code is in the platform-specific standard libraries that come with your compiler, you can see it by looking at the standard library implementation source. Here's the documentation (and source) for libstdc++ by GNU (it comes with gcc): http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/index.html. Downloa...
4,175,754
4,175,867
Elegant binary i/o in C?
I've been loading a lot of binary files recently using C/C++, and I'm bothered by how inelegant it can be. Either I get a lot of code that looks like this (I've since moved on): uint32_t type, k; uint32_t *variable; FILE *f; if (!fread(&type, 4, 1, f)) goto boundsError; if (!fread(&k, 4, 1, f)) goto boundsErr...
If you want to de-serialize binary data, one option is to define serialization macros for the structs that you want to use. This is a lot easier in C++ with template functions and streams. (boost::serialization is a non-intrusive serialization library, but if you want to go intrusive, you can make it more elegant) Simp...
4,175,896
4,175,919
Safe way to continuously erase from a std::vector?
I thought the following code would work but it crashes when the target widget is at the end of the vector. for(std::vector<AguiWidget*>::iterator it = children.begin(); it != children.end(); ++it) { if((*it) == widget) it = children.erase(it); } I want it to go through and delete an...
You can use the erase-remove idiom to erase all elements that are equal to widget. children.erase(remove(children.begin(), children.end(), widget), children.end());
4,175,903
4,177,426
2D arrays cross languages C++ and C#
If I want to call an external C++ function which returns a 2d array, what kind of problems could I come across? For instance, if I declare the 2D array inside of the C++ function and initialize the size of the array within the C++ function, how will the .Net automatic garbage collector handle this? Do I have to give ...
Unless the function returns a vector or vectors, it is the exact same problem in C++ as well. It is a memory management problem, the caller of the function has no good way to free the memory of the array, it doesn't know the array sizes nor what allocator was used. For that matter, even iterating the array is perilou...
4,175,971
4,175,991
error C2228: left of '.size' must have class/struct/union
I'm getting this compiler error when calling vector's size(). Why? #include <vector> #include <iostream> #include <fstream> #include <sstream> #include <string> #include <cassert> using namespace std; class Vertex { float firstValue; float secondValue; float thirdValue; Vertex (float first, float ...
Believe it or not, this line does not declare an instance of std::vector named results, calling the constructor taking a begin and end iterator: std::vector<float> results(std::istream_iterator<int>(actualLineStream), std::istream_iterator<int>()); This actually declares a function called results that takes a para...
4,175,984
4,176,625
Mac + Netbeans C++ OpenGL problem
I am trying to develop OpenGL programs with C++ on Mac using Netbeans, and there are some compilation errors: "/usr/bin/make" -f nbproject/Makefile-Release.mk QMAKE= SUBPROJECTS= .build-conf "/usr/bin/make" -f nbproject/Makefile-Release.mk dist/Release/GNU-MacOSX/sdl_test mkdir -p build/Release/GNU-MacOSX rm -f build/...
In your project properties go to C++ Compiler. Under Include Directories add /System/Library/Frameworks. Under Linker at the bottom under Additional Options add -framework OpenGL. Change your include directive to #include <OpenGL/gl.h> Now you should be able to compile your program. But I seem to be missing something, ...
4,176,130
4,176,139
C++ error: request for member 'push_back' in 'v'
Why do I get this error? I am at a loss... error: request for member push_back in v, which is of non-class type std::vector<Leaf, std::allocator<Leaf> >* class Leaf { public: // Variables std::string *name; // Methods Leaf(){} Leaf(std::string *s) { name = s; } }; class Branch {...
In the function addLeaf() v is a pointer, and leaf is a pointer, you need to dereference both of them. v->push_back(*leaf); Also, what's with all the scope qualifications, like Leaf::Leaf and Branch::Branch? It should just be Leaf, and Branch.
4,176,152
4,176,197
Maze Solving using graph
Hey i was in a local programming competition and they asked me this question which i could not do so please help me on this one. Write a program that loads from a file the size of a maze and then the maze itself. To model the maze we use the character "S" that specifies the start cell, "." that specifies free cell, "#"...
One way to find a path: Have a queue of cells to check, and a count of steps for each cell from there to the destination. Set the ending cell's count to 0, and add it to the queue. While the queue is not empty: Get a cell from the queue. For each free neighbor cell, compare the current cell's count + 1 to the neighbo...
4,176,233
4,178,848
Can I access Qt signals/slots of objects out of scope?
Do the Qt signals/slots follow the scope of native C++? Let's say I have the following classes: House, Kitchen, Cellar, Stove and Shelf. class House {Kitchen kitchen, Cellar cellar;}; class Kitchen {Stove stove;}; class Cellar {Shelf shelf;}; Now I want to send a signal from the shelf in the cellar to the stove in ...
You can do the connection in any method of House, as there you can access both objects. The "connector" must be able to access both sender and receiver, at compile time, that's all there is to it.
4,176,314
4,176,338
Qt - How to open a website in a particular browser
I am coding one project, which needs to launch some webbrowsers with the given url. I saw some QT examples, but they explained how to launch the default browser, not a particular browser. Any helping suggestions will be appreciated. Edit1: Below is the code I use currently QString temp="C:/Program Files/Internet Explor...
If you know which browser you want to start and where they are located on the system (such as the default installation directories). You should be able to use QProcess This can usually be done as the following: iexplore.exe http://www.locationOfUrl.com or //path/to/app/firefox.exe http://www.locationOfUrl.com
4,176,464
4,177,104
Why are all iterations in a loop parallelized using OpenMP schedule(dynamic) given to one thread? (MSVS 2010)
Direct Question: I've got a simple loop with, what can be, a computationally intensive function. Let's assume that each iteration takes the same amount of time (so load balancing should be easy). #pragma omp parallel { #pragma omp for schedule(dynamic) for ( int i=0; i < 30; i++ ) { MyExpensiveFunction(); } } ...
Most likely, this is because the OMP implementation in Visual Studio decided that you did nowhere near enough work to merit putting it on more than one thread. If you simply increase the quantity of iterations, then you may well find that the other threads have more utilization. Dynamic scheduling means that the implem...
4,176,533
4,177,138
Non-blocking stack pop
Consider the following code which uses non-blocking semantics to pop a stack: T Stack<T>::pop( ) { while (1) { if (top == NULL) throw std::string(“Cannot pop from empty stack”); Node* result = top; if (top && __sync_bool_compare_and_swap(&top, result, top->next)) { ...
Firstly, assuming top is volatile and can be changed by another thread at any point, only take its value once per loop so you won't get the rug pulled out from under you: T Stack<T>::pop( ) { while ( 1 ) { Node* result = top; if ( result == NULL ) throw std::string ( “Cannot pop from emp...
4,176,637
4,176,661
Render a vector graphic (.svg) in C++
My and a friend are working on a 2D game where the graphics will be .svg files and we will scale them appropriately either by rasterizing them first, or rendering them directly on a surface (which still would require rasterization at some point). The problem is, I've been looking all day to find a library that will al...
The wxsvg library allows loading and manipulating SVG files. Qt also has an SVG module.
4,176,727
4,176,757
syslog const char* to string
catch (exception e) { syslog (LOG_ERR, "exception: " + e.what()); } Here is what im trying to do, And it aint working, ive tried using this string ctos(const char& c){ stringstream s; s << c; return s.str(); } But still lost Any help would be apreciated Thanks.
Try this catch (exception e) { syslog (LOG_ERR, "exception: %s" ,e.what()); }
4,176,854
4,176,865
reserved keywords in C++
I think there are reserved keywords in C++ , why they are called 'reserve keywords ' and categorized as different?
Words used by the language (if, for, while, struct, etc.) are sometimes called reserved words or keywords. I suspect that many people also call them reserved keywords. However, there are also words that the Committee may want to use in the future but that aren't currently used. I would consider these reserved keyword...
4,176,894
4,176,970
OpenGL skeletal animation performance
I'm in a bit of a situation. You see, when rendering my model with my renderMesh() function, the game was at about 30fps. When rendering to a display list, and running that, the fps went to about 450fps. Thats a gain of 1500%. I was overjoyed by this, for it meant that OpenGL wasn't the cause of the lag, it was the fun...
You could use VBOs and get improvement. Should be same or better then lists. 1500% improvement is strange. Are you sure you measuring FPS right?
4,176,895
4,176,908
c++ pointers to operators
I want to write a pointer in c++ (or in c++0x), that will points to a operator of a class lets say A or B. Is there any method to do it? Of course there is a syntax like int (A::*_p) (); but it doesn't solve this problem. I want to make general pointer, not specifying the base class for it - only pointer for "operato...
No, you can't do this. The class type is a part of the type of the operator member function. The type of A::operator()() is different from the type of B::operator()(). The former is of type int (A::*)() while the latter is of type int (B::*)(). Those types are entirely unrelated. The closest you can get is by using ...
4,176,916
4,176,943
Difference between reserved words and keywords?
What are the differences between reserved words and keywords in C++? Is 'main' a reserved word or a keyword?
The only thing I could think of that might differentiate the two is if a word was reserved for future use (i.e. not a keyword, but also not allowed for use). However, I couldn't think of an exapmle off the top of my head... Main is not a keyword per se, but it is usually required by C, C++, C#, and similar languages a...
4,176,951
4,176,967
How-to specialize template method in subclass(c++)?
I'm trying to specialize a template method of non-template class in its subclass: // .h file class MyWriter { public: template<typename T> void test(const T & val) { std::cout << val << "\n"; } }; // .cpp file class MyType { public: MyType(int aa, double dd) : a(aa), d(dd) {} int a; dou...
Specialization should be done for the same class not for a subclass and also outside of the class body: class MyWriter { public: template<typename T> void test(const T & val) { std::cout << val << "\n"; } }; template<> void MyWriter::test<MyType>(const MyType & val) { test(val.a); test(val....
4,176,963
4,177,418
What library do you use for matrix calculations on CUDA?
What library do you use for matrix calculations on CUDA? Or are there any? It seems as if everybody writes this by himself. For usual processors, I use Eigen. What about GPUs?
For dense matrix operations, you could consider CUBLAS (provided with the CUDA Toolkit), Magma and CULAtools. For sparse matrix operations consider CUSPARSE (provided with the CUDA Toolkit) and CUSP.
4,176,985
6,921,913
C++ in UNIX when parsing an xml file using libxml2
How to retrieve node and attribute values from xml file in C++ using libxml2 by using xpath ? Thanks in advance, Bhargava
sp1.xml: <users noofids="1"> <user user="vin" password="abc"/> </users> Program: #include <libxml/xpath.h> #include <libxml/tree.h> #include <iostream> using namespace std; int main (int argc, char **argv) { char ID[25]; xmlInitParser (); //LIBXML_TEST_VERSION xmlDoc *doc = xmlParseFile ("sp1.xml"); ...
4,177,200
4,419,571
Segmentation fault on boost::asio::ip::tcp::acceptor
Im getting segmentation fault from pthread_mutex_lock, heres my backtrace: Program received signal SIGSEGV, Segmentation fault. 0x00007ffff61b03f0 in pthread_mutex_lock () from /lib/libpthread.so.0 (gdb) bt #0 0x00007ffff61b03f0 in pthread_mutex_lock () from /lib/libpthread.so.0 #1 0x000000000041141f in boost::as...
You need to post more code (Server::Server()) and post the files in separate code blocks for readability. Try changing io to be a pointer, and explicitly initializing it in your constructor: Irc::Server::Server() : io() { start(); startAccept(); }
4,177,269
4,177,503
_CrtSetAllocHook never shows filename/line number
I am implementing a memory tracker in my application so that further down the line, should I get any memory leaks I can switch this little guy on to find it. All is great except that I am never passed the filename or the line number. Is there some flag I have to set using _CrtSetDbgFlag, or a preprocessor command? A...
From the <crtdbg.h> header file: #ifdef _CRTDBG_MAP_ALLOC #define malloc(s) _malloc_dbg(s, _NORMAL_BLOCK, __FILE__, __LINE__) // etc... #endif Note how the redefinition now calls another version of malloc that has the file and line number that you are looking for. Clearly, to make this work you will ha...
4,177,346
4,177,353
Class contiguous data
I have a C++ class which has four private floats and a bunch of nonstatic public functions that operate on this data. Is it guaranteed, or possible to make it so, that the four floats are contiguous and there is no padding. This would make the class the size of four floats, and it's address would be that of the first f...
That depends on your compiler. You can use #pragma pack(1) with e.g. MSVC and gcc, or #pragma pack 1 with aCC. For example, assuming MSVC/gcc: #pragma pack(1) class FourFloats { float f1, f2, f3, f4; }; Or better: #pragma pack(push, 1) class FourFloats { float f1, f2, f3, f4; }; #pragma pack(pop) That basical...
4,177,431
4,177,658
C++: doubts about visitor pattern
I know what Visitor Pattern is and how to use it; this question is not a duplicate of this one. I've got a library where I put most of the reusable code I write, and which I link to most of my projects. Often I need to add features to some classes, but without adding these new features to the library. Let me use a rea...
First: "Visitor Pattern is a way to simulate Double Dispatching in C++." This is, erm, not fully right. Actually, double dispatch is one form of multiple dispatch, which is a way to simulate (the missing) multi-methods in C++. Whether operations on a class hierarchy should be implemented by adding virtual functions o...
4,177,680
4,177,705
readout a big txt file
i want to know, if there is another way to readout a big file Hans //name Bachelor // study_path WS10_11 //semester 22 // age and not like this: fout >> name; //string fout >> study_path; //string fout >> Semester ; //string fout >> age; //int when my file turns to more than 20 line's i should make 20+ fouts?...
You could define a class to hold the data for each person: class Person { public: std::string name; std::string study_path; std::string semester; unsigned int age; }; Then you can define a stream extraction operator for that class: std::istream & operator>>(std::istream & stream, Person & person) { ...
4,177,744
4,177,902
C++ OS X open default browser
I would like to know a way to open the default browser on OS X from a C++ application and then open a requested URL. EDIT: I solved it like this: system("open http://www.apple.com");
In case you prefer using the native OS X APIs instead of system("open ...") You can use this code: #include <string> #include <CoreFoundation/CFBundle.h> #include <ApplicationServices/ApplicationServices.h> using namespace std; void openURL(const string &url_str) { CFURLRef url = CFURLCreateWithBytes ( NULL, ...
4,177,991
4,178,025
Hiding protected functions and members from the user?
My classes are event driven so for example, the public mouseClick() calls the protected onMouseClick(). I find that it might be puzzling if the user's intellisense picks up on all the protected ones. Is there a way to minimize this confusion in any way? Thanks
Member access control in C++ is for compilers, not for users. If you really need that, you should use ABCs as interfaces and create your objects through factories. This way you can make sure no end-user ever has to see any non-interface part of your code.
4,178,028
4,178,329
Giving a function implementation more than one name in c++
Let say I have a basic 2D vector class something like class vector2 { int x, y; } these two values could be used to represent a position as well as a width and height. does C++ provide a away for me to impliment a function such as vector2::getXpos() and then also define vector2::getWidth() and have it use the same i...
It appears you're not thinking about this in an object oriented way. I have to second mjfgates advice that you really don't want to do this. What you want to do is abstract the idea of a vector into a class and implement the common methods you might want to use with a vector. In fact, you may want to consider impleme...
4,178,029
4,178,056
how to convert string value into double format in c++
How do I convert a string value into double format in C++?
Use stringstream : #include <sstream> stringstream ss; ss << "12.34"; double d = 0.0; ss >> d;
4,178,103
4,245,149
How to enable creation of more than one chat room on same socket with boost ASIO? (C++)
So there is great chat server example, but how to create multyile rooms on same chat server with boost asio?
It's not possible to create multiple chat rooms with this example. It's a network programming example not a chat server. The example chat server operates on a socket and doesn't have any logic regarding virtual chat rooms. One chat is bound to a single socket which is blocked for other instances of the chat server. If ...
4,178,132
4,178,148
searching concurrent linked list
I have a concurrent linked list. I need to prioritize finds on this list, so if a thread begins iterating over the list and subsequent insert/delete requests show up I'd want to queue those but if there are find requests from other threads I'd let those happen. What's the best way to implement this situation? EDIT: I ...
Sounds like you are looking for a readers-/writer-lock. This is a lock that can be used to let many threads read the data-structure, but when one thread has write-access, all others are locked out. Boost offers an implementation.
4,178,143
4,178,182
compiling c++ program on windows
I am compiling C++ on VS 2005. When and why use #include and when and why use pre-decleration as class XXXX? What is the benefit of using each option and which one is preffered? I would also glad for a good tutorial on compiling.
Always prefer forward declaration whenever possible. Changes to the referred class file will not trigger recompilation of cpp files including the class using the pre-declared one. This reduces a bit the dependencies. On each place where you are effectively using the class XXXX, you will have to include that header. If ...
4,178,248
4,178,287
I cannot get stdout to update in Qt
I need to call an executable, from my QT application, monitor the output and then display the out put in a text browser. The executable I call from my QT app will run for many hours (~12) and each time the executable spits something out to stdout, I need to parse the output to be able to monitor its progress, then disp...
Look at https://stackoverflow.com/questions/1000674/turn-off-buffering-in-pipe which will remove the buffering and cause you to get input almost immediately (YMMV, I haven't tested this)
4,178,342
4,178,356
Confused about constant objects C++
I'm confused about constant objects in C++ When we have passed a constant object/ reference of a const object is that mean that we cannot edit the attribute values of that object ? or if its not whats the mean or constant in that is it 'refer' object' or 'attributes' also when we return a constant object declaring ...
This syntax: return_type function_name(parameters) const { } Indicates that function_name() may be invoked for an instance of the class that is const. It doesn't have any effect on the const-ness of the return value. const return_type function_name(parameters) { } ...indicates that the value being returned from fu...
4,178,392
4,178,500
How to separate logging logic from business logic in a C program? And in a C++ one?
I am currently coding in C and I have lots of printfs so that I can track, at some times, the flow of my application. The problem is that some times I want more detail than others, so I usually spend my time commenting/uncommenting my C code, so I can get the appropriate output. When using Java or C#, I can generally s...
IME you cannot really separate logging from the algorithms that you want to log about. Placing logging statements strategically takes time and experience. Usually, the code keeps assembling logging statements over its entire lifetime (though it's asymptotic). Usually, the logging evolves with the code. If the algorithm...
4,178,468
4,178,540
Crashed when i delete a c++ object
Possible Duplicate: When to use virtual destructors? [Second dicuss] hi,guys! You are all talking about virtual-destructor. And also i think about the base class`s destructor. But another test as this: class A { public: A() { } virtual void fun() { } private: int mIntA; }; when class A have a vitual...
The A class isn't polymorphic, therefore the delete has no possibility to know that ptrA actually points inside an allocated block and therefore the deallocation crashes.
4,178,535
4,178,615
Help with Pointers, pointers to objects, and classes
I am looking to be pointed in the right direction. I have 1 class Event class Event{ private: vector<string> Question; char Mode;// 1 = Ascending 2 = Descending 3 = None string EventName; public: Event(string Name){ EventName = Name; SetQuestionSize(); SetQuestion(); Mode = 3; ...
Since your Event class doesn't have a default constructor, you need to explicitly construct each object with its name, so the way you're doing it currently is the only way to do it. If you add a default constructor to Event, you can do it in at least two other ways: If you will always have a (small) fixed number of obj...