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
2,742,514
2,744,576
QT warning level suggestion
What is the warning level you use while compiling QT projects? When I compiled with W4, I'm getting a lot of warnings such as: C4127: conditional expression is constant Should I compile at W3, or find other ways to handle warnings at W4, such as: adding a new header file and using pragma's(mentioned here C++ Coding St...
I ran into the exact same problem you have a couple of years ago, that of setting the compiler to level 4 warnings to catch as many potiential problems as possible. At the time, I had a support contract with Qt and asked them why their code generated so many warnings. Their response was that they never gaurenteed tha...
2,742,549
2,742,576
Using STL/Boost to initialize a hard-coded set<vector<int> >
Like this question already asked, I'd like to initialize a container using STL where the elements are hard-coded in the cleanest manner possible. In this case, the elements are a doubly nested container: set<vector<int> > A; And I'd like (for example) to put the following values in: A = [[0,0,1],[0,1,0],[1,0,0],[0,0,0...
This does use g++ 4.4.1, with -std=c++0x #include <set> #include <vector> using namespace std; int main() { set<vector<int>> A = {{0,0,1},{0,1,0},{1,0,0},{0,0,0}}; }
2,742,708
2,756,633
Socket select() Handling Abrupt Disconnections
I am currently trying to fix a bug in a proxy server I have written relating to the socket select() call. I am using the Poco C++ libraries (using SocketReactor) and the issue is actually in the Poco code which may be a bug but I have yet to receive any confirmation of this from them. What is happening is whenever a co...
It appears you are correct Remy. I managed to distinguish whether the socket had disconnected using the following code (this was added to Poco/Net/src/SocketImpl.cpp): bool SocketImpl::isConnected() { int bytestoread; int rc; fd_set fdRead; FD_ZERO(&fdRead); FD_SET(_sockfd, &fdRead); struct timeval tv; tv.tv_sec = 0;...
2,742,924
2,742,942
Declaration of pointers in C++
In C++ whats the difference between char const *ptr=&ch; and const char *ptr=&ch;
They are the same, i.e. pointer to const char. However char * const ptr is different, being a const pointer to (non-const) char. And just to complete the set, const char * const ptr is a const pointer to const char.
2,743,016
2,743,038
Correct way to initialize dynamic Array in C++
I'm currently working on a C++ project, where dynamic arrays often appear. I was wondering, what could be the correct way to initialize a dynamic array using the new-operator? A colleague of mine told me that it's a no-no to use new within the constructor, since a constructor is a construct that shouldn't be prone to e...
You should let the std::bad_alloc propagate - there's likely nothing reasonable you could do anyway. First of all, throwing an exception from the constructor is the only reliable way to signal a problem - if there's no exception it means the object is completely constructed. So catching std::bad_alloc alone will not he...
2,743,439
2,743,530
How do I use boost options_description with hexadecimal input?
I want to have two options for the program to work on, the start address and end address so that the program options are as follows: --start_address 0xc0000000 --end_address 0xffffffff Is it possible for options_description to take such hex input? Do I have to consider the input as string and convert them to hex value...
ok. just discovered I can use options_description to enter the options and then parse the options using std::stringstream to convert to a hex number as follows boost::uint32_t start_address; std::stringstream interpreter; interpreter << std::hex << vm["start_address"].as<std::string>(); interpreter >> start_a...
2,743,472
2,743,554
deleting element objects of a std vector using erase : a) memory handling and b) better way?
I have a vec_A that stores instances of class A as: vec_A.push_back(A()); I want to remove some elements in the vector at a later stage and have two questions: a) The element is deleted as: vec_A.erase(iterator) Is there any additional code I need to add to make sure that there is no memory leak? . b) Assume that co...
a) The element is deleted as: vec_A.erase(iterator) Is there any additional code I need to add to make sure that there is no memory leak? . Yes, that's all you need to do. There will be no memory leak. Since you didn't allocate yoour object on heap, when you did vec_A.push_back(A()) a new object is copied into ...
2,743,487
2,743,537
How should a software product handle an access violation
We have a software product in c++, that due to documented problems with the compiler generates faulty code (Yes I know it is horrible in itself). This among other bugs causes Access Violations to be thrown. Our response to that is to catch the error and continue running. My question is, is this a responsible approach?...
I'm with Ignacio: It's imperative to get a fix for that compiler ASAP, or if such a fix is not forthcoming, to jump ship. Naturally there may be barriers to doing so, and I'm guessing you're looking for a short-term solution en route to achieving that goal. :-) If the faulty code problem is not very narrowly constraine...
2,743,572
2,743,577
This is a valid C code but not a valid C++ code?
In some library I'm using (written in C) its StorePGM(image, width, height, filename) char *image; int width, height; char *filename; { // something something } All functions are defined this way. I never seen such function definitions in my life. They seem to be valid to MSVC but when I compile it as C++ it gives e...
Yes. K&R, pre-standard C. Avoid using it.
2,743,687
4,884,418
Sphinx in C++ (Linux)
This time I want to implement Sphinx in Linux. Please give me the API required to do the same or the concerned link will also do. Although I found many for PHP, however none for C++. I have also used GTKmm in my application.
There is no API to do this. Sphinx will process text files in reStructuredText format and turn them into documentation. The ability to extract documentation from source code is only present for python code. For other languages you will need to put the documentation in the reStructuredText files directly. Do not be conf...
2,743,869
2,743,966
Best way to handle storing (possibly NULL) char * in a std::string
class MyClass { public: void setVar(const char *str); private: std::string mStr; int maxLength; //we only store string up to this length }; What's the best approach to implement setVar when the external code is quite likely to pass in NULL for an empty string (and cannot be changed)? I currently do something a...
The code you posted is incorrect, as it will always read maxLength characters from the source string. In particular, this means it will read past the end of the empty string when str is NULL. This will work instead, assuming str is null-terminated: void MyClass::setVar(const char *str) { if (str==NULL) mStr...
2,744,118
10,715,189
How do I remove (or apply) transparency on a gdk-pixbuf?
I have a c++ program in which a gdk-pixbuf is created. I want to output it as an image, so I call gdk_pixbuf_save_to_stream(pixbuf,stream,type,NULL,&err,NULL). This works fine when "type" is png or tiff, but with jpeg or bmp it just produces a black square. The original pixbuf consists of black-on-transparent (and g...
JPEG doesn't have any notion of an alpha channel, or transparency at all. The alpha channel is stripped during the conversion to JPEG. BMP has the same restriction. Since transparency is important to you, your program should stick to generating PNGs. As far as the question you've posed in the title, removing an alpha...
2,744,132
2,744,253
C++ Generic List Assignment
I've clearly been stuck in Java land for too long... Is it possible to do the C++ equivalent of the following Java code: interface Foo {} class Bar implements Foo {} static List<Foo> getFoo() { return new LinkedList<Foo>(); } static List<Bar> getBar() { return new LinkedList<Bar>(); } List<? extends Foo> stuff ...
No in my opinon that does not make sense in C++. First you return a reference that does not exist anymore. To avoid this, you can pass your std::list as a reference parameter to be modified in the function, as void fillFoos( std::list< Foo > & foos ) Second, foos are not bars and can't be copied one to another, excep...
2,744,150
2,744,317
Express any number as the sum of four prime numbers
I was give a problem to express any number as sum of four prime numbers. Conditions: Not allowed to use any kind of database. Maximum execution time : 3 seconds Numbers only till 100,000 If the splitting is NOT possible, then return -1 What I did : using the sieve of Eratosthenes, I calculated all prime numbers ti...
You could still be ok with time. Due to the Goldbach conjecture, Every even Number greater or equal 8 can be expressed as the sum of 2,2, and two further primes. Every odd number greater or equal 9 can be expressed as the sum of 2,3 and two further primes. It shouldn't take too long to figure out the primes. Edit: Actu...
2,744,181
2,744,206
How to call C++ function from C?
I know this. Calling C function from C++: If my application was in C++ and I had to call functions from a library written in C. Then I would have used //main.cpp extern "C" void C_library_function(int x, int y);//prototype C_library_function(2,4);// directly using it. This wouldn't mangle the name C_library_function...
You need to create a C API for exposing the functionality of your C++ code. Basically, you will need to write C++ code that is declared extern "C" and that has a pure C API (not using classes, for example) that wraps the C++ library. Then you use the pure C wrapper library that you've created. Your C API can optionally...
2,744,264
2,744,272
Returning a reference to a local or temporary variable
Look at the code below. I know it doesn't return the address of local variable, but why does it still work and assign the variable i in main() to '6'? How does it only return the value if the variable was removed from stack memory? #include <iostream> int& foo() { int i = 6; std::cout << &i << std::endl; //Pri...
You got lucky. Returning from the function doesn't immediately wipe the stack frame you just exited. BTW, how did you confirm that you got a 6 back? The expression std::cout << &i ... prints the address of i, not its value.
2,744,334
2,744,370
Tic-Tac-Toe AI: How to Make the Tree?
I'm having a huge block trying to understand "trees" while making a Tic-Tac-Toe bot. I understand the concept, but I can't figure out to implement them. Can someone show me an example of how a tree should be generated for such a case? Or a good tutorial on generating trees? I guess the hard part is generating partial ...
Imagine that at any point in a tic-tac-toe board, every single possible move is a branch. The current state of the board is the root. One move is a branch. Now pretend (one at a time), that each branch becomes the current state. Each possible move becomes a new branch. The leaf of the tree is when the last move is...
2,744,442
2,744,464
What's the memory overhead for a single windows threads?
Is it 1 Mb of stack per thread? Or is that just CLR threads? I want to know the memory over head of native windows threads (c++) and CLR threads as view via Task Manager. Thanks
The default is 1 MB for both native and CLR threads. You can alter it, though that's usually a bad idea.
2,744,956
2,745,846
Macro C++ Issues __VA_ARGS__
What (if any) are some potential problems with a C++ macro usage like this? Would an inline function be a more appropriate solution? #define EVENT_INFO(_format_, ...) CMyEvent::Generate(__FILE__, __LINE__, CMyEvent::EVT_HIGH, _format_, __VA_ARGS__) void CMyEvent::Generate( const char* file, //...
As you're using C++, you can avoid the pitfalls of using variable argument lists which are subject to many problems: No check on quantity of arguments No check on argument type To make it more C++, do something like: #define EVENT_INFO(args) EventLogStream (__FILE__, __LINE__, __PRETTY_FUNCTION__) << args and invoke...
2,745,074
2,745,086
Fast ceiling of an integer division in C / C++
Given integer values x and y, C and C++ both return as the quotient q = x/y the floor of the floating point equivalent. I'm interested in a method of returning the ceiling instead. For example, ceil(10/5)=2 and ceil(11/5)=3. The obvious approach involves something like: q = x / y; if (q * y < x) ++q; This requires a...
For positive numbers where you want to find the ceiling (q) of x when divided by y. unsigned int x, y, q; To round up ... q = (x + y - 1) / y; or (avoiding overflow in x+y) q = 1 + ((x - 1) / y); // if x != 0
2,745,105
2,745,130
when to use const char *
If i have a function api that expects a 14 digit input and returns a 6 digit output. I basically define the input as a const char *. would that be the correct and safe thing to do? also why would I not want to just do char * which I could but it seems more prudent to use const char * in that case especially since its ...
When you say const char *c you are telling the compiler that you will not be making any changes to the data that c points to. So this is a good practice if you will not be directly modifying your input data.
2,745,146
2,745,788
C++ boost or STL `y += f(x)` type algorithm
I know I can do this y[i] += f(x[i]) using transform with two input iterators. however it seems somewhat counterintuitive and more complicated than for loop. Is there a more natural way to do so using existing algorithm in boost or Stl. I could not find clean equivalent. here is transform (y = y + a*x): using boost::l...
There are several ways to do this. As you noted you can use transform with a number of predicates, some more or less automatically generated: std::vector<X> x = /**/; std::vector<Y> y = /**/; assert(x.size() == y.size()); // // STL-way // struct Predicate: std::binary_function<X,Y,Y> { Y operator()(X lhs, Y rhs) co...
2,745,167
2,745,203
Data Types and Structs
I'm reviewing for a test, and I am stumped by this question. Consider the following declarations: enum CategoryType {HUMANITIES, SOCIALSCIENCE, NATURALSCIENCE}; const int NUMCOURSES = 100; struct CourseRec { string courseName; int courseNum; CategoryType courseCategory; }; typedef Co...
Let's go step by step: courses[index1] .courseName[index2] courses is array of CourseRec courses[index1] is CourseRec courses[index1] .courseName is string courses[index1] .courseName[index2] is char * * - actually it is char&
2,745,350
2,745,387
C++ destructor issue with std::vector of class objects
I am confused about how to use destructors when I have a std::vector of my class. So if I create a simple class as follows: class Test { private: int *big; public: Test () { big = new int[10000]; } ~Test () { delete [] big; } }; Then in my main function I do the following: Test tObj = Test(); vector<T...
Your problem is here: Test tObj = Test(); The Test() creates a temporary Test object, which then gets copied to tObj. At this point, both tObj and the temporary object have big set to point to the array. Then the temporary object gets destroyed, which calls the destructor and destroys the array. So when tObj gets d...
2,745,360
2,745,385
C++: Short question regarding switch and break
Example: switch( x ) { case y: if ( true ) { break; } cout << "Oops"; break; } If the switch statement selects y, will Oops be written to the standard output? - Is break in switch statements a dynamic keyword like continue which can be called under conditions or static like a closing bracket }?
break breaks out of an enclosing switch, while, for, or do ... while. It doesn't break out of an enclosing if or bare block. Pretty much exactly like continue. It's certainly not part of the required syntax of a switch statement (like a close-brace is part of the syntax of blocks). break is a statement, essentially mea...
2,745,425
2,745,439
C++ pointers simple question
If I have the following lines inside a loop: Type *unite = new Type(newSize); or double *array= new double[anySize]; what is the behavior in what concerns to memory if I don't have delete operators inside it? It will be constantly allocating objects and arrays on different memory locations, and therefore memory leak...
Yes it will. This: for (int i = 0; i < 10; ++i) { Type* unite = new Type(newSize); } will allocate 10 objects of type Type, all at different locations. None of them will be deallocated, and at the end you will not have a pointer to any of them. You will leak 10 * sizeof(Type) bytes of memory. Similarly, this for (i...
2,745,669
2,745,829
Send Ctrl+Up to a window
I'm trying to send messages to a window that says Ctrl and Up-arrow has been pressed. I've got the basics down, I can send presses of the space key that registeres fine. But I can't seem to get the ctrl+ ↑ working. chosen code snippets: [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)] static exte...
I don't have a great way to test it, but would it work if the order of these two lines: SendMessage(handle, (int) WMessages.WM_KEYDOWN, (int) key, 0); SendMessage(handle, (int) WMessages.WM_KEYDOWN, (int)VKeys.VK_CONTROL, 0); was changed to: SendMessage(handle, (int) WMessages.WM_KEYDOWN, (int)VKeys.VK_CONTROL, 0); Se...
2,745,715
2,746,002
2-dimensional matrix
whats the logic to find the sum of alternate elements of a two-dimensional matrix.
//arr is the 2 D array MxN int sum = 0; for(int j=0;j<N;j++) { for(int i=j&1;i<M;i+=2) { sum += a[i][j]; } }
2,745,777
2,747,253
Computational geometry: find where the triangle is after rotation, translation or reflection on a mirror
I have a small contest problem in which is given a set of points, in 2D, that form a triangle. This triangle may be subject to an arbitrary rotation, may be subject to an arbitrary translation (both in the 2D plane) and may be subject to a reflection on a mirror, but its dimensions were kept unchanged. Then, they give ...
The given triangle is defined by three lengths. You want to find three points in the list separated by exactly those lengths. Square the given lengths to avoid bothering with sqrt. Find the square of the distance between every pair of points in the list and only note those that coincide with the given lengths: O(V^2), ...
2,745,872
2,745,902
Function pointers to member functions
There are several duplicates of this but nobody explains why I can use a member variable to store the pointer (in FOO) but when I try it with a local variable (in the commented portion of BAR), it's illegal. Could anybody explain this? #include <iostream> using namespace std; class FOO { public: int (FOO::*fptr)(int ...
When you use a member function pointer, you need to specify the object on which it is acting. I.e. you need to create a pointer to an instance of BAR (let's call it bar) and do: (bar->*fptr)(a,b) to call the function, or an instance of BAR and do: (bar.*fptr)(a,b) Put another way: #include <iostream> class BAR { ...
2,745,932
2,746,043
Street light and shadow in opengl?
To make a scene street illuminated, I tried point source light, used glMaterial and used ambient light. I get a scene fully illuminated, not exactly the way like street light, can anyone share resources or explain how exactly I can achieve this? I went through many light resources in net, could not properly understand....
You probably want to use what OpenGL considers a spot light -- this lets you "aim" the light, and specify how much the light falls off as you move away from where it's pointed. Note that if you want the light itself to show up in the scene, you have to draw it in yourself -- when you specify the light position, OpenGL ...
2,746,072
2,746,092
What's wrong with my recursive function?
So I'm trying to implement a recursive function that generates the entire game tree of Tic-Tac-Toe, and I can't seem to get it to work. void BuildTree(Node& nNode, const int& nextPlayer) { //Copy last board Ticboard tBoard = nNode.m_board; do { //Return first valid move ...
nNode.m_branches.push_back(f); This will push_back a copy of the Node f, so the stuff inside nNode.m_branches will be irrelevant to the modification of f later on.
2,746,147
2,746,190
Would this constructor be acceptable practice?
Let's assume I have a c++ class that have properly implemented a copy constructor and an overloaded = operator. By properly implemented I mean they are working and perform a deep copy: Class1::Class1(const Class1 &class1) { // Perform copy } Class1& Class1::operator=(const Class1 *class1) { // perform copy retur...
I would say, "no", for the following reasons: A traditional copy constructor accepts its argument as a const reference, not as a pointer. Even if you were to accept a pointer as a parameter, it really ought to be const Class1* to signify that the argument will not be modified. This copy constructor is inefficient (or ...
2,746,168
5,253,726
How to construct a c++ fstream from a POSIX file descriptor?
I'm basically looking for a C++ version of fdopen(). I did a bit of research on this and it is one of those things that seems like it should be easy, but turns out to be very complicated. Am I missing something in this belief (i.e. it really is easy)? If not, is there a good library out there somewhere to handle thi...
From the answer given by Éric Malenfant: AFAIK, there is no way to do this in standard C++. Depending on your platform, your implementation of the standard library may offer (as a nonstandard extension) a fstream constructor taking a file descriptor as input. (This is the case for libstdc++, IIRC) or a F...
2,746,215
2,746,250
C++ reference type as instance variable in Objective-C++
C++ reference types as instance variables are forbidden in Objective-C++. How can I work around this?
You can't sensibly use references as instance variable because there is no way to initialize instance variables and references can't be reseated. An alternative might be to simply use (possibly smart) pointers instead. Another possibility that gets you closer to C++-like behaviour is to use a PIMPL-style member for you...
2,746,264
2,746,293
Why the streams in C++?
As you all know there are libraries using streams such as iostream and fstream. My question is: Why streams? Why didn't they stick with functions similar to print, fgets and so on (for example)? They require their own operators << and >> but all they do could be implemented in simple functions like above, also the fu...
Streams have better type safety. For instance printf("%s", a); can go horribly wrong if a is an integer. cout << a; doesn't have this problem. Another issue is that streams better conform to Object Oriented design methodologies. For instance you have a simple application that writes some output and then you want the ...
2,746,326
2,746,345
Which of FILE* or ifstream has better memory usage?
I need to read fixed number of bytes from files, whose sizes are around 50MB. To be more precise, read a frame from YUV 4:2:0 CIF/QCIF files (~25KB to ~100KB per frame). Not very huge number but I don't want whole file to be in the memory. I'm using C++, in such a case, which of FILE* or ifstream has better (less/minim...
Impossible to say - it will depend on the implementation, and how you are reading the data, which you have not described. In general, questions here regarding performance are somewhat pointless, as they depend heavily on your actual usage of library and language features, the specific implementation, your hardware etc....
2,746,457
2,746,533
Show a download list with qt4
What is the best way to show a list of downloads using QT4? 1 QListWidget 2 QTreeWidget 3 QTableWidget Thanks
It depends on how much functionality you want. If you just want to simply list the filenames, use a QListWidget. If you want to list other things like progress, filesize, etc. then you may want to use a QTableWidget. If you want to be able to group downloads under different categories, you can use the QTreeWidget, w...
2,746,593
2,746,734
Video courses for learning C++
Do you have any recommendations on great video courses as a complement to books for learning C++?
Have not used these and I'm not sure about international shipping, but these are partly taught by Yashavant Kanetkar. Quest C++ Programming Don't let the 550 price throw you, it's in Rupees so about $13 US. -- Update for shipping: For shipments to USA/Canada, UK, Europe, Japan, Australia, we charge INR 2000 (USD...
2,746,624
2,746,977
how to handle delete by illegal address
Suppose we have a situation like this. Suppose instead of "p = &global;" we called some function(written by someone which invalidate our pointer). How to handle this problem? How to protect code from crashes? I know about and use boost smart pointers. But what to do if we have this situation. struct Test { int a; ...
You can use the code below to find out if a pointer points to a stack area or heap area: bool IsMemoryOnStack( void* p ) { void* dwStackTop = 0; void* dwStackLowCurrent = 0; __asm { mov EAX, FS:[4] mov dwStackTop, eax mov EAX, FS:[8] mov dwStackLowCurrent, eax } ...
2,746,627
2,746,676
A question about TBB/C++ code
I am reading The thread building block book. I do not understand this piece of code: FibTask& a=*new(allocate_child()) FibTask(n-1,&x); FibTask& b=*new(allocate_child()) FibTask(n-2,&y); What do these directive mean? class object reference and new work together? Thanks for explanation. The following code i...
new(pointer) Type(arguments); This syntax is called placement new, which assumes the location pointer is already allocated, then the constructor of Type is simply called on that location, and return a Type* value. Then this Type* is dereferenced to give a Type&. Placement new is used when you want to use a custom allo...
2,746,677
2,746,685
What happens when you deallocate a pointer twice or more in C++?
int main() { Employee *e = new Employee(); delete e; delete e; ... delete e; return 0; }
You get undefined behaviour if you try to delete an object through a pointer more than once. This means that pretty much anything can happen from 'appearing to work' to 'crashing' or something completely random.
2,746,855
2,747,598
How can I create an Image in GDI+ from a Base64-Encoded string in C++?
I have an application, currently written in C#, which can take a Base64-encoded string and turn it into an Image (a TIFF image in this case), and vice versa. In C# this is actually pretty simple. private byte[] ImageToByteArray(Image img) { MemoryStream ms = new MemoryStream(); img.Save(ms, Syst...
This should be a two-step process. Firstly, decode the base64 into pure binary (the bits you would have had if you loaded the TIFF from file). The first Google result for this looks to be pretty good. Secondly, you'll need to convert those bits to a Bitmap object. I followed this example when I had to load images from ...
2,747,004
2,747,046
GCC: Simple inheritance test fails
I'm building an open source 2D game engine called YoghurtGum. Right now I'm working on the Android port, using the NDK provided by Google. I was going mad because of the errors I was getting in my application, so I made a simple test program: class Base { public: Base() { } virtual ~Base() { } }; // class ...
Use g++ to drive the linker, not gcc: /home/oem/android-ndk-r3/build/prebuilt/linux-x86/arm-eabi-4.4.0/bin/arm-eabi-g++ -Wl, --entry=main, ... Update: another problem appears to be your use use of -nostdlib. This is stopping the compiler from adding all the standard libraries (such as the runtime library that provide...
2,747,316
2,747,345
c++ File input/output
I am trying to read from a file using fgets and sscanf. In my file, I have characters on each line of the while which I wish to put into a vector. So far, I have the following: FILE *fp; fp = fopen(filename, "r"); if(!fp) { fprintf(stderr, "Unable to open file %s\n", filename); return 0; } // Read fil...
tmp is a pointer and not an array so reading into it results in a buffer overrun. for a start you should change the decleration of tmp to: char *tmp = malloc(SOME_MAXIMUM_SIZE * sizeof(char)); and then you should remember to free all of the pointers in axioms when you're done.
2,747,322
2,747,353
sending address of a variable declared on the stack?
I have a doubt concerning declaring variables, their scope, and if their address could be sent to other functions even if they are declared on the stack? class A{ AA a; void f1(){ B b; aa.f2(&b); } }; class AA{ B* mb; f2(B* b){ mb = b; //... } }; Afterwards, I u...
It contains the address of the local variable which could not be available anymore, so the pointer isn't valid anymore? Yes. It becomes a dangling pointer. You could try vector::swap, as in: class AA { B mb; // not a pointer f2(B* b){ mb.swap(*b); // swap the content with b, which is just a few pointer assign...
2,747,430
2,747,482
Syntax for specializing function templates
Is there a difference between the following approaches? // approach 1 namespace std { template<> void swap<Foo>(Foo& x, Foo& y) // note the <Foo> { x.swap(y); } } // approach 2 namespace std { template<> void swap(Foo& x, Foo& y) { x.swap(y); } } I stumpled upon this ...
Yes, there is. But not in that particular example. If the parameter is not deduced, it can make a difference template<typename T> void f(typename T::type t); You cannot specialize that without <type> because it cannot deduce what T is from the parameter list. struct MyType { typedef int type; }; // needs <MyType> te...
2,747,785
2,747,834
Recommendations for C++ open source game engines on IPhone
I decided that I want to make a game for the iphone I was thinking of using oolong or sio2 any recommendations? Both have the problem of lack of tutorials, is it possible to somehow use a normal C++ game tutorial and integreate the engines rather than the one used in the tutorials? So if the C++ tutorial talks of crea...
You're making a game, not a game engine. The short answer is, yes, you can just use those engines to make the game. The long answer is that you should probably go through the tutorials doing it the way that they do it just to get a feeling for C++/OpenGL/whatever. Then, using the knowledge that you have gained, make ...
2,747,891
2,755,216
Boost ASIO async_write "Vector iterator not dereferencable"
I've been working on an async boost server program, and so far I've got it to connect. However I'm now getting a "Vector iterator not dereferencable" error. I suspect the vector gets destroyed or dereferenced before he packet gets sent thus causing the error. void start() { Packet packet; packet.setOpcode(SMSG_...
I have found a solution, as the vector would get destroyed I made a queue that contains the resulting packets and they get processed one by one, now nothing gets dereferenced so the problem is solved. might want to change my queue to hold the packet class instead of the result but that's just a detail.
2,747,955
2,748,032
Confusion on C++ Python extensions. Things like getting C++ values for python values
I'm wanted to convert some of my python code to C++ for speed but it's not as easy as simply making a C++ function and making a few function calls. I have no idea how to get a C++ integer from a python integer object. I have an integer which is an attribute of an object that I want to use. I also have integers which ar...
The way to get a C int from a Python integer is with PyInt_AsLong() and a downcast (although you may want to use a C long instead.) To go the other way, you call PyInt_FromLong(). It's not obvious to me where in the code you want to do this, although I do have a couple of other comments about your code: Conceptually, ...
2,748,091
2,748,125
What's the performance penalty of weak_ptr?
I'm currently designing a object structure for a game, and the most natural organization in my case became a tree. Being a great fan of smart pointers I use shared_ptr's exclusively. However, in this case, the children in the tree will need access to it's parent (example -- beings on map need to be able to access map d...
From the Boost 1.42 source code (<boost/shared_ptr/weak_ptr.hpp> line 155): shared_ptr<T> lock() const // never throws { return shared_ptr<element_type>( *this, boost::detail::sp_nothrow_tag() ); } ergo, James McNellis's comment is correct; it's the cost of copy-constructing a shared_ptr.
2,748,138
2,748,167
error LNK2019 and fatal error LNK1120 i get these errors in c++
i have no idea how to get these errors out. i wrote the whole code over and tried to see if it was a problem with brackets but that doesnt help either. i dont know what line it is but i believe it is in this function. error LNK2019: unresolved external symbol "int __cdecl read_file_in_array(int (* const)[3])" (?read_f...
Your function prototype declares: int read_file_in_array(int exam[100][3]); But the function itself is defined as: int read_file_in_array(double exam[100][3]) Make sure you use the same types in both.
2,748,212
2,748,236
Can Visual Studio manage function prototypes for me in C++ header files?
In C++, the common practice is to declare functions in header files and define them in cpp files. This leads to always having two copies of every function's prototype. Then whenever I want to change a function's name/return value/parameter, I have to manually change it in both files. This seems unnecessarily tedious an...
You can use the Visual Assist X add-in for Visual Studio. One of its feature is to do what you want: Modify the signature of a function in the base class and let it modify all signature of the same function in the cpp file and in derived classes. This add-in is not free but you can try the trial.
2,748,295
2,748,319
How can I copy one map into another using std::copy?
I would like to copy the content of one std::map into another. Can I use std::copy for that? Obviously, the following code won't work: int main() { typedef std::map<int,double> Map; Map m1; m1[3] = 0.3; m1[5] = 0.5; Map m2; m2[1] = 0.1; std::copy(m1.begin(), m1.end(), m2.begin()); return 0; } This won'...
You can use GMan's answer --- but the question is, why do you want to use std::copy? You should use the member function std::map<k, v>::insert instead. m2.insert(m1.begin(), m1.end());
2,748,323
2,750,056
Which way to go in Linux 3D programming?
I'm looking for some answers for a project I'm thinking of. I've searched and from what I understand (correct me if I'm wrong) the only way the program I want to make will work is through 3D application. Let me explain. I plan to make a studio production program but it's unique in the fact that I want to be able to mak...
I don't know much about the MS Surface, but I'm a musician and multimedia artist working mostly with code, so... My advice is very much different - it doesn't matter if it's Irrlight, Orge, pure OpenGL or anything else. If you don't know much about 3D prgramming you'd better start with something different. There are se...
2,748,379
2,748,385
Does reserving capacity incur two allocations or just one?
std::vector<T> vec; // line #1 vec.reserve(100); // line #2 I am wondering if line #1 triggers a small allocation (say, memory for 10 Ts), or if the first allocation happens on line #2. Does the standard say anything about that?
It's implementation defined. The default-constructor for vector does not need to allocate anything, but it's permissible for an implementation to do so.
2,748,466
2,748,475
static array in c++ forgets its size
In this small example, c++ forgets size of an array, passed to a constructor. I guess it is something simple, but I cannot see it. In classes.h, there is this code: #ifndef CLASSES_INC #define CLASSES_INC #include <iostream> class static_class { public: static_class(int array[]) { std::cout<<sizeof(array)/sizeof(i...
When declaring a function parameter, the following two are equivalent because an array decays to a pointer when it is passed as an argument: int array[] int *array; So, you end up computing sizeof(int*) / sizeof(int), which happens to be one on your platform because their sizes are the same. If you need the size of th...
2,748,550
2,748,592
How to iterate over modifed std::map values?
I have an std::map, and I would like to define an iterator that returns modified values. Typically, a std::map<int,double>::iterator iterates over std::pair<int,double>, and I would like the same behavior, just the double value is multiplied by a constant. I tried it with boost::transform_iterator, but it doesn't compi...
std::multiply which expect a double as first argument, and not a std::pair. The transform function must take a single std::pair argument (as the map elements are pair of key values) and return whatever you want. The following function could be used instead of std::multiply. double times(std::pair<int,double> const& p, ...
2,748,551
2,749,523
QTextBrowser line spacing after a wordwrap
How do I set line spacing after a wordwrap in QTextBrowser? Ie. how dow I set line height?
You should be able to achive this by setting an appropriate stylesheet. Edit: I was mistaken with the initial reply -- setStyleSheet() works on the widget, not its contents. However, you can achieve the behaviour by formatting your text as HTML with stylesheet formatting, and then setting that as the text in your QText...
2,748,587
2,748,625
Floodfill with "layers"
What I want is to create a vector drawing program with layers, but to avoid using transparency / opacity, I want to draw each shape from lowest layer to highest layer onto a single bitmap. For the filling, I want to floodfill the shape. My issue is that, if I have a shape that is drawn then floodfilled, then the next s...
Floodfill will not work for what you want... Unless, you make one of the following: Option 1: Use the floodfill in other part of the memory, and then blit the shape using a mask to the place where you want, since you said you wanted to avoid transparency, this option is sort of crossed out... (altough I still recommend...
2,748,641
2,748,652
MingW C++ Documentation?
I remember some years ago, when I learned C using Turbo C, it had a extensive documentation on its headers... My question is: There are something like that for MingW?
MinGW is just a windows port of GCC, so the official GCC documentation should work (mostly) just fine.
2,748,660
2,748,681
optimize 2D array in C++
I'm dealing with a 2D array with the following characteristics: const int cols = 500; const int rows = 100; int arr[rows][cols]; I access array arr in the following manner to do some work: for(int k = 0; k < T; ++k) { // for each trainee myscore[k] = 0; for(int i = 0; i < cols; ++i) { // for each sample fo...
A general in-place matrix transposition is very difficult, but if you're okay with transposing it to another array, then it's pretty simple. const int cols = 500; const int rows = 100; int arr[rows][cols]; // fill arr[][] int arrT[cols][rows]; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { ...
2,748,818
2,749,261
C/C++ __restrict type
Is there a way to define using typedef integral/float type which implies no aliasng? something equivalent to (but primitive construct): template < typename T > struct restrict { T* __restrict data; }; as related question, is it possible to ask gcc what it determines alias/no alias of pointer is?
As noted in the comments, many newer C++ compilers do support the C99 implementation of the restrict type qualifier. Since restrict is not a reserved keyword in C++, the compilers generally use __restrict or __restrict__. Both GCC and Visual C++ document this nicely, with explicit references to C99. The C++ 1998 stan...
2,748,866
2,749,602
C++0x rvalue references and temporaries
(I asked a variation of this question on comp.std.c++ but didn't get an answer.) Why does the call to f(arg) in this code call the const ref overload of f? void f(const std::string &); //less efficient void f(std::string &&); //more efficient void g(const char * arg) { f(arg); } My intuition says that the f(stri...
GCC is doing it wrong according the FCD. The FCD says at 8.5.3 about reference binding If the reference is an lvalue reference and the initializer expression is an [lvalue / class type] ... Otherwise, the reference shall be an lvalue reference to a non-volatile const type (i.e., cv1 shall be const), or the reference s...
2,748,950
2,748,954
Vector insert() causes program to crash
This is the first part of a function I have that's causing my program to crash: vector<Student> sortGPA(vector<Student> student) { vector<Student> sorted; Student test = student[0]; cout << "here\n"; sorted.insert(student.begin(), student[0]); cout << "it failed.\n"; ... It crashes right a...
It should be: sorted.insert(sorted.begin(), student[0]); You were passing the iterator from the wrong instance.
2,748,962
2,748,971
Advantage of using a static member function instead of an equivalent non-static member function?
I was wondering whether there's any advantages to using a static member function when there is a non-static equivalent. Will it result in faster execution (because of not having to care about all of the member variables), or maybe less use of memory (because of not being included in all instances)? Basically, the func...
There is absolutely no performance difference between static member functions and free functions. From a design perspective, it sounds like the function in question has very little to do with Bullets, so I would favour putting it in a utility library somewhere, there is no runtime overhead in doing this, only extra dev...
2,748,969
2,749,029
"Inherited" types using CRTP and typedef
The following code does not compile. I get an error message: error C2039: 'Asub' : is not a member of 'C' Can someone help me to understand this? Tried VS2008 & 2010 compiler. template <class T> class B { typedef int Asub; public: void DoSomething(typename T::Asub it) { } }; class C : public B<C> { public: t...
You are being a bit unfair to the compiler here - C is incomplete without B<C> fully known and when processing B<C>, C is still an incomplete type. There are similar threads on comp.lang.c++.moderated and comp.lang.c++. Note that it works if you delay the use by moving it into a member function definition, e.g.: struct...
2,749,042
2,749,051
C++ 2d Array Class Function Call Help
I hope this question takes a simple fix, and I am just missing something very small. I am in my second semester of C++ in college, and we are just getting into OOP. This is my first OOP program, and it is causing me a little problem. Here are the errors I am getting: Member function must be called or its address taken ...
The following line: cout << setw(3) << grid[i][c].getSymbol; Doesn't call the function. Write this instead: cout << setw(3) << grid[i][c].getSymbol(); Likewise for the other error messages. The warning is generated because the erroneous line is the only time displayGrid uses the grid parameter.
2,749,048
2,749,162
Is this call to a function object inlined?
In the following code, Foo::add calls a function via a function object: struct Plus { inline int operator()(int x, int y) const { return x + y; } }; template<class Fct> struct Foo { Fct fct; Foo(Fct f) : fct(f) {} inline int add(int x, int y) { return fct(x,y); // same efficiency adding directly? }...
For g++ 4.4.1, it will inline at -O1 or above. I used the program (as well as your code): int main() { Foo<Plus> foo((Plus())); int a, b; cin >> a >> b; int x = foo.add(a, b); cout << x << endl; } For -O0, you get (g++ -S, excerpted): main: .LFB960: ; ... call _ZN3FooI4PlusEC1ES0_ ...
2,749,209
2,749,695
C++ Forward declaration for virtual function
I have a class hierarchy and i am writing a virtual function in it. Say there are three classes class A { virtual A* test(); }; ( File A.h ) class B : public A { virtual C* test(); }; ( File B.h ) class C : public A {}; ( File C.h ) Now is it possible for me to avoid including C.h in B.h, by doing some kind of fo...
You can tell the compiler only three things, in three different ways, about a class C: That it exists. You do that by forward-declaring the class. How it is structured. You do that by declaring the class. How it behaves. You do that by defining the class' member-functions. If you want to tell the compiler what the cl...
2,749,328
2,749,368
Is there any boost-independent version of boost/tr1 shared_ptr
I'm looking for independent implementation of boost/tr1 shared_ptr, weak_ptr and enable_shared_from_this. I need: Boost independent very small implementation of these features. I need support of only modern compilers like GCC-4.x, MSVC-2008, Intel not things like MSVC6 or gcc-3.3 I need it to be licensed under non-co...
I extracted shared_ptr from Boost to use it separately, and it was definitely fewer than 300 files. That was 3 years ago however so things may have changed (maybe there are more files in the config folder these days?). What I needed for the shared_ptr was: assert.hpp checked_delete.hpp throw_exception.hpp config.hpp a...
2,749,382
2,749,438
C++ errors not shown in Visual Studio C# project
I have in Visual Studio 2008 a .NET 3.5 C# project that uses a dll compiled from a C# project (let's call it dll A). Dll A is using on his turn some C++ libraries. The problem is that when I encounter an error while calling objects from dll A, the application just closes, without showing any error. But I need to know w...
Did you activate unmanaged debugging in the property page of your C# project? Without that, debug output from the C++ DLL wont make it to visual studio's output window.
2,749,443
2,764,544
Using richtext in QTextEdit
What is exactly richtext and how do I format data in richtext in QTextEdit?
The internal rich text format is tag/attribute-based, and is similar to HTML using in-line CSS style="xxx" attributes. The default export/import format (using toHTML/setHTML) is a subset of HTML. See this link: http://doc.trolltech.com/4.6/richtext-html-subset.html Note that CSS classes are not supported internally and...
2,749,450
2,754,032
Why function does not know the array size?
If I write int main() { int a[100] = {1,2,3,4,}; cout<<sizeof(a)/sizeof(a[0])<<endl; //a is a pointer to the first elem of array, //isn't it return 0; } I get 400! If I write void func(int *a); int main() { int a[100] = {1,2,3,4,}; func(a); return 0; } ...
This isn't working because sizeof is calculated at compile-time. The function has no information about the size of its parameter (it only knows that it points to a memory address). Consider using an STL vector instead, or passing in array sizes as parameters to functions. This was answered by Marcel Guzman in Calculati...
2,749,471
2,749,499
Default string arguments
myPreciousFunction(std::string s1 = "", std::string s2 = "") { } int main() { myPreciousFunction(); } Can i make the arguments look more pretty? I want there to be empty strings if no arguments were supplied.
you may consider this: myPreciousFunction(std::string s1 = std::string(), std::string s2 = std::string()) { } But it doesn't really look prettier. Also, if you're passing strings, you might want to pass them as const&: myPreciousFunction(const std::string& s1, const std::string& s2) { } This is a standard way to avoi...
2,749,733
2,749,758
How to add libraries in C++?
Yea this is a dumb question... However in both of my C++ classes we did not do this at all (except for native libraries: iostream, iomanip, etc.)... My question is can anyone provide a link that gives the general explanation of adding libraries to C++? I do realize what what #include means; it's just I have no clue on...
This would probably interest you, but here is a short version: When you assemble the .cpp, .c or whatever files, each translation unit (that is, each file) generates an object file. When creating the final executable, you combine all the object files into a single binary. For static libraries, you compile the static ...
2,749,855
2,749,915
Why is it so hard to find a C++ 3d game tutorial
I'm planning on learning 3d game development for the iphone using a 3d engine, but because of lack of tutorials for the iphone I was planning on using C++ game tutorials and making the necessary changes. The problem is that I've had limited success when searching for things such as 'c++ 3d fps tutorial ' I dont really ...
There are no tutorials on writing a MS Word killer either. That's because tutorials are for explaining specifics. There are tutorials for "how to implement bump-mapping in your game", but not for "how to make a complete AAA game from scratch". If you feel you need a tutorial for that kind of thing, you're not ready to ...
2,749,889
2,749,965
Looking forward to a programming future but confused where to start
I am very new to this site and to programming. I started doing some basic programming with python a few weeks ago and recently, messing around with Java basics. My main problem is that I am completely overwhelmed and haven't got the slightest clue where I should be starting. I want to learn programming because I really...
Game programming is a lot about design and gameplay; the language is merely a tool. Of course, C++ is widely used, but even a C++ guru wouldn't be able to make a decent game if he didn't play games or understand how the actual mechanics work. You can learn C++ any day, learning how to create a game that is actually fun...
2,749,990
2,750,021
C++ function dynamic data type definition
in C++, when you define a function which takes one argument, you have to define the data type of that variable: void makeProccess(int request) However, I want to implement a function which takes different data types rather taking statically defined integer type. void makeProccess(anyType request) How can I design a p...
Use templates: template <typename T> void makeProcess(T request) { // request is of type "T", which can vary cout << "request: " << request; } An additional benefit, is you can specialize it: template <> void makeProcess(string request) { cout << "This is special handling for a string request: " << request; }
2,750,131
2,750,158
Deploying locally compiled binaries on server
I have Ubuntu 8.04 running on a Xen based VPS server that runs on a dual-core AMD Opteron 64-bit machine. I have some locally developed C++ based daemons that I would want to deploy in that machine. My local machine is a 32 bit Ubuntu 9.04 running on an Intel core 2 duo laptop. Can I execute binaries compiled from s...
Xen is a hypervisor on top of which OSes are expected to run. It isn't an OS itself, in the normal sense of the word, and you can't build stuff to run on it. Unless the "stuff" is an OS, of course. EDIT: Since Ubuntu is running inside the hypervisor, Xen itself is somewhat irrelevant. Pretty much anything you can do in...
2,750,137
2,750,146
Can I use Boost's format library to replace iostream?
I don't like to use <iostream> in C++ Library. I prefer to use something that is similar to "printf" and "scanf" in <stdio.h>. Can I use Boost's format library to replace <iostream> in all my C++ program ?
Boost Format only does the formatting bit. You still need iostream to actually make something appear on the screen. Of course, using them together will achieve the parity with printf you are looking for. And it does so without sacrificing type-safety (though that's not a huge issue these days, since the compiler will u...
2,750,138
2,750,202
What libraries use design patterns implemented with compile-time metaprogramming techniques?
Does anybody know of any libraries that use design patterns that are implemented using compile-time techniques e.g. template metaprogramming? I know that Loki implements a few but I need to find other libraries.
I think that you are asking for libraries that help to use design pattern more that libraries using design patterns, isn't it? There are some in Boost but not too much, like Flyweight - Design pattern to manage large quantities of highly redundant objects. The not yet released but accepted library Boost.Factory and th...
2,750,173
2,750,210
C++ LNK2019 error with constructors and destructors in derived classes
I have two classes, one inherited from the other. When I compile, I get the following errors: Entity.obj : error LNK2019: unresolved external symbol "public: __thiscall Utility::Parsables::Base::Base(void)" (??0Base@Parsables@Utility@@QAE@XZ) referenced in function "public: __thiscall Utility::Parsables::Entity::Entit...
The relevant bit is this: unresolved external symbol "public: __thiscall Utility::Parsables::Base::Base(void)" You need to provide a definition for Base::Base and Base::~Base. A declaration is not good enough. Even if you have nothing to do in either function, you need to leave an empty function body, because C++ actu...
2,750,270
2,750,291
C/C++ Struct vs Class
After finishing my C++ class it seemed to me the structs/classes are virtually identical except with a few minor differences. I've never programmed in C before; but I do know that it has structs. In C is it possible to inherit other structs and set a modifier of public/private? If you can do this in regular C why in th...
In C++, structs and classes are pretty much the same; the only difference is that where access modifiers (for member variables, methods, and base classes) in classes default to private, access modifiers in structs default to public. However, in C, a struct is just an aggregate collection of (public) data, and has no ot...
2,750,316
2,750,322
*this vs this in C++
I understand what this does, but what is the difference between *this and this? Yes, I have Googled and read over *this in my text book, but I just don't get it...
this is a pointer, and *this is a dereferenced pointer. If you had a function that returned this, it would be a pointer to the current object, while a function that returned *this would be a "clone" of the current object, allocated on the stack -- unless you have specified the return type of the method to return a refe...
2,750,636
2,750,712
Portable way to determine the platform's line separator
Different platforms use different line separator schemes (LF, CR-LF, CR, NEL, Unicode LINE SEPARATOR, etc.). C++ (and C) runtime libraries make a lot of this transparent to most programs, by converting '\n' to and from the target platform's native new line encoding. But if your program needs to determine the actual b...
I'm no C/C++ expert, but there doesn't appear to be anything in the standard library that will directly give you the line separator. The translation is handled transparently by the text-mode file functions. Even though you feel your approach is "kludgy", it is probably the simplest and most reliable, since you are rea...
2,750,644
2,750,658
Forcing a templated object to construct from a pointer
I have a fictional class: template<typename T> class demonstration { public: demonstration(){} ... T *m_data; } At some point in the program's execution, I want to set m_data to a big block of allocated memory and construct an object T there. At the moment, I've been using this code: void construct()...
Use placement new: new (m_data) T(); Placement new is really just an overload of the operator new function that accepts an additional parameter – the memory location where the object should be constructed at. This precisely matches your use-case. In particular, this is how allocators usually implement the construct me...
2,750,680
2,750,691
C++ function will not return
I have a function that I am calling that runs all the way up to where it should return but doesn't return. If I cout something for debugging at the very end of the function, it gets displayed but the function does not return. fetchData is the function I am referring to. It gets called by outputFile. cout displays "done...
Either there's some other line of code in your program that prints "done here", or you're corrupting the stack and affected the return address. But I don't see any buffers on the stack that you could overrun. Have you tried using a debugger?
2,750,778
2,839,015
Optimizing GDI+ drawing?
I'm using C++ and GDI+ I'm going to be making a vector drawing application and want to use GDI+ for the drawing. I'v created a simple test to get familiar with it: case WM_PAINT: GetCursorPos(&mouse); GetClientRect(hWnd,&rct); hdc = BeginPaint(hWnd, &ps); MemDC = CreateCompatibleDC(hdc)...
Instead of creating all the resources and tearing them all down for every WM_PAINT, you could try off-loading this to application setup and cleanup. In other words, shift all the stuff like CreateCompatibleDC, CreateCompatibleBitmap to WM_CREATE, and the corresponding deletes to WM_DESTROY. You can keep references to a...
2,750,832
2,750,950
C++ parent class alignment
Is it possible to specify alignment of parent class? for example something like (which does not compiled): template<size_t n> class Vector : public boost::array<double,n> __attribute__ ((aligned(16))) { thanks well, from comments I gather this is no good way to go. I think I will just stick to composition/alignment of...
We don't need to request alignment on the derived class neither we can. The reason why we don't need is that it is enough to request alignment for the derived class, and that requesting alignment to the derived class will result on layout for the base class that depends on the derived. class A : public C __attribute__...
2,750,957
2,750,975
Can g_time_out add be given a member function of a class?
The question is simply in the title, if I have a function I want to use via a g_timeout_add(), but this function is a class member function, is there any way I can use it with g_timeout_add()?
You need to use a trampoline function, e.g.: extern "C" gboolean trampoline(gpointer data) { static_cast<MyClass*>(data)->mem_fun(); } // ... MyClass c = /* ... */; g_timeout_add(/*...*/, static_cast<gpointer>(&c)); See this question on why you should use free functions if you want to write portable code.
2,750,970
2,750,984
Different types for declaring pointer variables
Consider the below 2 declarations. * appears next to the datatype and not next to variable char* ptr1, * ptr2, * ptr3; //all 3 are pointers * appears next to the variable and not next to datatype char *ptr1,*ptr2,*ptr3; //again all 3 are pointers Is there any difference in intepretation between the 2 declarations. I ...
The only difference is whitespace, they end up being pointers-to-chars. I personally use char * ptr1, using plenty of whitespace in my code. Void pointers can point to any type of object and have no size. For example, this works (but isn't really a good idea): int * ptr1; float * ptr2; (*ptr1) = 17; ptr2 = (void*)ptr1;...
2,750,974
2,750,978
What does this "label" mean in C++?
I was reading some c++ code, and i saw something interesting. The code was something like this: repeat: ...code here.... fallback: ...code here.... start: ....another code.... This is the first time i am seeing this kind of "labels" in c++ code, i called the labels cos i have seen something similar in...
It is a label, to which you can jump using a goto. Whether one should use gotos in a program is another matter entirely.
2,750,988
2,753,039
C++ Reading and Editing pixels of a bitmap image
I'm trying to create a program which reads an image in (starting with bitmaps because they're the easiest), searches through the image for a particular parameter (i.e. one pixel of (255, 0, 0) followed by one of (0, 0, 255)) and changes the pixels in some way (only within the program, not saving to the original file.) ...
But if by "bitmap" you really meant a bitmap (that is, a raw image file with nothing but uncompressed pixel data), it's rather easy: char *filename = "filename"; FILE *input = fopen(filename, "rb+"); if (!input) { printf("Could not open input file '%s'\n", filename); system("PAUSE"); return 1; } fseek(inpu...
2,751,037
2,751,041
Pointers and Addresses
Consider the below example int nCount[2] = {5,10}; int* ptrInt; ptrInt = nCount; cout<<ptrInt<<Endl;//this will print the address of arrar nCount now consider this char *str = "Idle mind is a devil's workshop"; int nLen = strlen(str); char* ptr; ptr = new char[nLen+1]; strcpy(ptr,str); cout<<ptr<<endl;//this wil pr...
Since char*s are frequently used for storing strings, the ostream operator<< is overloaded for char* to print out the pointed-to string instead of the pointer. If you want to output the pointer, you can cast the pointer to void* and then output that.
2,751,069
2,751,087
Using OpenGL in a regular window (Win32)
I want to use OpenGL in my WndProc but I'm not sure how. I also don't want GL to occupy the whole screen, just a portion of the screen. In the end I basically want to make a drawing win32 app but use OGL instead of GDI. so how can I tell GL to use my control (a panel) 's hdc for drawing?
When you call wglCreateContext, pass the control's HDC instead of the window. The same thing works on OpenGL and DirectX.
2,751,096
2,806,290
Terminate threads Gracefully in ACE
I have a question similar to This one . But I want to implement this in Linux, using ACE framework. What is the way to do this
A little more information would help obtain a better answer: Are your worker threads waiting on other events prior to running? How do your threads communicate with one another? Will you always have the ability to terminate gracefully, or are you anticipating having to force terminate some threads? The other questio...
2,751,115
2,751,136
unroll nested for loops in C++
How would I unroll the following nested loops? for(k = begin; k != end; ++k) { for(j = 0; j < Emax; ++j) { for(i = 0; i < N; ++i) { if (j >= E[i]) continue; array[k] += foo(i, tr[k][i], ex[j][i]); } } } I tried the following, but my output isn't the same, and it should be: for(k = begin; k != end; ++k) {...
if (j >= E[i]) continue; array[k] += foo(i, tr[k][i], ex[j][i]); array[k] += foo(i+1, tr[k][i+1], ex[j][i+1]); array[k] += foo(i+2, tr[k][i+2], ex[j][i+2]); array[k] += foo(i+3, tr[k][i+3], ex[j][i+3]); versus if (j >= E[i]) continue; array[k] += foo(i, tr[k][i], ex[j][i]); Screening conditions are n...
2,751,156
2,751,217
Drawing NGons with OpenGL
Is OpenGL, given a series of points, able to fill in a polygon or is this only possible by creating lots of trianges? Thanks
Setting glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) should give you a filled polygon, as long as the vertices satisfy appropriate conditions (all the points have to be coplanar, and define a convex polygon, iirc). You'd draw the polygon with the standard glBegin(GL_POLYGON), glVertex*(coords) and then glEnd() calls.
2,751,176
2,752,503
Debug CGI by simulation
I basically want to debug a cgi programm with gdb by emulating the environment variables and stdin stream. How do I set the variables and stdin? I am using lampp and gdb. Thanks!
From http://inside.mines.edu/~lwiencke/elab/gdb/gdb_19.html: show environment [varname] set environment varname [=] value And from http://davis.lbl.gov/Manuals/GDB/gdb_5.html#SEC22 You can redirect your program's input and/or output using shell redirection with the run command. For example, E.g. run < input_fil...