question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
3,999,400
3,999,494
Error: Field has an incomplete type
quaternion.h:15: error: field ‘v’ has incomplete type Hi! I am stuck on an error that I cannot seem to solve. Below is my code: #ifndef QUATERNION_H #define QUATERNION_H #include "vec3.h" class Vec3; class Quaternion { public: Quaternion(Vec3 v); Quaternion(double w, Vec3 v); Vec3 v; <------------------------...
Well, you have circular inclusion of two header files: vec3.h and quaternion.h. Include guards will make sure that each header is included only once. One of them will be included first, the other - second. In your case quaternion.h is included first, meaning that Vec3 becomes an incomplete type in it. This is what the ...
3,999,470
3,999,748
Memory Fences - Need help to understand
I'm reading Memory Barriers by Paul E. McKenney http://www.rdrop.com/users/paulmck/scalability/paper/whymb.2010.07.23a.pdf everything is explained in great details and when I see that everything is clear I encounter one sentence, which stultifies everything and make me think that I understood nothing. Let me show the e...
What does it mean? It means that if you have: read read read READ BARRIER read read read then the read barrier acts as a "join point" dividing these reads into two batches. All the reads preceding the read barrier will have been done before any read following the read barrier is begun. Which loads in bar() must comple...
3,999,644
3,999,670
How to compare vectors with Boost.Test?
I am using Boost Test to unit test some C++ code. I have a vector of values that I need to compare with expected results, but I don't want to manually check the values in a loop: BOOST_REQUIRE_EQUAL(values.size(), expected.size()); for( int i = 0; i < size; ++i ) { BOOST_CHECK_EQUAL(values[i], expected[i]); } The...
Use BOOST_CHECK_EQUAL_COLLECTIONS. It's a macro in test_tools.hpp that takes two pairs of iterators: BOOST_CHECK_EQUAL_COLLECTIONS(values.begin(), values.end(), expected.begin(), expected.end()); It will report the indexes and the values that mismatch. If the sizes don't match, it will...
3,999,678
3,999,701
Having issues with #includes and incomplete types
I have gotten rid of a circular dependence but am still having issues with another problem. I am still learning and hope that someone can explain to me more about what is wrong with my implementation. Sorry for the trouble, but I really appreciate everyone who is helping me. So, the issue I am having now is that in my ...
You need to add #include "Quaternion.h" to the top of vec3.cpp.
3,999,795
4,023,659
Interfacing GPIB with Qt
I was wondering if it is possible to interface with GPIB Instruments by using C++ and Qt. If it is possible, can anyone tell me how easy it would be and/or point me in a direction for a tutorial or examples? Thanks a lot.
Yes, it should be possible. Part of the package should be a 488.2 API for C programs, which you can also use from a C++ and/or Qt program. You may have to wrap the header file in extern "C", if there is no such line in the header file.
3,999,806
3,999,861
Why not mark everything inline?
First off, I am not looking for a way to force the compiler to inline the implementation of every function. To reduce the level of misguided answers make sure you understand what the inline keyword actually means. Here is good description, inline vs static vs extern. So my question, why not mark every function definit...
Did you really mean #include everything? That would give you only a single module and let the optimizer see the entire program at once. Actually, Microsoft's Visual C++ does exactly this when you use the /GL (Whole Program Optimization) switch, it doesn't actually compile anything until the linker runs and has access ...
4,000,029
4,000,050
"Expected ; before..." with template function to print std::vector<Whatever>
I'm trying to make a pretty-printer for std::vector's of whatever ... doubles, my own custom classes... anything that has a friend std::ostream& operator<<. However, when trying to compile the following function: template <typename T> std::ostream& operator<<(std::ostream& os, std::vector<T> const& list) { std::vect...
The compiler doesn't know you're trying to declare i as variable because that template expression is based on a template parameter. That's why the keyword typename is for. Try this: typename std::vector<T>::const_iterator i = list.begin();
4,000,056
4,000,095
Debugging string from resource with assembly
Here is my issue. I'm trying to learn how to do debugging in assembly with OllyDBG. Usually, when a string is literally in the application, I can find something that points to it, however, this string is from the resource file (when doing WinAPI programming, a resource, .rc, is used). Therefore, given that it is in res...
Put breakpoint to LoadStringW and wait this string. (Of course conditional BP is better than repeatedly press [F9]) But it's better first to do a static analysis (disassemble file), then use OllyDbg to debug it, if needed. For example during static analysis you can find all LoadStringW calls, and find which loads the ...
4,000,064
4,000,083
bool from a struct lead to "error: expression must have class type"
I have a struct defined as struct sData{ idx * id; int * stime; bool * result; unsigned int N; }; Then the code that uses it in numeric compute(numeric e, sData swabs){ numeric cache=0.0; int sid=0; while(sid<swabs.N){ if(swab.result[sid]) cache += log(e); else cache += log(1.0-e); sid ...
swab -> swabs :) The error means that you wrote something like X.Y and X is not an instance of a class/struct.
4,000,219
4,000,249
if/else format within while loop
while(true) { cout << "Name: "; getline(cin, Name); if(Name == "Stop") break; cout << "Additional Name - Y/N: "; getline(cin, additional); if (additional == "Y") cout << "Additional Name: "; getline(cin, Name2); else cout << "Location: "; getline(cin, Location); if(Location == "Stop")...
You have to enclose the statements between the if and the else within brackets { ... }.
4,000,237
4,000,266
Syntax for calling templated method
I'm wondering what's the proper syntax for calling template method given as: struct print_ch { print_ch(char const& ch) : m_ch(ch) { } ~print_ch() { } template<typename T> void operator()() { std::cout << static_cast<T>(m_ch) << std::endl; } private: char m_ch; }; I came up with sth...
You have to tell the compiler explicitly that the operator() of the templated fnct is itself a template: fnct.template operator()<print_type>(); If you don't specify this with the template keyword the compiler will assume that operator() is just a normal method, not a template.
4,000,288
4,003,810
Why should the member function declarations of a class template be all well-formed?
OK, suppose I want to check whether the template parameter has a nested type/typedef XYZ. template <class T> struct hasXZY { typedef char no; typedef struct { char x[2]; } yes; template <class U> static yes f(typename U::XYZ*); template <class /*U*/> static no f(...); enum {value ...
Edit: My question is: why should the member function declararions be all well-formed? Since the compiler instantiates the methods only upon their usage, why does it need correct declaration. Consider the above example2 as a possible use-case of this feature. When implicitly instantiating a class template specializati...
4,000,358
4,000,384
Is possible to get automatic cast from user-defined type to std::string using cout?
As in the question, if I define a string operator in my class: class Literal { operator string const () { return toStr (); }; string toStr () const; }; and then I use it: Literal l1 ("fa-2bd2bc3e0"); cout << (string)l1 << " Declared" << endl; with an explicit cast everything goes right, but if I remove the...
No.. std::string would have to have a constructor that took Literal as an argument. What you could do is overload operator << for your Literal class and have it cast and insert into the stream in there. ostream &operator <<(std::ostream &stream, const Literal &rhs) { stream << (string) rhs; return stream; } ...
4,000,425
4,047,221
OpenFileDialog->DialogShow() results cause errors in SQLite
I have a program that accesses a database using SQLite. When I open a OpenFileDialog or a SaveFileDialog before I do the SQLite call: result = sqlite3_prepare_v2(databaseConnection,converted,10000,&stmt,&strptr); and choose "Cancel", everything works okay (result == SQLITE_OK) but when I choose "Open", even if I don't...
I finally figured out how to fix it. Under the Properties for my dialog box, I had to set the RestoreDirectory property to true. I'm not quite sure how that fixed it unless somehow by changing the directory it made SQLite not be able to find my database file. Thanks for your help!
4,000,555
4,000,620
Can child templates stored in a base class array, use an overloaded virtual function?
In hope to simplify a homework problem dealing with inheritance, I thought it might be better to use polymorphism to accomplish the task. It isn't required, but makes much more sense if possible. I am, however, getting symbol errors making it work as I thought it should or just the base class definition is called. I...
I'm going to leave the type thing aside, though I think you probably don't need it and therefore don't need the template... but, here's what you need: First, the vector should be of pointers: vector<Fruit<int> *> fruits; this prevents slicing (where the Apple part of the object is cut off). Also, now that you have poin...
4,000,593
4,000,638
goto line of code failing to execute
I have always been taught to almost never to use goto statements in programming. However we are required to do so as part of my most recent programming project. I have an if/else statement with various goto statements, and the goto statements are failing to execute. I have no idea why. Any help would be appreciated. ...
This actually has nothing to do with goto. You've got an operator precedence problem. Bitwise and (&) has lower precedence than equality (==). As a result, you're actually doing if ((myInt>>22) & (7 == X)). To fix it, just add some parens: if ((myInt>>22) & 7) == X).
4,000,689
4,004,206
Example for rendering with Cg to a offscreen frame buffer object
I would like to see an example of rendering with nVidia Cg to an offscreen frame buffer object. The computers I have access to have graphic cards but no monitors (or X server). So I want to render my stuff and output them as images on the disk. The graphic cards are GTX285.
You need to create an off screen buffer and render to it the same way as you would render to a window. See here for example (but without Cg) : http://www.mesa3d.org/brianp/sig97/offscrn.htm Since you have a Cg shader, just enable it the same way as you would render to a window. EDIT: For FBO example, take a look here :...
4,000,710
4,000,830
C++ How can I convert a date in year-month-day format to a unix epoch format?
I need to convert a given date to an int containing the number of milliseconds since Jan 1 1970. (unix epoch) I tried the following code: tm lDate; lDate.tm_sec = 0; lDate.tm_min = 0; lDate.tm_hour = 0; lDate.tm_mday = 1; lDate.tm_mon = 10; lDate.tm_year = 2010 - 1900; time_t lTimeEpoch = mktime(&lDate); ...
As specified in the man page, tm_mon is: The number of months since January, in the range 0 to 11.
4,000,772
5,954,692
Visual Studio 2010 - LINK : fatal error LNK1181: cannot open input file " ■/.obj"
I have VS 2010 on Windows 7. I create a new project, chose c++ language, Win32 project, DLL, Export symbols, then finish. Now when I compile the project without any changes to what VS generates, I get... LINK : fatal error LNK1181: cannot open input file " ■/.obj" I also have VS 2008 install on the same machine. I f...
Well it has been a while since posting this questions. I figured out a workaround awhile ago, so now I am going to answer it myself. But if you have any better ideas or additional info others could benefit from, please post. I found that after creating my C++ project, I need to remove the "Microsoft.Cpp.Win32.User" p...
4,000,877
4,000,904
How can I get the current instance's executable file name from native win32 C++ app?
Possible Duplicate: How to get the application executable name in Windows (C++ Win32 or C++/CLI)? How can I get the current instance's file name & path from within my native win32 C++ application? For example; if my application was c:\projects\testapps\getapppath.exe it would be able to tell the path is c:\projects...
You can do this via the GetModuleFileName function. TCHAR szFileName[MAX_PATH]; GetModuleFileName(NULL, szFileName, MAX_PATH)
4,000,949
4,001,006
Syntax Error: identifier 'Edge'?
At the consturctor Node = new Node[numberOfNodes]; and Edge = new Edge[numberOfEdges]; gives identifier error? what's the wrong with it ? typedef struct node { int id; int x; int y; } Node; typedef struct edge { int id; Node node1; Node node2; } Edge; class graph { private: int numberOfNodes; int numberOfEdge...
You have various variable name conflicts, including a conflict between your variable declaration int* Node, and the typedef Node. Also, you declare your array of nodes as type int* when it should be type Node*. You do the same with Edge. Try the following instead: class graph { private: int numberOfNodes; ...
4,001,090
4,001,155
Finding amount of RAM using C++
How would i find out the amount of RAM and details about my system like CPU type, speed, amount of physical memory available. amount of stack and heap memory in RAM, number of processes running. Also how to determine if there is any way to determin how long it takes your computer to execute an instruction, fetch a wor...
With Linux and GCC, you can use the sysconf function included using the <unistd.h> header. There are various arguments you can pass to get hardware information. For example, to get the amount of physical RAM in your machine you would need to do: sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGESIZE); See the man page for al...
4,001,178
4,001,261
How to implement a timer with interruption in C++?
I'm using the GCC compiler and C++ and I want to make a timer that triggers an interruption when the countdown is 0. Any Ideas? Thanks in advance. EDIT Thanks to Adam, I know how to do it. Now. What about multiple timers running in parallel? Actually, these timers are for something very basic. In NCURSES, I have a lis...
One way to do it is to use the alarm(2) system call to send a SIGALRM to your process when the timer runs out: void sigalrm_handler(int sig) { // This gets called when the timer runs out. Try not to do too much here; // the recommended practice is to set a flag (of type sig_atomic_t), and have // code else...
4,001,370
4,001,459
Linux C++ threads are dead, but "hanging" - thread limit
A friend of mine is trying to fix up a custom http server in C++ written for windows to work in Linux. I tried to help him, but all I found seemed too obvious. The app creates a thread for every time a request comes in. The thread serves the request and ends. After some number of requests (something over 300) new threa...
Looks like you've got a bunch of "joinable" threads. They're waiting for someone to call pthread_join() on them. If you don't want to do that (to get the return value of the thread, for example), you can create the threads as 'detached': pthread_t threadID; pthread_attr_t attrib; pthread_attr_init(&attrib); pthread_a...
4,001,448
4,001,505
Qt: How to detect the right clicked item when using customContextMenuRequested signal
hello all quick question im using in Treewidget the customContextMenuRequested signal and using using popup with qmenu How can I get the item pointer / object / reference that just bean right clicked before the popup executed I need to make some validation on the item
That signal contains a QPoint, QWidget::customContextMenuRequested(const QPoint & pos), which you can pass to QTreeWidget::itemAt(const QPoint & p) which returns a QTreeWidgetItem.
4,001,464
4,001,631
Windows current ThreadID without windows API call
I'd like to query the current threadID without making a windowsAPI call. According to this http://en.wikipedia.org/wiki/Win32_Thread_Information_Block wikipedia article it should be possible to access the thread ID directly. I tried this code: void* tibPtr; __asm { mov EAX, FS:[0x18] mov [tibPtr], EAX } int...
If you want to see how Windows does it, simply trace into the function - it's already very fast - doesn't cause a mode switch. However, if you want to avoid even that, you can read the thread id directly out of the TIB at offset 0x24. C with asm is not my strong suit, but something like: int threadId; __asm { mov E...
4,001,517
4,004,035
How is *it++ valid for output iterators?
In example code, I often see code such as *it++ for output iterators. The expression *it++ makes a copy of it, increments it, and then returns the copy which is finally dereferenced. As I understand it, making a copy of an output iterator invalidates the source. But then the increment of it that is performed after crea...
The expression *it++ does not (have to) make a copy of it, does not increment it, etc. This expression is valid only for convenience, as it follows the usual semantics. Only operator= does the actual job. For example, in g++ implementation of ostream_iterator, operator*, operator++ and operator++(int) do only one thing...
4,001,695
4,001,709
Returning value from a function
const char *Greet(const char *c) { string name; if(c) name = c; if (name.empty()) return "Hello, Unknown"; return name.c_str(); } int _tmain(int argc, _TCHAR* argv[]) { cout << Greet(0) << '\t' << Greet("Hello, World") << endl; return 0; } I see 2 bugs with the above code. Ret...
Number 1 is correct. The pointer returned from c_str() is invalidated when name is destroyed. Dereferencing the pointer after name results in undefined behavior. In your tests, under gcc it appears to work; under Visual C++ it prints garbage. Any results are possible when the behavior is undefined. Number 2 is inco...
4,001,760
4,001,818
How to make the read function not to hang?
I'm using socat to create a virtual serial port with: socat PTY,link=/dev/ttySV0,echo=1 PTY,link=/dev/ttySV1,echo=1 The in my program written in C++, I open the ttySV1 port and start to read. The read function is in a while, but the problem is that the read function hangs until I send data to the port. Do you know how...
You could also use a system read function depending on the operating system you are running. The details should be under man (3) read. You would have to set O_NONBLOCK using fnctl. This should cause your read to fail if the pipe / FIFO is currently empty. I checked the man pages for Linux but their should be similar be...
4,001,845
4,001,864
How can I execute a Perl script inside C++ console application?
I am new to C++ programming :). I was wondering what would be the best and easiest approach for this problem. I have a C++ console application and a Perl script. Both of them are to be integrated. To be more specific need to write perl perlscript.pl arg1 in a cmd prompt (to execute the Perl script). perform few action...
It's only "very inefficient" if it has a noticeable impact on the performance of your program. Since it is very easy to call the system() function, you should try this first and see for yourself. Only then should you consider other options. Since any other approach is going involve considerably more work, trying to imp...
4,002,179
4,002,195
C++ MSVS dll headers #include issues
I don't code with lib linking and dll for most of the time, recently when I do, i realized there could be something very wrong with the way i do my #include. Is the following the correct/desirable way to do #include? suppose i have 3 projects (1) dll_A (2) dll_B (3) exe_1. dll_A depends on dll_B, exe_1 depends one dll_...
If dll_B is just an implementation detail of dll-A, then don't include [dll_B.h] from [dll_A.h], just include it from [dll_A.cpp]. Avoiding that header dependency may require a little redesign. E.g. you may want to think about PIMPL idiom for [dll_A]. More details are impossible to state without knowing more details......
4,002,417
4,002,622
Selecting Randomly Lowest Weighted
There are plenty of SO questions on weighted random, but all of them rely on the the bias going to the highest number. I want to bias towards the lowest. My algorithm at the moment, is the randomly weighted with a bias towards the higher values. double weights[2] = {1,2}; double sum = 0; for (int i=0;i<2;i++) { sum +...
How about this: template<typename InputIterator> vector<int> generateWeightMap(InputIterator first, InputIterator last) { int value = 0; vector<int> weightMap; while(first != last) { while((*first)-- > 0) weightMap.push_back(value); ++first; value++; } return ...
4,002,734
4,002,903
C++ Reading Objects from File Error
fstream file; Patient Obj("XXX",'M',"XXX"); file.open("Patients.dat",ios::in|ios::out|ios::app); file.seekg(ios::end); file.write((char*)&Obj,sizeof(Obj)); file.seekg(ios::beg); Patient x; file.read((char*)&x,sizeof(x)); x.printallInfo(); ...
That seems like a brittle and non-portable way to marshal classes. One thing that could be happening with the way you do this is that you aren't making a deep copy of the data you're serializing. for instance, if one of the members of your Patient class is a std::string, a bare pointer is written to the file, but no ...
4,002,757
4,013,659
how to add zlib to an existing qt installation
How can I add zlib to an existing installation of Qt. I m pretty new in this so please give me detailed description! Thanks for your help in advance!
zlib is contained in the core Qt libraries. If you want to use the zlib functions in a Qt program, you only have to include zlib.h which is in src/3rdparty/zlib. See e.g. the implementation of QByteArray in src/corelib/tools. If you want to use quazip, just add the library to your project. It is based on the Qt librari...
4,003,018
4,003,150
Pointer in C++ - Need explanation how it works
http://www.codeproject.com/KB/IP/SocketFileTransfer.aspx?artkw=socket%20send%20a%20file I don't clearly understand this line : // get the file's size first cbLeftToReceive = sizeof( dataLength ); do { BYTE* bp = (BYTE*)(&dataLength) + sizeof(dataLength) - cbLeftToReceive; cbBytesRet = sockClient.Receive( bp, ...
Oh. The funny array arithmetic. The idea is to count from the end, so that when you reach the end you know you're done. In pieces: 1. Find the address of dataLength (BYTE*)(&dataLength) 2. Skip to the end of dataLength + sizeof(dataLength) 3. Back up by the number of bytes we expect to receive - cbLeftToReceive T...
4,003,087
4,003,092
What's the major difference between "union" and "struct" in C.?
Possible Duplicate: Difference between a Structure and a Union in C I could understand what a struct means. But, i am bit confused with the difference between union and struct. Union is like a share of memory. What exactly it means.?
With a union, all members share the same memory. With a struct, they do not share memory, so a different space in memory is allocated to each member of the struct. For example: union foo { int x; int y; }; foo f; f.x = 10; printf("%d\n", f.y); Here, we assign the value of 10 to foo::x. Then we output the value of...
4,003,232
4,003,287
How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers
One of my pet hates of C-derived languages (as a mathematician) is that (-1) % 8 // comes out as -1, and not 7 fmodf(-1,8) // fails similarly What's the best solution? C++ allows the possibility of templates and operator overloading, but both of these are murky waters for me. examples gratefully received.
First of all I'd like to note that you cannot even rely on the fact that (-1) % 8 == -1. the only thing you can rely on is that (x / y) * y + ( x % y) == x. However whether or not the remainder is negative is implementation-defined. Reference: C++03 paragraph 5.6 clause 4: The binary / operator yields the quotient, an...
4,003,292
4,003,474
Does ptr_vector iterator not require increments?
#include <boost/ptr_container/ptr_vector.hpp> #include <iostream> using namespace std; class Derived { public: int i; Derived() {cout<<"Constructed Derived"<<endl;} Derived(int ii):i(ii) {cout<<"Constructed Derived"<<i<<endl;} ~Derived() {cout<<"* Destructed Derived"<<i<<endl;} }; int ...
Is my technique of iteration and using the iterator correct? No, erasing from a container generally invalidates the iterator to the erased item. If it works, this is just a side-effect of the implementation details. The correct way would be to use the return value of the erase method: it = pv.erase(it); However, fo...
4,003,314
4,003,326
Howto make a var. name with a var. in C/C++?
I have some vars live: int foo1; int foo2; .. and I want to reach them from: for (int i = 1;i<=2;i++) { // howto get foo1 and foo2? } how to get them? EDIT, end what when it will be no int but a Opject *pointer;?
You can't; you need an array of some kind. e.g.: int foo[2]; /* Two elements, foo[0] and foo[1] */ for (int i = 0; i < 2; i++) { foo[i] = i; } or: int foo1; int foo2; int *p[] = { &foo1, &foo2 }; /* Array of pointers */ for (int i = 0; i < 2; i++) { *p[i] = i; /* Changes foo1 or foo2 */ } I don't fully...
4,003,584
4,003,627
More elegant way to check for duplicates in C++ array?
I wrote this code in C++ as part of a uni task where I need to ensure that there are no duplicates within an array: // Check for duplicate numbers in user inputted data int i; // Need to declare i here so that it can be accessed by the 'inner' loop that starts on line 21 for(i = 0;i < 6; i++) { // Check each ot...
You could sort the array in O(nlog(n)), then simply look until the next number. That is substantially faster than your O(n^2) existing algorithm. The code is also a lot cleaner. Your code also doesn't ensure no duplicates were inserted when they were re-entered. You need to prevent duplicates from existing in the first...
4,003,615
4,003,672
Gradient direction computation
I'm working on my task in computer vision course. One of sub-tasks is gradient direction computation based on image brightness. I've made a matrix bright[width][height] containing brightness values for every pixel of the image. And i have two such functions: double Image::grad_x(int x,int y){ if(x==width-1 || x==0)...
Your computation is correct. It is a simple gradient method you're using, but if that's fine for your use there is nothing wrong with that. The corner cases are a problem because you don't have enough data to calculate a gradient in the same way as the other pixels. One way to deal with them is to simply not calculate ...
4,003,634
4,003,668
Changing window background colour
In the winAPI, how do I change the window background colour? For example, wc.hbrBackground = ....; is for setting the window background initially, but how do I change it there after? Thanks.
Use the SetClassLongPtr function with the GCLP_HBRBACKGROUND argument: SetClassLongPtr(windowHandle, GCLP_HBRBACKGROUND, brushHandle); http://msdn.microsoft.com/en-us/library/ms633589%28VS.85%29.aspx
4,004,015
4,004,027
Advantages of using arrays instead of std::vector?
I'm currently seeing a lot of questions which are tagged C++ and are about handling arrays. There even are questions which ask about methods/features for arrays which a std::vector would provide without any magic. So I'm wondering why so much developers are chosing arrays over std::vector in C++?
In general, I strongly prefer using a vector over an array for non-trivial work; however, there are some advantages of arrays: Arrays are slightly more compact: the size is implicit. Arrays are non-resizable; sometimes this is desirable. Arrays don't require parsing extra STL headers (compile time). It can be easier t...
4,004,049
4,004,056
Why is my C++ Game of Life not working properly?
This compiles and runs okay, but the results are totally different from what they should be. I've snipped irrelavent code: bool grid[1280][1024]; // hardcoded to my screen res for now for (int x = 0; x<1280; x++) //init grid to false { for (int y = 0; y<1024; y++) { grid[x][y] = false; } } gri...
Firstly, it doesn't work because you haven't separated each cell's results, i.e., if grid[0][0] dies, then this will be immediately reflected on grid[1][0]'s life or death, which is not how Game of Life works. Secondly, it doesn't work because you don't appear to have run the game more than one iteration.
4,004,084
4,004,219
Grayscale blending with OpenGL?
Is there a way to set the blending parameters so the whole scene renders in grayscale? (without using GLSL, only pipeline functions) Thanks
No, all colors are separated. You need a pixel shader for that
4,004,138
4,004,379
Cleanly duplicate an instance of a baseclass or subclass in C++?
In the trivial example inheritance hierarchy: class Food { virtual ~Food(); }; class Fruit : public Food { virtual ~Fruit(); }; class Apple: public Fruit { virtual ~Apple(); } class Vegetable: public Food { virtual ~Vegetable(); } I wish to create a method that can clone an object from its subclass ...
You can use the CRTP to automatically implement a Clone method. template<typename T, typename Derive> class CloneImpl : public Derive { public: virtual Derive* clone() { return new T(static_cast<const T&>(*this)); } }; class Food { public: virtual Food* clone() = 0; virtual ~Food() {} }; class F...
4,004,217
4,004,265
OOP, assignment operator does not work
This is from my code: struct R3 { float x; float y; float z; R3(float, float, float); R3(); }; R3::R3(float a, float b, float c) { x = a; y = b; z = c; } R3::R3() { x = 0; y = 0; z = 0; } struct Bodies { int Mass; float...
Your Place, Speed and Acc members are declared as functions. Use: struct Bodies { int Mass; float Dist[100]; R3 Place; R3 Speed; R3 Acc; instead. And use initialization in the constructor: Bodies::Bodies(int M, R3 XYZ, R3 V, R3 A): Mass(M), Place(XYZ), Speed( V ), Acc( A ){} instea...
4,004,225
4,004,255
Why is this giving me a segfault?
This: bool grid[1280][1024]; for (int x = 0; x<1280; x++) { for (int y = 0; y<1024; y++) { grid[x][y] = false; } } works fine, but bool grid[1280][1024]; bool grid2[1280][1024]; for (int x = 0; x<1280; x++) { for (int y = 0; y<1024; y++) { grid[x][y] = false; grid2[x][y] = ...
Probably not enough stack space, your second example also crashes on my PC. Try allocating on the heap, or even better, use a proper container class: #include <array> #include <vector> typedef std::array<bool, 1280> line; int main() { std::vector<line> grid(1024); std::vector<line> grid2(1024); // no ini...
4,004,445
4,004,458
how to reverse engineer c++ project?
as asked above. cheers in advance
Examine the assembler code. Turn it back into C++. Profit. Admittedly, there a fair bit of detail you could add to steps 1 and 2 but that's the basic idea, and the level of detail in my answer more than match the level of detail in your question :-)
4,004,519
4,004,703
randomise a two-dimensional array with chars?
Is this code a good solution to randomise a two-dimensional array and write out all the symbols on the screen? If you have a better tip or solution please tell me. int slumpnr; srand( time(0) ); char game[3][3] = {{'O','X','A'}, {'X','A','X'}, {'A','O','O'}}; for(int i = 0 ; i < 5 ; i++) { slumpnr = rand()%3; ...
You don't need the if/else chain. Simply use the random variable as an index into your array: int r = rand() % 3; cout << " " <<game[r][0] << " | " << game[r][1] << " | " << game[r][2] << "\n"; cout << "___|___|___\n"; Oh, I just noticed you have a weird mapping from 1 to 0 and from 0 to 1. If that is really necessary...
4,004,673
4,004,680
Class variable within its definition?
This is probably a dumb question. I am trying to make a text-mud. I need each Room class to contain other Room classes that one can refer to when trying to move to them or get information from them. However, I can not do that because I obviously can not declare a class within its definition. So, how do I do this? Here'...
It's not possible to have a Room member variable. You could use a pointer or reference though. class Room { public: Room* NorthRoom; Room* EastRoom; Room* SouthRoom; Room* WestRoom; };
4,004,873
4,005,713
what video/image encoding format is recommended when trying to encode and transmit raw video in real time?
I'm trying to encode and transfer raw video frames over LAN (100 Mbps) connection (frames captured by a web cam). What video/image encoding format is recommended for fast compression (with not much regard for the compression ratio) ? Thanks,
If you need individual frames to be independent of one another, use mjpeg (which is equivalent to encoding each frame as a jpeg). It's simple and you have plenty of tools with which to manipulate it. Otherwise, as long as you have a remotely modern cpu and the resolution isn't insanely high, just use a simple mpeg4 asp...
4,004,963
4,004,985
Check for null pointer
I'm building a iphone app and using c++ and am having trouble checking if a pointer is null. IMyInterface* myInterface; if ( !myInterface ){ //doesn't work myInterfacee->doSometing(); } if ( myInterface != 0 ) { //doesn't work myInterfacee->doSometing(); } if (...
Your basic problem here is that you haven't initialized myInterface. Assuming myInterfacee is just a typo, the following would all be fine, and none of them would call doSometing: IMyInterface* myInterface = 0; if ( myInterface ){ // ! removed myInterface->doSometing(); } if ( myInterface != 0 ) ...
4,005,067
4,005,083
C++ Failing at SOCKET accept() Method
I am currently make a Server, I learned to make something like this: while(true) { SOCKET s = accept(s, ....) // do something with the connection printf("connection\n"); } I learned that it will stuck at accept(..) while there isnt a connection. In my Program there isnt any connection yet, but it get o...
Most likely it returns immediately with an error which you don't seem to be checking. E.g. it may be that s wasn't properly created, etc. Edit: just noticed that you are assigning the result of accept() to the same 's', which is terribly wrong. Your 's' is a general listening socket presumably created by socket(), boun...
4,005,086
4,005,095
C++ template specialization
Hello! Does someone know a way to achieve or emulate the following behaviour? (this code results in compilation-time error). E.g, I want to add specific template specialization only in derived classes. struct Base { template <typename T> void Method(T a) { T b; } template <> void Method<int>(int a) { ...
How about overloading struct Base { template <typename T> void Method(T a) { T b; } void Method(int a) { float c; } }; struct Derived : public Base { using Base::Method; void Method(float a) { float x; } }; Explicit specializations can't be added like that in your example. In a...
4,005,097
4,005,640
for-loop to compare the two-dimensional array???Help!
I am currently developing a game in which a player plays slot machine.The game is based on that the user stops in money, 100sek, 300sek or 500sek. Then the user makes a bet for each game. The one-armed bandit randomly spits out 3 different symbols in nine pieces fields. See figure: The goal of the game is to obtain as...
I'm not sure that I understand your requirements perfectly but have decided to interpret them as best I can. This code does what I think you want. I've used 0, 1 and 2 as the characters but you can easily swap them for whatever you want in the output. I've also not bothered calculating the payout since you've written t...
4,005,260
4,005,419
c++ metaprogramming madness
consider the following templated datastructures enum eContent{ EINT = 1, EFLOAT = 2, EBOOL = 4 }; template<int> struct Container{ Container(){assert(false);} //woops, don't do that! }; template<> struct Container<EINT>{ Container():i(123){} int i; }; template<> struct Container<EFLOAT>{ C...
enum eContent{ eInt = 1, eFloat = 2, eBool = 4 }; template<unsigned, unsigned> struct Member {}; template<> struct Member<eInt, eInt>{ Member():i(123){} unsigned i; }; template<> struct Member<eFloat, eFloat>{ Member():f(123.456f){} float f; }; template<> struct Member<eBool, eBool...
4,005,284
4,005,316
insert to sorted position linked list
I have question quite much related to this one I asked a while ago place a value in the sorted position immediately I wonder if you can use the same approach in that you step backward in a linked list to find the position it should be inserted into. If it is possible how do you loop a linked list backward? I can't figu...
You can't traverse a singly-linked list backward, but you can keep a pointer to the last two elements you have seen instead of just one. So, traverse the list from the front, and keep two pointers: current, and previous. If the element you are inserting is less than current, then update previous to point to it.
4,005,407
4,005,437
What is Operator overloading? Is operator overloading a specific feature to C++ and not available in Java
Please explain in detail with examples. Thank you
Operator overloading is a feature where the language allows you to define operators for your own types, so that you can write e.g. o1 + o2 where o1 and o2 are instances of your own type, instead of built-in types. Operator-overloading is not specific to C++, but it's not available in java. Here's an example in Python: ...
4,005,458
4,005,515
What does this mean: "error: invalid combination of multiple type-specifiers"
I'm getting a compiler error on FreeBSD: error: invalid combination of multiple type-specifiers From the C++ Code: typedef unsigned off_t uoff_t; Not sure what the gcc compiler is trying to tell me.
Use typedef std::make_unsigned_t< off_t > uoff_t; since C++14 instead to achieve the desired effect. Use typedef std::make_unsigned< off_t >::type uoff_t; since C++11. Use typedef boost::make_unsigned< off_t >::type uoff_t; before C++11.
4,005,485
4,005,509
how to overload == operator to allow it to be used in multiple comparisons?
I am trying to overload == operator to compare objects like below. class A { int a; public: A(int x) { a = x; } bool operator==(const A& obRight) { if(a == obRight.a) { return true; } return false; } }; int main() { A ob(10), ob2(10), ob3(10); if(...
No. You fundamentally misunderstood your operation. if (ob == ob2 == ob3) = if (ob == (ob2 == ob3) Think about the types. if (A == (A == A)) if (A == bool) // Oh dear, no == operator for bool! You need to have if ((ob == ob2) && (ob == ob3)) if ((A == A) && (A == A)) if (bool && bool) // fine
4,005,504
4,005,543
Check Input in Visual C++ using C commands
I want to use the following code just to check the input. #include <stdio.h> #include <iostream> #include <ctype.h> int main() { int number1; puts("Enter number 1 please:"); scanf_s("%d",&number1); if (isdigit(number1)) { puts("Input is correct."); } else { puts("Y...
Your problem is in the use of isdigit. Compare this code: int main() { int number1; puts("Enter number 1 please:"); scanf_s("%d",&number1); printf("You entered %d\n", number1); if (isdigit(number1)) { puts("Input is correct."); } else { puts("Your input is not correct. Enter a number please."); } std::cin....
4,005,506
4,005,553
Windows C++ Pipe Creates Big Black Terminal Window
I'm trying to pipe io through a terminal application as per microsoft's documentation (http://msdn.microsoft.com/en-us/library/ms682499(VS.85).aspx). The problem is, when I add this code, it pops up a big black empty box / terminal / console window. I don't want it to do that. Suggestions? Thanks!
Make sure that the dwFlags member of the STARTUPINFO structure has the STARTF_USESHOWWINDOW bit set and that the wShowWindow is set to SW_HIDE. That should work
4,005,552
4,005,576
Objective C member in C++ class
Is it possible to have a objective c member in a c++ class @interface ObjectiveCClass : UIViewController { int someVarialbe; } - (void)someFunction; @end class CPlusPlusClass{ ObjectiveCClass obj; // have a objective c member void doSomething(){ obj.someFunction; // an...
To create header files that can be shared between obj-c and cpp code, you could use the compiler predefined macros to do something like: // A .h file defining a objc class and a paired cpp class // The implementation for both the objective C class and CPP class // MUST be in a paired .mm file #pragma once #ifdef __OBJ...
4,005,601
4,005,664
How do I invoke the nothrow version of delete?
I have the following code, which doesn't compile: int *p = new(nothrow) int; delete (nothrow) p; //Error The error I get is: error C2440: 'delete' : cannot convert from 'const std::nothrow_t' to 'void*' Does a nothrow version of delete exist? If so, how can I invoke it? In C++: The Complete Reference, it's given t...
A std::nothrow_t deallocation function exists, but you cannot call it with a delete expression. The deallocation function is there for completeness. If a new expression fails because of an exception, the compiler needs to free the memory it allocated via operator new with a matching call to operator delete. So there ne...
4,005,626
4,005,648
What is the closest thing to Pex for Visual C++?
Pex automagically generates unit tests for C# code. Is there anything similar (free or commercial) for C++ code?
If you're using Visual Studio 2005 or newer, you can use Team Test. Here is a guide on how to use it.
4,005,777
4,006,058
How to cover all possible data types when declaring a function parameter?
I'm attempting to construct a function that will perform a sanity check on the user's response to a number of questions, each of which would ideally be a non-zero integer. How can I construct a function that would be able to accept a parameter of any data type, but only have a single parameter? For example: bool Sanity...
C++ is a statically typed language. What type a variable is of will be fixed at compile-time and cannot be changed at run-time. What users enter, however, will only be known at run-time, and cannot be known at compile-time. Therefore your question makes no sense. When you expect an integer from a user, then the best ...
4,005,823
4,005,842
Non-member static templated method definitions in C++?
Can I call a non-member static templated function from a static member function where the definition is split into header and cpp: // zero.cpp class Zero { static void zero() { one(5); } }; // one.h template <typename T> static void one(T& var); // one.cpp template <typename T> void one(T& var) { } // main.cp...
Template definitions need to be visible at the point of instantiation. That is, it needs to be in the header somehow: // one.hpp template <typename T> static void one(T& var) { // definition visible in header } Though I'm not sure why you'd want it to be static.
4,005,860
4,005,879
Catch with multiple parameters
First I found in cplusplus.com the following quote: The catch format is similar to a regular function that always has at least one parameter. But I tried this: try { int kk3,k4; kk3=3; k4=2; throw (kk3,"hello"); } catch (int param) { cout << "int exception"<<param<<endl; } catch (int param...
(kk3, "hello") is a comma expression. The comma expression evaluates all of its arguments from left to write and the result is the rightmost argument. So in the expression int i = (1,3,4); i becomes 4. If you really want to throw both of them (for some reason) you could throw like this throw std::make_pair(kk3, std...
4,005,865
4,005,930
Stack unwinding in C++ when using Lua
I recently stumbled into this this C++/Lua error int function_for_lua( lua_State* L ) { std::string s("Trouble coming!"); /* ... */ return luaL_error(L,"something went wrong"); } The error is that luaL_error use longjmp, so the stack is never unwound and s is never destructed, leaking memory. There are a few ...
If I understand correctly, with Luabind functions that throw exceptions are properly caught and translated anyway. (See reference.) So whenever you need to indicate an error, just throw a standard exception: void function_for_lua( lua_State* L ) { std::string s("Trouble coming!"); /* ... */ // translated i...
4,005,926
4,006,111
How do I convert this OpenGL makefile from Linux to Mac OS X?
I'm trying to compile a OpenGL program on my MacBook and can't figure out how to convert this makefile. CFLAGS= -I/usr/X11R6/include -I/usr/local/include LDFLAGS= -L/usr/X11R6/lib -L/usr/local/lib -lGL -lGLU -lm -lglut BINARIES=q2 all: $(BINARIES) clean: -rm *.o $(BINARIES) q2 : q2.o g++ $(LDFLAGS) $^ -o q2 ...
Change the source code #ifdef __APPLE__ #include <GLUT/glut.h> #else #include <GL/glut.h> #endif Don't include GL.h or GLU.h. glut.h should pull them for you regardless of the platform. And change your Makefile CFLAGS= LDFLAGS= -framework GLUT -framework OpenGL -framework Cocoa Note that I was also able to build so...
4,005,943
4,006,133
What does this mean: "warning: comparison between 'enum A<B>' and 'enum A<B>'"?
I added following at line 42 of proto.h: typedef boost::make_unsigned<off_t>::type uoff_t; And now I get this verbose and confusing warning from gcc complaining about comparing an enum to the same enum type: In file included from proto.cpp:12: /usr/local/include/boost/type_traits/is_unsigned.hpp: In instantiation of '...
This is what happens BOOST_NO_INCLASS_MEMBER_INITIALIZATION gets defined in Boost.Config (not sure why it would for gcc, but I'll leave that alone for the moment). Thus, BOOST_STATIC_CONSTANT(no_cv_t, minus_one = (static_cast<no_cv_t>(-1))); BOOST_STATIC_CONSTANT(no_cv_t, zero = (static_cast<no_cv_t>(0))); declaration...
4,005,970
4,005,987
Simplest way to show a clock in C++ and Linux
I'm using C++ under Linux compiling with standard GCC. In my program I want to add a simple clock showing HH:MM:SS. What's the easiest way to do that?
A good way is to use localtime
4,006,160
4,006,173
In C++, initialize a class member with 'this' pointer during construction
I'd like to create a class that is associated to another class in some sort of parent-child relationship. For this the "child" class needs a reference to it's parent. For example: template <typename T> class TEvent { private: T* Owner; public: TEvent(T* parent) : Owner(parent) {} }; class Foo { private: TE...
It is OK to use this in the initialization list, as long as it is not used to access any members that may not have been initialized yet.
4,006,347
4,006,354
Character encoding problem
Greetings, I'm developing a project in C++ where I want to use characters like á é õ and ┌ ─ ┐ │ to draw a couple of nice frames. My doubt resides in what I should change in my code/project settings since, without any kind of modifications, the console just prints pseudo-random characters. I know that the above charac...
I think the best way to do it would be to use wchar and wstring for the characters - they are meant for locale-independant string operations and are defined as UTF-16 in Windows and as UTF-32 in Linux. Note that you need to use the proper functions, for example wprintf instead of printf... If you're using iostream, I t...
4,006,348
4,006,466
mknod(2) requires superuser on FreeBSD what to use instead?
I am porting from Linux to FreeBSD and have run into ::mknod() failing with errno: [EINVAL] Creating anything else than a block or character spe- cial file (or a whiteout) is not supported. But I also see it states earlier on the man page: The mknod() system call requires super-user privi...
According to the Linux man page for mknod(2): POSIX.1-2001 says: "The only portable use of mknod() is to create a FIFO-special file. If mode is not S_IFIFO or dev is not 0, the behavior of mknod() is unspecified." So your use of it in this manner is non-portable and not recommended. open(2), however, seems to have t...
4,006,553
4,006,560
Problem with const qualifiers to get private atributes of an object
I'm a completely new to C++ and I'm having a very stupid problem. I have a Graph class and I need to create a copy constructor for it. This is my class: #include <igraph.h> #include <iostream> using namespace std; class Graph { public: Graph(int N); // contructor ~Graph(); // destructor Graph(const Graph&...
The getGraph function needs to be declared with the const qualifier: const igraph_t* getGraph() const { ... } This is because other is a constant reference. When an object or reference is constant, you can only call member functions of that object which are declared with the const qualifier. (The const which appears ...
4,006,581
4,006,590
How to make user input multiline string data in c++?
I tried getline(cin, .... ), but this cannot take input more than one line. The end of input is determined by something like #.
You can use getline with a different character than '\n' as the delimeter. // will collect input until the user enters a # getline(cin,mystring,'#');
4,006,597
4,006,721
Reading files slow on Windows 7
Basic c++ question here. I'm trying to read a large file on Windows 7 Pro. C++ compiler is Visual Studio 2010. (ver 16.0). I'm finding that the program runs about 5 times slower on Windows 7 than one on a virtual machine running Ubuntu on the same box. Ubuntu version 10.04 using gcc 4.4.3. The file is rather large ~900...
If you are concerned with performance I would recommend to step out of the C++ world and into Win32 API file handling (e.g. memory mapped files, boost has a library for that).
4,006,603
4,006,614
overloading ostream for any function that returns a vector
Hi assume that I have class A : using namespace std; template <class T> class A{ private: vector<T> my_V; public: // assume initializations etc are done inline vector<T> get_v() { return my_v; } }; and some where else I have overloaded ostream of std::vector template <class T> ostream & operator<<(ostream& out...
Your operator<< overload takes a non-const reference. Your A<T>::get_v() function returns a std::vector<T> by value; this returned object is a temporary. A non-const reference cannot bind to a temporary object. Your overload needs to take a const reference (const std::vector<T>&).
4,006,634
4,006,640
std::vector push_back is bottleneck
Here is what my algorithm does: It takes a long std::string and divides it into words and sub words based on if it's greater than a width: inline void extractWords(std::vector<std::string> &words, std::string &text,const AguiFont &font, int maxWidth) { words.clear(); int searchStart = 0; int curSearchPos...
Generally, if adding elements to a vector is a bottleneck, you should use std::vector<T>::reserve to reserve some space in advance. This should reduce the likelihood that a call to push_back will trigger a memory reallocation. That said, string processing in general can be pretty CPU intensive, and reallocating a vect...
4,006,727
4,006,749
#include <CEGUI/RendererModules/Ogre/CEGUIOgreRenderer.h> doesn't include ogre headers correctly
Using Ubuntu 10.10 I have compiled and installed the latest Ogre and CEGUI libraries. I can #include for example but when I try to add the CEGUI headers I have issues. #include <CEGUI/RendererModules/Ogre/CEGUIOgreRenderer.h> This in turn includes OgreBlendMode.h and OgreTextureUnitState.h but doesn't have the OGRE/ ...
Put the OGRE directory in your default include path.
4,006,736
4,006,761
C negative array index
this is my struct : struct Node { struct Node* data; struct Node* links[4]; } assuming there is no padding, does Node->links[-1] guaranteed to be pointing on Node::data ?
No guarantee; this is undefined behaviour: Compiler-dependent structure padding Standard only defines array indexing between 0 and length (inclusive) Possible strict-aliasing violation In practice, it's quite possible that you will end up pointing at data, but any attempts to access it will result in UB.
4,006,854
4,010,952
Qt C++ tcp client with python twisted server
I'm trying to connect a very basic twisted "hello world" server with a basic Qt tcp client. The client uses these Signals: connect(&socket, SIGNAL(connected()), this, SLOT(startTransfer())); connect(&socket, SIGNAL(readyRead()), this, SLOT(readServer())); and then readServer() looks like this: ui->resultLabel->setText...
The issue turned out to be QDataStream, which is apparently more than just a little particular about the data it's reading. Thankfully, I discovered QDataStream::readRawData which liked data being sent by python a lot better (further I discovered this had nothing to do with twisted, but the python socket implementation...
4,006,883
4,006,901
Unnecessary locking in STL? (Visual C++ Express)
I'm trying to build a Tetris AI algorithm that can scale over multiple cores. In my tests it turns out that using multiple threads is slower than using a single thread. After some research I found that my threads spend most of their time waiting for _Lockit _Lock(_LOCK_DEBUG). Here's a screenshot. As you can see, the l...
If you're spending time in LOCK_DEBUG, then you are using the debugging iterators. These iterators all track their positions and parent containers, and detect several cases of undefined behavior for you. They do, however, impose a runtime cost. Compile in release mode and see if that's still a bottleneck. There might b...
4,007,091
4,007,109
Templated classes in a union?
I'm trying to get the maximum size of any possible instance of my template as a compile time constant. The first thing that came to mind was something like this... union TestUnion { template<typename T> class MyClass { public: MyClass() { }; MyClass(T& t) : _t(t) { } private: T _t; }; }; But sizeof(TestUni...
You are getting the size of a union that has no members. Declaring a template within a union scope doesn't declare any union members. In C++ (and also I believe C) it is guaranteed that all class or union types occupy at least 1 byte of space. So that's why the size is 1. There is no way to get the maximum possible ...
4,007,112
4,007,134
C++ and command line options
Is it bad form to use the GNU getopt in C++ programs? Is there a C++ specific alternative, or should I still just use getopt?
There is nothing wrong with using getopt. There are a multitude of object oriented alternatives floating around including Boost.Program_options, and classes in POCO, and ACE.
4,007,179
4,007,221
Concept checking of static member variables compile error on gcc
I'm trying to apply the technique described in http://www.drdobbs.com/tools/227500449 With the sample code below, I expect the output: 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 And this is indeed what happens if I compile using clang. But with gcc, this code gives the following errors: junk.cpp: In instantiation of ‘cons...
Your code is correct. Is clang correct and this is a gcc bug? Yes most probably. Comeau confirms that your code is correct.
4,007,254
4,007,256
Overwriting Data in a C++ File using fstream
Hi i want to overwrite the content(object) in a specific file i have set the position but it always add to the end of the file Code int InputIO::editPatient(int location,Obj P){ int positon=location*sizeof(P); f.open("File.dat",ios::in|ios::out|ios::app|ios::binary|ios::ate); f.seekp(0,ios::be...
Just solve this have to remove ios::app (Append) Append always add to the end of the file
4,007,335
4,007,705
C++ enum data structure
Can someone give me a real time need for enum data structure. As in example in some real system where it can be used? And what is the reason for having such a data structure. The example given was enum colors_t {black, blue, green, cyan, red, purple, yellow, white}; But i felt, this is similar to string array. I am ...
For the record, Bjarne Stroustrup talks about bringing enums into C++ in the book The Design and Exolution of C++ with the statement "C enumerations constitute a curiously half-baked concept. Enumerations were not part of the original conception of C and were apparently reluctantly introduced into the language as a co...
4,007,362
4,007,366
Exception Handling problem in C++
Hii , I am new to C++ programming and need some help regarding the code i wrote below.... Its a basic exception handling program #include<iostream> class range_error { public: int i; range_error(int x){i=x;} } int compare(int x) { if(x<100) throw range_error(x); ...
class range_error { public: int i; range_error(int x){i=x;} }; // <-- Missing semicolon. int compare(int x) { if(x<100) throw range_error(x); return x; } Here's how your code should probably look: #include <iostream> #include <std...
4,007,589
4,007,715
Multithreading an OpenGL/WinAPI application
NOTE: Please read the whole thing before posting, you'll see why. So I have an OpenGL/WinAPI application. I'm doing what you would expect, by doing cycles of handling messages, then rendering a frame, handling messages, rendering frame... The trouble is, when I resize or move a window, the screen freezes, and it can lo...
When the user clicks on the non client areas of a window to move or size a window, DefwindowProc goes into a modal loop, so your game loop is no longer being executed - until the user cancels or finishes the modal operation. There are window messages you can use to detect the start and end of modal operations: WM_ENTE...
4,007,620
4,080,600
How to read a multi-session DVD disk size in Windows?
Trying to read the sizes of disks that were created in multiple sessions using GetDiskFreeSpaceEx() gives the size of the last session only. How do I read correctly the number and sizes of all sessions in C/C++? Thanks.
You might want to look at the DeviceIoControl API function. See here for control codes. Here is a code example that retrieves the size of a CD disk. Substitute CreateFile(TEXT("\\\\.\\PhysicalDrive0") for e.g. CreateFile(TEXT("\\\\.\\F:") /* Drive is F: */ if you wish. Note: The page says that DeviceIoControl c...
4,007,734
4,007,739
C++ fstream Erase the file contents from a selected Point
I need to Erase the file contents from a selected Point (C++ fstream) which function should i use ? i have written objects , i need to delete these objects in middle of the file
C++ has no standard mechanism to truncate a file at a given point. You either have to recreate the file (open with ios::trunc and write the contents you want to keep) or use OS-specific API calls (SetEndOfFile on Windows, truncate or ftruncate on Unix). EDIT: Deleting stuff in the middle of a file is an exceedingly pre...
4,007,761
4,013,130
ThreadQueue - Development for Servers - C++
Today i got a idea to make an ThreadQueue for C++, for my Server Application. unsigned int m_Actives; // Count of active threads unsigned int m_Maximum; std::map<HANDLE, unsigned int> m_Queue; std::map<HANDLE, unsigned int>::iterator m_QueueIt; In an extra Thread i would to handle these while: while(true) { i...
You can use WaitForMultipleObjects to wait while any of started threads is ended. Or, what is probably better in this case in each thread you can send an EVENT before stopping it. Than, the monitor thread should only wait and process this event. But, to be honest, your description and source is rather tricky....
4,007,865
4,007,924
Few questions about the C++ preprocessor:
A few questions about the C++ preprocessor: how to make the preprocessor go to a new line into the preprocessoring code? how to make the preprocessor insert a tab character or multiple spaces into the preprocessoring code? how to make the preprocessor insert comments into the preprocessoring code?
1) use the backslash, as Tim pointed out 2) I don't think you can 3) #define COMMENT /##/ this is a comment #define CPPCOMMENT(c) /##/ c #define CCOMMENT(c) /##* c *##/ COMMENT CPPCOMMENT(This is a c++ comment) CCOMMENT(This is a c comment) Edit 2 Caveats 1) Doesn't work in all compilers. 2) Don't do this, it's stupi...
4,007,959
4,783,799
Which linker setting determines the load path of a shared library?
I have built the Poco C++ library on Mac. When inspecting the built output files I notice that their load paths are absolute paths that point to the build directory. For example: $ otool -L libPocoFoundation.dylib libPocoFoundation.dylib: /Users/francis/orig/poco-1.3.6p2/lib/Darwin/i386/libPocoFoundation.9.dylib (c...
Related question at stackoverflow.com "How to set the runtime path (-rpath) of an executable with gcc under Mac OSX?" explains some ways to do it at compile-time. BTW: I've reproduced your POCO bug on MacOS Leopard and opened a bug 3164792 for POCO-1.4.0
4,008,041
4,008,101
Application structure
class Base { private: bool mEnabled; public: bool getEnabled() { return mEnabled; } }; class First : public Base; { // ... }; class Second : public Base { Second() { // I have to check First::mEnabled } }; class Manager { First obj1; Second obj2; }; I have some class manager which hand...
Instead of static you probably would check for getEnabled in your class manager: if( obj1.getEnabled() ) { Second obj2; } The problem is that you want to get access to another class without any relation between them. So a more top-level class needs to create this relation.
4,008,085
4,008,096
Standard C++ and MFC wrapper
Firstly, I want to have a clearly overall look at MFC, Win32API . Is: Win32API: The first layer between hardware and software in prog [ except assembly ] MFC : A wrapper by Microsoft ? It helps us in design GUI and a lot of library for easier and faster programming. My problem is : I want an easy coding in GUI, no need...
Win32 is the C API to the Windows OS, not to hardware. Many of these functions ask the OS to manipulate hardware on your behalf. MFC is the original C++ "wrapper" to Win32. It's fairly old now, so if you want "easy coding", may I suggest you look at .NET instead.
4,008,106
4,008,113
C++ Iterate an istream
What is the best way to parse or iterate an istream? I need to create a function that takes an istream, parses it and creates an object so was wondering the easiest way to do this. Even something that could convert it to string would be dandy.
You can use an istream_iterator. typedef std::istream_iterator<std::string> streamiter; for (streamiter it = streamiter(some_istream); it != streamiter(); it++) { // process words } This will split the input stream at all whitespaces.