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 Standards: 101 Rules, Guidelines, and Best Practices). What are your practices? Thanks.
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 that their code would compile without any warnings. Only that their code would run correctly. After several attemps, I started surrounding the Qt header files with pragmas to disable the warnings as shown below - #pragma warning(push,3) // drop compiler to level 3 and save current level #include <QString> #include <QVariant> #include <QStack> #include <QLabel> #include <QtGui/QTableWidget> #pragma warning(pop) // restore compiler warning level By doing it this way, you only compile the Qt header files at the lower warning level. Or whatever level it takes to get rid of the warnings. You may have some individual warnings that still show up, so you could raise the warning level or disable individual warnings with #pragma warning(disable: 4700) Some Boost library files also have this problem.
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]]; C++0x fine, using g++ 4.4.1. STL is preferable as I don't use Boost for any other parts of the code (though I wouldn't mind an example with it!).
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 connection abruptly terminates the socket select() call is returning immediately which is what I believe it is meant to do? Anyway, it returns all of the disconnected sockets within the readable set of file descriptors but the problem is that an exception "Socket is not connected" is thrown when Poco tries to fire the onReadable event handler which is where I would be putting the code to deal with this. Given that the exception is silently caught and the onReadable event is never fired, the select() call keeps returning immediately resulting in an infinite loop in the SocketReactor. I was considering modifying the Poco code so that rather than catching the exception silently it fires a new event called onDisconnected or something like that so that a cleanup can be performed. My question is, are there any elegant ways of determining whether a socket has closed abnormally using select() calls? I was thinking of using the exception message to determine when this has occured but this seems dirty to me.
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; tv.tv_usec = 250000; rc = ::select(int(_sockfd) + 1, &fdRead, (fd_set*) 0, (fd_set*) 0, &tv); ioctl(FIONREAD, &bytestoread); return !((bytestoread == 0) && (rc == 1)); } From my understanding, this checks if the socket is readable using a call to select() and then checks the actual number of bytes which are available on that socket. If the socket reports that it is readable but the bytes are 0 then the socket is not actually connected. While this answers my question here, this unfortunately has not solved my Poco problem as I can't figure out a way to fix this in the Poco SocketReactor code. I tried making a new event called DisconnectNotification but unfortunately cannot call that as the same error gets thrown as does for a ReadNotification on a closed socket.
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 errors or shouldn't fail at all, respectively. Now let's consider the following example: We have two classes, a more or less complex class State and a class StateContainer, which should be self-explained. class State { private: unsigned smth; public: State(); State( unsigned s ); }; class StateContainer { private: unsigned long nStates; State *states; public: StateContainer(); StateContainer( unsigned long n ); virtual ~StateContainer(); }; StateContainer::StateContainer() { nStates = SOME_DEFINE_N_STATES; states = new State[nStates]; if ( !states ) { // Error handling } } StateContainer::StateContainer( unsigned long n ) { nStates = n; try { states = new State[nStates] } catch ( std::bad_alloc &e ) { // Error handling } } StateContainer::~StateContainer() { if ( states ) { delete[] states; states = 0; } } Now actually, I have two questions: 1.) Is it ok, to call new within a constructor, or is it better to create an extra init()-Method for the State-Array and why? 2.) Whats the best way to check if new succeeded: if (!ptr) std::cerr << "new failed." or try { /*new*/ } catch (std::bad_alloc) { /*handling*/ } 3.) Ok its three questions ;o) Under the hood, new does some sort of ptr = (Struct *)malloc(N*sizeof(Struct)); And then call the constructor, right?
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 help against other possible exceptions. Then what can you do to "handle" it in such a way that the other code is aware and can react appropriately? Use exceptions right - let them propagate to the site where they can be reasonably handled.
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 values. I have this at the moment: po::options_description desc("Allowed options"); desc.add_options() ("help,h", "display this help message") ("path,p", po::value<std::string>(), "Executable file path") ("start_address,s", po::value<std::string>(), "Start address") ("end_address,e", po::value<std::string>(), "End address") ; Can boost::lexical_cast do such a conversion?
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_address;
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 condition if(num <5) is if num is among a specific numberList. Given this, is there a better way to delete the elements of a vector than what I am illustrating below? #include<vector> #include<stdio.h> #include<iostream> class A { public: int getNumber(); A(int val); ~A(){}; private: int num; }; A::A(int val){ num = val; }; int A::getNumber(){ return num; }; int main(){ int i =0; int num; std::vector<A> vec_A; std::vector<A>::iterator iter; for ( i = 0; i < 10; i++){ vec_A.push_back(A(i)); } iter = vec_A.begin(); while(iter != vec_A.end()){ std::cout << "\n --------------------------"; std::cout << "\n Size before erase =" << vec_A.size(); num = iter->getNumber() ; std::cout << "\n num = "<<num; if (num < 5){ vec_A.erase(iter); } else{ iter++; } std::cout << "\n size after erase =" << vec_A.size(); } std::cout << "\nPress RETURN to continue..."; std::cin.get(); return 0; }
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 the vector. When you do erase, vector will take care of deleting the elements. Assume that condition if(num <5) is if num is among a specific numberList. Given this, is there a better way to delete the elements of a vector than what I am illustrating below? Yes, you can remove/erase idiom. This is an example: class A { public: A(int n) : m_n(n) { } int get() const { return m_n; } private: int m_n; }; bool lessThan9(const A& a) { return a.get() < 9; } //Or if you want for a generic number struct Remover : public std::binary_function<A,int,bool> { public: bool operator()(const A& a, int n)const { return a.get() < n; } }; int main() { std::vector<A> a; a.push_back(A(10)); a.push_back(A(8)); a.push_back(A(11)); a.push_back(A(3)); a.erase(std::remove_if(a.begin(), a.end(), lessThan9), a.end()); //Using the user-defined functor a.erase(std::remove_if(a.begin(), a.end(), std::bind2nd(Remover(), 9)), a.end()); return 0; }
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? Is it responsible to let an application live when it has failed so disasterously? Would it be more responsible to alert the user and die? Edit: One of the arguments of letting the exception unhandled is that Access Violation shows that the program was prevented from doing harm, and probably haven't done any either. I am not sure if I buy that. Are there any views on this?
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 constrained to a known, largely harmless situation, then I'd tend to think continuing to produce and ship the product with the faulty code could be considered irresponsible, regardless of how you handle the violation. If it's a very narrowly constrained, known situation, how you handle it depends on the situation. You seem to know what the fault is, so you're in the position to know whether you can carry on in the face of that fault or not. I would tend to lean toward report and exit, but again, it totally depends on what the fault actually is.
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 errors. What is it? some kind of old version C?
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 confused by the added C/C++/etc. support in Sphinx 1.0: this only covers new reStructeredText directives to better format (and index) documentation regarding non-python code. It is theoretically possible to use a tool like Doxygen to extract documentation from C++ sources and use that in Sphinx, but this requires custom tools. Breathe may be one such tool.
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 bit like: void MyClass::setVar(const char *str) { mStr.assign(str ? str : "",maxLength); } But it seems kind of messy. ideas?
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.clear(); else mStr.assign(str, std::min(strlen(str), maxLength)); }
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 gdk_pixbuf_get_has_alpha returns true) so I'm guessing that the problem is with the alpha mask. GdkPixbuf has a function to add an alpha channel, but I can't see one that removes it again, or (which might be as good) to invert it. Is there a simple way to get the jpeg and bmp formats to work properly? (I should say that I'm very new to proper programming like this.)
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 channel can be done manually. The trick is understanding how the data in a GdkPixbuf is stored. When you have an RGB pixbuf with an alpha channel (also called RGBA), the pixels are stored as 32-bit values: 4 bytes, one byte per color, the fourth being the alpha channel. RGB pixbufs are stored as 24-bit values, one byte per color. So, if you create a temporary byte buffer and copy over the first three bytes of each RGBA pixel and drop the fourth, that temporary buffer is then pure RGB. To diagram it a little: [R][G][B][A][R][G][B][A]... => [R][G][B][R][G][B]... Note that you have to pack the temporary buffer; there's no spare byte between the [B] byte and the next [R] byte. You then create a new GdkPixbuf by handing it this RGB buffer, and you've removed the alpha channel. See gdk_pixbuf_get_pixels() to access the RGBA buffer and gdk_pixbuf_new_from_data() to create the RGB pixbuf. See here for more discussion on how the packed data is stored inside a GdkPixbuf.
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 = getBar(); Where Foo is a sub-class of Bar. So in C++.... std::list<Bar> * getBars() { std::list<Bar> * bars = new std::list<Bar>; return bars; } std::list<Foo> * stuff = getBars(); Hope that makes sense....
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, except I think if you provide the right copy operator. But if you use inheritance, all your foos and bars should be pointers (and if you can smart ones as shared_ptr pointers from boost or tr1). But that doesn't mean the copy works. I'm not really sure about what you want to do, but transposing from JAVA to C++ in this case does not work. If you create foos, they will have everything from bars automatically. std::list< Foo > foos; // just work fine If you want a list of bars constructed as foos: std::list< Bar * > bars; bars.push_back( new Foo() ); Or as I would put it in real C++ code with shared_ptr: typedef boost::shared_ptr< Bar >; typedef boost::shared_ptr< Foo >; typedef std::list< BarPtr > BarList; BarList bars; bars.push_back( FooPtr( new Foo() ) );
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 till the specified number. looked up a concept called Goldbach conjecture which expresses an even number as the summation of two primes. However, I am stuck beyond that. Can anyone help me on this one as to what approach you might take? The sieve of Eratosthenes is taking two seconds to count primes up to 100,000.
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: Actually, you could speed this up significantly: For any even Number N, find the largest prime that is less or equal N-7 and choose that prime and 3, then look for two further primes to suit your sum. For any odd Number N, find the largest prime greater or equal N-6 and choose it and two, then again choose two primes.
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 and linker would find the same name in its input *.lib files and problem is solved. Calling C++ function from C??? But here I'm extending a large application which is written in C and I need to use a library which is written in C++. Name mangling of C++ is causing trouble here. Linker is complaining about the unresolved symbols. Well I cannot use C++ compiler over my C project because thats breaking lot of other stuff. What is the way out? By the way I'm using MSVC
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 follow an object-oriented style, even though C is not object-oriented. Ex: // *.h file // ... #ifdef __cplusplus #define EXTERNC extern "C" #else #define EXTERNC #endif typedef void* mylibrary_mytype_t; EXTERNC mylibrary_mytype_t mylibrary_mytype_init(); EXTERNC void mylibrary_mytype_destroy(mylibrary_mytype_t mytype); EXTERNC void mylibrary_mytype_doit(mylibrary_mytype_t self, int param); #undef EXTERNC // ... // *.cpp file mylibrary_mytype_t mylibrary_mytype_init() { return new MyType; } void mylibrary_mytype_destroy(mylibrary_mytype_t untyped_ptr) { MyType* typed_ptr = static_cast<MyType*>(untyped_ptr); delete typed_ptr; } void mylibrary_mytype_doit(mylibrary_mytype_t untyped_self, int param) { MyType* typed_self = static_cast<MyType*>(untyped_self); typed_self->doIt(param); }
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; //Prints the address of i before return return i; } int main() { int i = foo(); std::cout << i << std::endl; //Prints the value std::cout << &i << std::endl; //Prints the address of i after return }
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 trees. I know how to implement generating a whole tree, but not parts of it.
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 made and the board is full. The reason you need to have a tree, is that once it is built, you need to figure out which branch has the most leaves that are 'WIN' scenarios. You build the branch of all possible outcomes, add up the total number of WINs, and then make the move that has the chance to end up with the most wins. Make the tree something like this: class Node { public: std::list< Node > m_branches; BoardState m_board; int m_winCount; } std::list< Node > tree; Now, you iterate through the list of branches in the tree, and for each branch, iterate through its branches. This can be done with a recursive function: int recursiveTreeWalk( std::list< Node >& partialTree) { for each branch in tree if node has no branches calculate win 1/0; else recursiveTreeWalk( branch ); partialTree.m_winCount = sum of branch wins; } // initial call recursiveTreeWalk( tree ) Very pseudo-code.
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, // filename int line, // line number CMyEvent::LEVEL level, // severity level const char *format, // format of the msg / data ...) // variable arguments { // Get a message from the pool CMyEvent* p_msg = GetMessageFromPool(); if(p_msg != NULL) { va_list arguments; // points to each unnamed argument va_start(arguments, format); // Fill the object with strings and data. p_msg->Fill(file, line, level, 0, format, arguments); va_end(arguments); } }
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 it like (warning: all code here is pseudocode and may be syntactically incorrect, but you should get the basic idea): EVENT_INFO ("The answer to " << the_question << " is " << answer); // usually 42 The EventLogStream is similar to the cout object and like cout, you can provide class specific output: class Vector3D { EventLogStream &operator << (EventLogStream &out) { out << "{" << x << ", " << y << ", " << z << "}"; } }
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 an extra comparison and multiplication; and other methods I've seen (used in fact) involve casting as a float or double. Is there a more direct method that avoids the additional multiplication (or a second division) and branch, and that also avoids casting as a floating point number?
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 an api that i am providing. so for different input values I generate 6 digit codes.
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::lambda; transform(y.begin(), y.end(), x.begin(), y.begin(), (_1 + scale*_2); // I thought something may exist: transform2(x.begin(), x.end(), y.begin(), (_2 + scale*_1); // it does not, so no biggie. I will write wrapper Thanks
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) const { return rhs + f(lhs); } }; std::transform(x.begin(), x.end(), y.begin(), y.begin(), Predicate()); // // C++0x way // std::transform(x.begin(), x.end(), y.begin(), y.begin(), [](X lhs, Y rhs) { return rhs += f(lhs); }); Now, if we had a vector with the range of indices, we could do it in a more "pythony" way: std::vector<size_t> indices = /**/; // // STL-way // class Predicate: public std::unary_function<size_t, void> { public: Predicate(const std::vector<X>& x, std::vector<Y>& y): mX(x), mY(y) {} void operator()(size_t i) const { y.at(i) += f(x.at(i)); } private: const std::vector<X>& mX; std::vector<Y>& mY; }; std::foreach(indices.begin(), indices.end(), Predicate(x,y)); // // C++0x way // std::foreach(indices.begin(), indices.end(), [&](size_t i) { y.at(i) += f(x.at(i)); }); // // Boost way // BOOST_FOREACH(size_t i, indices) y.at(i) += f(x.at(i)); I don't know if there could be something to do with views, they normally allow some pretty syntax. Of course it's a bit difficult here I think because of the self-modifying y.
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 CourseRec CourseList [NUMCOURSES]; CourseList courses; int index1, index2; What is the data type of the expression courses[index1] .courseName[index2] ? (a) CourseList (b) CourseRec (c) string (d) char (e) none; the expression is syntactically invalid I thought that the answer would be string, since courseName is a string, or maybe even CourseRec, since it is in the struct, but the answer is (d)char. Why is this a char data type? Any help is greatly appreciated.
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<Test> tVec; tVec.push_back(tObj); I get a runtime crash in the destructor of Test when I go out of scope. Why is this and how can I safely free my memory?
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 destroyed, it tries to destroy the already-destroyed array again. Further, when tVec is destroyed, it will destroy its elements, so the already-destroyed array will be destroyed yet again. You should define a copy constructor and an assignment operator so that when a Test object gets copied, the big array gets copied, or has some sort of reference count so that it doesn't get destroyed until all owners are destroyed. An easy fix is to define your class like this: class Test { private: std::vector<int> big; public: Test (): big(10000) {} }; In this case, you wouldn't need to define any destructor, copy constructor, or assignment operator, because the std::vector<> member will take care of everything. (But note that this means 10,000 integers get allocated and copied whenever you copy an instance of Test.)
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 meaning "transfer execution to the point after the end of the innermost breakable construct".
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 leaks?
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 (int i = 0; i < 10; ++i) { double *array= new double[anySize]; } will for the same reason leak 10 * anySize * sizeof(double) bytes of memory.
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 extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); Now this works fine for sending Space: public static void SendKeyPress(IntPtr handle, VKeys key) { SendMessage(handle, (int) WMessages.WM_KEYDOWN, (int) key, 0); SendMessage(handle, (int)WMessages.WM_KEYUP, (int)key, 0); } But this doesn't work for sending Ctrl+↑ to VLC to increase the sound volume: public static void SendKeyPress(IntPtr handle, VKeys key, bool control) { int lParamKeyDown = 0; lParamKeyDown |= 1; lParamKeyDown |= 1 << 24; int lParamKeyUp = lParamKeyDown; lParamKeyUp |= 1 << 30; lParamKeyUp |= 1 << 31; //it was down before int lParamCtrlDown = lParamKeyDown; int lParamCtrlUp = lParamKeyUp; lParamKeyDown |= (int)MapVirtualKey((uint)key, 0) << 16; lParamKeyUp |= (int)MapVirtualKey((uint)key, 0) << 16; lParamCtrlDown |= (int)MapVirtualKey((uint)VKeys.VK_CONTROL, 0) << 16; lParamCtrlUp |= (int)MapVirtualKey((uint)VKeys.VK_CONTROL, 0) << 16; IntPtr controlPtr = new IntPtr((int)VKeys.VK_CONTROL); IntPtr lParamCtrlDownPtr = new IntPtr(lParamCtrlDown); IntPtr lParamCtrlUpPtr = new IntPtr(lParamCtrlUp); IntPtr lParamKeyDownPtr = new IntPtr(lParamKeyDown); IntPtr lParamKeyUpPtr = new IntPtr(lParamKeyUp); IntPtr keyPtr = new IntPtr((int)key); object o = new object(); HandleRef wndRef = new HandleRef(o, handle); PostMessage(wndRef, (uint)WMessages.WM_KEYDOWN, controlPtr, lParamCtrlDownPtr); PostMessage(wndRef, (uint) WMessages.WM_KEYDOWN, keyPtr, lParamKeyDownPtr); PostMessage(wndRef, (uint) WMessages.WM_KEYUP, controlPtr, lParamCtrlUpPtr); PostMessage(wndRef, (uint) WMessages.WM_KEYUP, keyPtr, lParamKeyUpPtr); } What am I missing? Edit3: The Messages are exactly the same and there are no extra messages since I switched to PostMessage but VLC still won't increase or decrease the volume. It's not just VLC either, Spotify won't accept the same command even though the messagess look exactly alike in Spy++.
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); SendMessage(handle, (int) WMessages.WM_KEYDOWN, (int) key, 0); so that the control key being down essentially wraps the press of the other key?
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 me a set of points in the plane, and I have to find 3 points that form my triangle after one or more of those geometric operations. Example: 5 15 8 5 20 10 6 5 17 5 20 20 5 10 5 15 20 15 10 Output: 5 17 10 5 15 20 I bet it's supposed to apply some known algorithm, but I don't know which. The most common are: convex hull, sweep plane, triangulation, etc. Can someone give a tip? I don't need the code, only a push, please!
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), but with a low coefficient because most lengths will not match. Now you have a sparse graph with O(V) edges. Find every cycle of size 3 in O(V) time, and prune the matches. (Not sure of the best way, but here is one way with proper big-O.) Total complexity: O(V^2) but finding the cycles in O(V) may be the limiting factor, depending on the number of points. Spatially sorting the list of points to avoid looking at all pairs should improve the asymptotic behavior, otherwise.
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 a, int b); int add_stuff(int a, int b) { return a+b; } void call_adder(int a, int b) { fptr = &FOO::add_stuff; cout<<(this->*fptr)(a,b)<<endl; } }; class BAR { public: int add_stuff(int a, int b) { return a+b; } void call_adder(int a, int b) { //int (BAR::*fptr)(int a, int b); //fptr = &BAR::add_stuff; //cout<<(*fptr)(a,b)<<endl; } }; int main() { FOO test; test.call_adder(10,20); return 0; }
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 { int i; public: BAR(): i(0) {}; int AddOne() { return ++i; }; int GetI() { return i; }; } int main() { BAR bar; auto fPtr = &BAR::AddOne; // This line is C++0x only (because of auto) std::cout << (bar.*fPtr)(); //This will print 1 to the console std::cout << std::endl; std::cout << bar.GetI(); //This will also print 1 to the console. }
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 uses that in its calculations of lighting of other objects in the scene, but it does not attempt to draw any sort of bright area in that part of the scene to show the light itself. Drawing a real-looking light source can be fairly tricky -- you not only have to show the light itself, but at least some amount of "glow" around it (if you want to get technical, the amount should vary depending on things like the humidity and dust in the air, but most people don't really try to compute that).
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 int validMove = tBoard.FirstValidMove(); if (validMove != -1) { Node f; Ticboard tempBoard = nNode.m_board; tempBoard.Move(validMove, nextPlayer); tBoard.Move(validMove, nextPlayer); f.m_board = tempBoard; f.m_winCount = 0; nNode.m_branches.push_back(f); int currPlay = (nextPlayer == 1 ? 2 : 1); BuildTree(f,currPlay); } else { break; } }while(true); } The actual function works, I've gone through and debugged it and it SHOWS it working as it is supposed to, but when I look at the nodes generated (for Tic-Tac-Toe, by the way) in Visual Studios via breakpoint, it only shows the first 9 branches. I know more were generated because it takes a few seconds, and I added a counter. Here's how I call the code: Ticboard lol; Node startTree; startTree.m_board = lol; int startPlay = 1; BuildTree(startTree, startPlay); Without copying all my code for bitboards and whatnot in here, can you see anything immediately wrong with the logic?
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 return *this; } Now lets say I have this constructor as well: Class1::Class1(Class1 *class1) { *this = *class1; } My question is would the above constructor be acceptable practice? This is code that i've inherited and maintaining.
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 won't work!) because all members of Class1 are default-initialized, and then copied using operator= operator= has the same problem; it should accept a reference, not a pointer. The traditional way to "re-use" the copy constructor in operator= is the copy-and-swap idiom. I would suggest implementing the class that way.
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 this? EDIT: Moved my example solution to a separate answer.
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 FILE*. Based on above observations and my research below there's working code in two variants; one for libstdc++ and another one for Microsoft Visual C++. libstdc++ There's non-standard __gnu_cxx::stdio_filebuf class template which inherits std::basic_streambuf and has the following constructor stdio_filebuf (int __fd, std::ios_base::openmode __mode, size_t __size=static_cast< size_t >(BUFSIZ)) with description This constructor associates a file stream buffer with an open POSIX file descriptor. We create it passing POSIX handle (line 1) and then we pass it to istream's constructor as basic_streambuf (line 2): #include <ext/stdio_filebuf.h> #include <iostream> #include <fstream> #include <string> using namespace std; int main() { ofstream ofs("test.txt"); ofs << "Writing to a basic_ofstream object..." << endl; ofs.close(); int posix_handle = fileno(::fopen("test.txt", "r")); __gnu_cxx::stdio_filebuf<char> filebuf(posix_handle, std::ios::in); // 1 istream is(&filebuf); // 2 string line; getline(is, line); cout << "line: " << line << std::endl; return 0; } Microsoft Visual C++ There used to be non-standard version of ifstream's constructor taking POSIX file descriptor but it's missing both from current docs and from code. There is another non-standard version of ifstream's constructor taking FILE* explicit basic_ifstream(_Filet *_File) : _Mybase(&_Filebuffer), _Filebuffer(_File) { // construct with specified C stream } and it's not documented (I couldn't even find any old documentation where it would be present). We call it (line 1) with the parameter being the result of calling _fdopen to get C stream FILE* from POSIX file handle. #include <cstdio> #include <iostream> #include <fstream> #include <string> using namespace std; int main() { ofstream ofs("test.txt"); ofs << "Writing to a basic_ofstream object..." << endl; ofs.close(); int posix_handle = ::_fileno(::fopen("test.txt", "r")); ifstream ifs(::_fdopen(posix_handle, "r")); // 1 string line; getline(ifs, line); ifs.close(); cout << "line: " << line << endl; return 0; }
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 your C++ members: struct CppImpl { SomeClass& ref; CppImpl(SomeClass& ref) : ref(ref) {} }; @interface A : NSObject { CppImpl* pimpl; } - (id)initWithRef:(SomeClass&)ref; @end @implementation - (id)initWithRef:(SomeClass&)ref { if(self = [super init]) { pimpl = new CppImpl(ref); } return self; } // clean up CppImpl in dealloc etc. ... @end
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 function printf("Hello World!"); is a lot more readable and logical to me than cout << "Hello World"; I also think that all of those string abstractions in C++ all compile down to (less efficient) standard function calls in binary.
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 output to go to a file instead of to the console. With C calls you'll have to replace all of the calls to printf to calls to fprintf and take care to maintain the FILE* along the way. With streams you just change the concrete class of the stream you're using and that's it, most of the code remains the same like so: void doSomething(ostream& output) { output << "this and that" << a; } doSomething(cout); doSomething(ofstream("c:\file.txt"));
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/minimal) memory usage? Please kindly advise. Thanks! EDIT: I read fixed number of bytes: 25KB or 100KB (depending on QCIF/CIF format). The reading is in binary mode and forward-only. No seeking needed. No writing needed, only reading. EDIT: If identifying better of them is hard, which one does not require loading the whole file into memory?
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. etc. Edit: To answer your expanded question - neither library requires you read everything into memory. Why would you think they do?
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, which will also allow for multiple table cells per row like the QTableWidget. If you want something fancier like the firefox downloader, you may have to create an item delegate to handle the drawing yourself.
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 40) for a single order of 1 to 16 Quest Courses.
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; int b; int c; }; Test global; int main() { Test *p = new Test; p->a = 1; p->b = 2; p->c = 3; p = &global; delete p; return 0; }
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 } return ( p<= dwStackTop && p>= dwStackLowCurrent ); }
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 is the defination of this class FibTask. class FibTask: public task { public: const long n; long* const sum; FibTask(long n_,long* sum_):n(n_),sum(sum_) {} task* execute() { if(n<CutOff) { *sum=SFib(n); } else { long x,y; FibTask& a=*new(allocate_child()) FibTask(n-1,&x); FibTask& b=*new(allocate_child()) FibTask(n-2,&y); set_ref_count(3); spawn(b); spawn_and_wait_for_all(a); *sum=x+y; } return 0; } };
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 allocation algorithm, as demonstrated in the code you're reading (allocate_child()).
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, System.Drawing.Imaging.ImageFormat.Tiff); return ms.ToArray(); } private Image byteArrayToImage(byte[] byteArrayIn) { MemoryStream ms = new MemoryStream(byteArrayIn); BinaryWriter bw = new BinaryWriter(ms); bw.Write(byteArrayIn); Image returnImage = Image.FromStream(ms, true, false); return returnImage; } // Convert Image into string byte[] imagebytes = ImageToByteArray(anImage); string Base64EncodedStringImage = Convert.ToBase64String(imagebytes); // Convert string into Image byte[] imagebytes = Convert.FromBase64String(Base64EncodedStringImage); Image anImage = byteArrayToImage(imagebytes); (and, now that I'm looking at it, could be simplified even further) I now have a business need to do this in C++. I'm using GDI+ to draw the graphics (Windows only so far) and I already have code to decode the string in C++ (to another string). What I'm stumbling on, however, is getting the information into an Image object in GDI+. At this point I figure I need either a) A way of converting that Base64-decoded string into an IStream to feed to the Image object's FromStream function b) A way to convert the Base64-encoded string into an IStream to feed to the Image object's FromStream function (so, different code than I'm currently using) c) Some completely different way I'm not thinking of here. My C++ skills are very rusty and I'm also spoiled by the managed .NET platform, so if I'm attacking this all wrong I'm open to suggestions. UPDATE: In addition to the solution I've posted below, I've also figured out how to go the other way if anyone needs it.
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 a resource table.
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 Base class Vehicle : virtual public Base { public: Vehicle() : Base() { } ~Vehicle() { } }; // class Vehicle class Car : public Vehicle { public: Car() : Base(), Vehicle() { } ~Car() { } }; // class Car int main(int a_Data, char** argv) { Car* stupid = new Car(); return 0; } Seems easy enough, right? Here's how I compile it, which is the same way I compile the rest of my code: /home/oem/android-ndk-r3/build/prebuilt/linux-x86/arm-eabi-4.4.0/bin/arm-eabi-g++ -g -std=c99 -Wall -Werror -O2 -w -shared -fshort-enums -I ../../YoghurtGum/src/GLES -I ../../YoghurtGum/src -I /home/oem/android-ndk-r3/build/platforms/android-5/arch-arm/usr/include -c src/Inheritance.cpp -o intermediate/Inheritance.o (Line breaks are added for clarity). This compiles fine. But then we get to the linker: /home/oem/android-ndk-r3/build/prebuilt/linux-x86/arm-eabi-4.4.0/bin/arm-eabi-gcc -lstdc++ -Wl, --entry=main, -rpath-link=/system/lib, -rpath-link=/home/oem/android-ndk-r3/build/platforms/android-5/arch-arm/usr/lib, -dynamic-linker=/system/bin/linker, -L/home/oem/android-ndk-r3/build/prebuilt/linux-x86/arm-eabi-4.4.0/lib/gcc/arm-eabi/4.4.0, -L/home/oem/android-ndk-r3/build/platforms/android-5/arch-arm/usr/lib, -rpath=../../YoghurtGum/lib/GLES -nostdlib -lm -lc -lGLESv1_CM -z /home/oem/android-ndk-r3/build/platforms/android-5/arch-arm/usr/lib/crtbegin_dynamic.o /home/oem/android-ndk-r3/build/platforms/android-5/arch-arm/usr/lib/crtend_android.o intermediate/Inheritance.o ../../YoghurtGum/bin/YoghurtGum.a -o bin/Galaxians.android As you can probably tell, there's a lot of cruft in there that isn't really needed. That's because it doesn't work. It fails with the following errors: intermediate/Inheritance.o:(.rodata._ZTI3Car[typeinfo for Car]+0x0): undefined reference to `vtable for __cxxabiv1::__si_class_type_info' intermediate/Inheritance.o:(.rodata._ZTI7Vehicle[typeinfo for Vehicle]+0x0): undefined reference to `vtable for __cxxabiv1::__vmi_class_type_info' intermediate/Inheritance.o:(.rodata._ZTI4Base[typeinfo for Base]+0x0): undefined reference to `vtable for __cxxabiv1::__class_type_info' collect2: ld returned 1 exit status make: *** [bin/Galaxians.android] Fout 1 These are the same errors I get from my actual application. If someone could explain to me where I went wrong in my test or what option or I forgot in my linker, I would be very, extremely grateful. Thanks in advance. UPDATE: When I make my destructors non-inlined, I get new and more exciting link errors: intermediate/Inheritance.o:(.rodata+0x78): undefined reference to `vtable for __cxxabiv1::__si_class_type_info' intermediate/Inheritance.o:(.rodata+0x90): undefined reference to `vtable for __cxxabiv1::__vmi_class_type_info' intermediate/Inheritance.o:(.rodata+0xb0): undefined reference to `vtable for __cxxabiv1::__class_type_info' collect2: ld returned 1 exit status make: *** [bin/Galaxians.android] Fout 1
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 provides your missing externals). Is there a reason you need this?
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 file int line_count = 0; char buffer[1024]; while(fgets(buffer, 1023, fp)) { // Increment line counter line_count++; char *bufferp = buffer; ... while(*bufferp != '\n') { char *tmp; if(sscanf(bufferp, "%c", tmp) != 1) { fprintf(stderr, "Syntax error reading axiom on " "line %d in file %s\n", line_count, filename); return 0; } axiom.push_back(tmp); printf("put %s in axiom vector\n", axiom[axiom.size()-1]); // increment buffer pointer bufferp++; } } my axiom vector is defined as vector<char *> axiom;. When I run my program, I get a seg fault. It happens when I do the sscanf. Any suggestions on what I'm doing wrong?
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 use my AA::mb pointer in the code. So things I would like to know are following. When the program exits A::f1() function, b variable since declared as a local variable and placed on the stack, can't be used anymore afterwards. What happens with the validity of the AA::mb pointer? It contains the address of the local variable which could not be available anymore, so the pointer isn't valid anymore? If B class is a std::<vector>, and AA::mb is not a pointer anymore to that vector, but a vector collection itself for example. I would like to avoid copying all of it's contents in AA::f2() to a member AA::mb in line mb = b. Which solution would you recommend since I can't assign a pointer to it, because it'll be destroyed when the program exits AA::f2()
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 assignments.
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 when I tried to specialize swap for my own string type and noticed that swap<::string> doesn't work, but for a completely different reason :)
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> template<> void f<MyType>(int t) { } Of course in your case, it's the digraph <: that's meaning the same as [ causing your problem. Put a space like < ::string> to avoid the problem.
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 creating an engine I can skip it and use sio2 or oolong? Thanks
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 your own game using oolong or SIO. Trust me, you are not going to want to use the code you wrote when you were learning C++ to make an actual game, unless you can read something and immediately master it.
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_PING); send(packet); } void send(Packet packet) { cout << "DEBUG> Transferring packet with opcode " << packet.GetOpcode() << endl; async_write(m_socket, buffer(packet.write()), boost::bind(&Session::writeHandler, shared_from_this(), placeholders::error, placeholders::bytes_transferred)); } void writeHandler(const boost::system::error_code& errorCode, size_t bytesTransferred) { cout << "DEBUG> Transfered " << bytesTransferred << " bytes to " << m_socket.remote_endpoint().address().to_string() << endl; } Start gets called once a connection is made. packet.write() returns a uint8_t vector Would it matter if I'd change void send(Packet packet) to void send(Packet& packet) Not in relation to this problem but performance wise.
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 are inside a list in the object which I need to use. I wanted to test making a C++ extension with this function: def setup_framebuffer(surface,flip=False): #Create texture if not done already if surface.texture is None: create_texture(surface) #Render child to parent if surface.frame_buffer is None: surface.frame_buffer = glGenFramebuffersEXT(1) glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, c_uint(int(surface.frame_buffer))) glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, surface.texture, 0) glPushAttrib(GL_VIEWPORT_BIT) glViewport(0,0,surface._scale[0],surface._scale[1]) glMatrixMode(GL_PROJECTION) glLoadIdentity() #Load the projection matrix if flip: gluOrtho2D(0,surface._scale[0],surface._scale[1],0) else: gluOrtho2D(0,surface._scale[0],0,surface._scale[1]) That function calls create_texture, so I will have to pass that function to the C++ function which I will do with the third argument. This is what I have so far, while trying to follow information on the python documentation: #include <Python.h> #include <GL/gl.h> static PyMethodDef SpamMethods[] = { ... {"setup_framebuffer", setup_framebuffer, METH_VARARGS,"Loads a texture from a Surface object to the OpenGL framebuffer."}, ... {NULL, NULL, 0, NULL} /* Sentinel */ }; static PyObject * setup_framebuffer(PyObject *self, PyObject *args){ bool flip; PyObject *create_texture, *arg_list,*pyflip,*frame_buffer_id; if (!PyArg_ParseTuple(args, "OOO", &surface,&pyflip,&create_texture)){ return NULL; } if (PyObject_IsTrue(pyflip) == 1){ flip = true; }else{ flip = false; } Py_XINCREF(create_texture); //Create texture if not done already if(texture == NULL){ arglist = Py_BuildValue("(O)", surface) result = PyEval_CallObject(create_texture, arglist); Py_DECREF(arglist); if (result == NULL){ return NULL; } Py_DECREF(result); } Py_XDECREF(create_texture); //Render child to parent frame_buffer_id = PyObject_GetAttr(surface, Py_BuildValue("s","frame_buffer")) if(surface.frame_buffer == NULL){ glGenFramebuffersEXT(1,frame_buffer_id); } glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, surface.frame_buffer)); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, surface.texture, 0); glPushAttrib(GL_VIEWPORT_BIT); glViewport(0,0,surface._scale[0],surface._scale[1]); glMatrixMode(GL_PROJECTION); glLoadIdentity(); //Load the projection matrix if (flip){ gluOrtho2D(0,surface._scale[0],surface._scale[1],0); }else{ gluOrtho2D(0,surface._scale[0],0,surface._scale[1]); } Py_INCREF(Py_None); return Py_None; } PyMODINIT_FUNC initcscalelib(void){ PyObject *module; module = Py_InitModule("cscalelib", Methods); if (m == NULL){ return; } } int main(int argc, char *argv[]){ /* Pass argv[0] to the Python interpreter */ Py_SetProgramName(argv[0]); /* Initialize the Python interpreter. Required. */ Py_Initialize(); /* Add a static module */ initscalelib(); }
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, PyObject_IsTrue() returns a boolean. Don't compare it to 1, just use it as a boolean value. However, you should check if it returned an error, which would be -1. (The usual check is < 0.) If you don't check for error returns you end up swallowing the exception, but leaving the exception object hanging around. This is bad. The Py_XINCREF() of create_texture is not necessary. You have a borrowed reference to the args tuple, which in turn owns a reference to the create_texture object. There is no way for create_texture to go away before your function returns. You only need to incref it if you are going to keep it around longer than this functioncall. If you did have to incref it, you wouldn't need to use Py_XINCREF() because it won't ever be NULL. And if you did have to incref it, you would need to remember to decref it in your error return case, as well. Instead of creating an argument tuple just to call PyEval_CallObject(), just call PyObject_CallFunctionObjectArgs(create_texture, arglist, NULL) or PyObject_CallFunction(create_texture, "O", arglist). Py_BuildValue("s", "frame_buffer") is not really the right way to get a Python string for "frame_buffer". A better way is PyString_FromString(). However, both of those return new references, and PyObject_GetAttr() doesn't eat the reference to the attribute name, so you end up leaking that reference. You should use none of these, and instead use PyObject_GetAttrString(), which takes the attribute name as a const char*. Remember to check the return value of all functions that can return an error value (which is almost all Python API functions.) Besides PyTrue_IsTrue() you're also forgetting this for Py_BuildValue() and PyObject_GetAttr().
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 data -- ergo the data of their parents. The direction of owning is of course that a map owns it's beings, so holds shared pointers to them. To access the map data from within a being we however need a pointer to the parent -- the smart pointer way is to use a reference, ergo a weak_ptr. However, I once read that locking a weak_ptr is a expensive operation -- maybe that's not true anymore -- but considering that the weak_ptr will be locked very often, I'm concerned that this design is doomed with poor performance. Hence the question: What is the performance penalty of locking a weak_ptr? How significant is it?
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_file_in_array@@YAHQAY02H@Z) referenced in function _main fatal error LNK1120: 1 unresolved externals i believe this one has to do with brackets #include <iostream> #include <fstream> using namespace std; int read_file_in_array(int exam[100][3]); double calculate_total(int exam1[], int exam2[], int exam3[]); // function that calcualates grades to see how many 90,80,70,60 //void display_totals(); double exam[100][3]; int read_file_in_array(double exam[100][3]) { ifstream infile; int exam1[100]; int exam2[100]; int exam3[100]; infile.open("grades.txt");// file containing numbers in 3 columns if(infile.fail()) // checks to see if file opended { cout << "error" << endl; } int num, i=0,j=0; while(!infile.eof()) // reads file to end of line { for(i=0;i<100;i++) // array numbers less than 100 { for(j=0;j<3;j++) // while reading get 1st array or element infile >> exam[i][j]; infile >> exam[i][j]; infile >> exam[i][j]; cout << exam[i][j] << endl; { if (! (infile >> exam[i][j]) ) cout << exam[i][j] << endl; } exam[i][j]=exam1[i]; exam[i][j]=exam2[i]; exam[i][j]=exam3[i]; } infile.close(); } return 0; } double calculate_total(int exam1[],int exam2[],int exam3[]) { int calc_tot,above90=0, above80=0, above70=0, above60=0,i,j, fail=0; int exam[100][3]; calc_tot=read_file_in_array(exam); for(i=0;i<100;i++) { exam1[i]=exam[100][0]; exam2[i]=exam[100][1]; exam3[i]=exam[100][2]; if(exam[i][j] <=90 && exam[i][j] >=100) { above90++; { if(exam[i][j] <=80 && exam[i][j] >=89) { above80++; { if(exam[i][j] <=70 && exam[i][j] >=79) { above70++; { if(exam[i][j] <=60 && exam[i][j] >=69) { above60++; { if(exam[i][j] >=59) { fail++; } } } } } } } } } } return 0; } int main() { int go,go2,go3; int exam[100][3]; int exam1[100]; int exam2[100]; int exam3[100]; go=read_file_in_array(exam); go2=calculate_total(exam1,exam2,exam3); //go3=display_totals(); cout << go,go2,go3; return 0; }
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 and there must be lots of people that share my pain, so is there a way to automate these changes between files in VS? Bonus points for vim solutions as well.
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't work because copy will call operator* on m2.begin() to "dereference" it and assign a value (all values are of type std::pair<const int, double>). Then it will call operator++ to move to the next space in m2. Both of these operations don't work because of the const in const int and there is no space reserved for any new elements. Is there any way to make it work with std::copy? Thanks!
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 make it fluid. Let me explain. Imagine Microsoft's Surface program where you're able to touch and drag pictures across the screen. Instead of pictures I want them to be sound samples (wavs,mp3,etc). Of course instead the input will be with the mouse but if I ever do finish the project I would totally add touch screen input compatibility! Anyway, I'm guessing there's "physics" to do with it which is why I'm thinking that even though it'll be a 2D application I'll need to code it in a 3D environment. Assuming that I'm correct in how I want to approach my project, where can I start learning about 3D programming? I actually come from PHP programming which will make C++ easier for me to learn. But I don't even know where to start. If I'm not wrong OpenGL is the most up to date API as far as I know. Anyway, please give me your insights guys. I could really use some guidance here since I could totally be wrong in everything that I wrote :) I would like to add that I'm most likely looking for tutorials, Linux 3D programming sites, source/demos (google failed me for the most part). Note: I also understand this is not a project I'll finish in weeks, months and might take years. That's fine, I want to get C++ under my belt however long it takes. I'm just looking for opinions, sources, tutorials and things that might help me (as stated above).
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 several environments for artists to work with graphics, multimedia and code. Try one of them and watch the projects made in each of them on the project's websitees and on Vimeo. I think most of what you want to do is already done, but still can be very inspiring. The environments that come to my mind are: Processing - great prototyping environment by Ben Fry and Casey Reas. I use it always before coding anything serious as it provides me with all the multimedia and communication libraries i need, it's simple like hell and it's Java so you can easli deploy your apps after all! (As far as I remember there is touch surface library for Processing) openFramewoks - same as above but C++, but it's less clean and still under development. It's very easy to prototype in Processing and code finally in openFrameworks as the latter was very much influenced by the former. (The touch surface library is implemented for oF for sure) NodeBox - great and very powerful environment in Python. Has a very strange but great and intuitive (after all) GUI with some very unique methodolody of work!! SuperCollider is a wonderful sound processing and algorythimc composition programming language with a very easy to code GUI library and graphics API. It gives you everything you ever imagined about sound programming functionality. Pure Data - graphical approach toward programming. Made by Miller Puckett (the co-author of Max/MSP) with OpenGL (GEM extension) functionality provided by the guys from IEM in Austria. Final good advice: Books!!! Programming Interaction (O'Reilly), a few books on Processing website, classic work - Computer graphics for Java programmers (great one, really!!). Read as well all the chapters about domain languages and domain knowladge in "97 things every programmer should know". It can really help!! BTW: if you don't concider heavy real-time procedures thing about Java (Java2D, Java3D, JOGL) - it's millions times easier then C++ and Processing is actually Java, so you have a very good prototyping environment that can produce ready to use Java classes and applets. I used Processing in real-time theatre productions where stage movement was controlling the sound (syths and hardware samplers) all made in Processing, so this "heavy real-tme" means HEAVY real-time!! If any further questions about this particular domain programming - don't hesitate to email me.
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(int)<<"\n"; } }; class my_class{ public: static static_class s; static int array[4]; }; #endif In classes.cpp, there is this code: #include "classes.h" int my_class::array[4]={1, 2, 3, 4}; static_class my_class::s = static_class(my_class::array); In main.cpp, there is only simple #include "classes.h" int main () { return 0; } Now, the desired output (from the constructor of static_class) is 4. But what I get is 1. Why is that? edit: A lot of answers suggest that sizeof on pointer returns the size of a pointer. That is not true, AFAIK (from http://msdn.microsoft.com/en-us/library/4s7x1k91(VS.71).aspx - "When the sizeof operator is applied to an array, it yields the total number of bytes in that array, not the size of the pointer represented by the array identifier.") edit2: ok, as I found out, when compiler can see the size, sizeof returns the whole size, but when it decays to a pointer (which is the case here), sizeof actually really returns size of pointer.
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 the array in your function, you should pass it as an argument to the function, or use a container that keeps track of the size for you.
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 compile: #include <map> #include <boost/iterator/transform_iterator.hpp> #include <boost/functional.hpp> typedef std::map<int,double> Map; Map m; m[100] = 2.24; typedef boost::binder2nd< std::multiplies<double> > Function; typedef boost::transform_iterator<Function, Map::value_type*> MultiplyIter; MultiplyIter begin = boost::make_transform_iterator(m.begin(), Function(std::multiplies<double>(), 4)); // now want to similarly create an end iterator // and then iterate over the modified map The error is: error: conversion from 'boost ::transform_iterator< boost::binder2nd<multiplies<double> >, gen_map<int, double>::iterator , boost::use_default, boost::use_default >' to non-scalar type 'boost::transform_iterator< boost::binder2nd<multiplies<double> >, pair<const int, double> * , boost::use_default, boost::use_default >' requested What is gen_map and do I really need it? I adapted the transform_iterator tutorial code from here to write this code ...
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, int i) { return i*p.second; } boost::make_transform_iterator(m.begin(), Function(times, 4));
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 QTextBrowser. Example: QTextBrowser *browser = new QTextBrowser(); QString text; text.append("<html><body>"); text.append("<style type='text/css'>p { margin-bottom:20px; }</style>"); // add the paragraphs here. If the input is plain text convert it to HTML paragraphs first. text.append("<p>Paragraph 1</p>"); text.append("<p>Paragraph 2</b>"); text.append("</body></html>"); browser->setHtml(text);
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 shape overlaps it a bit and that new shape's border is the same as the other one's then floodfill will only partially fill it. Is there a way given a shape's coordinates that I can find the actual bounds for floodfill rather than use a target color? Thanks
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 it, really, it is not hard to make a if that checks if that pixel is or not to be copied) Option 2: Use only basic shapes, that you can fill easily without using floodfill, filling them with horizontal lines with the starting and endpoint being between the two end pixels of each line of the shape. That would be for squares, circles... Option 3: Same as option 2, but allowing arbitrary triangles. Option 4: Same as 3, but allowing you to read a list of points, and compose the object with several rectangles, so you can make any arbitrary shape (even convex ones). That one would be really hard to implement properly (specially convex shapes).
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 for(int j = 0; j < rows; ++j) { // for each expert myscore[k] += delta(i, anotherArray[k][i], arr[j][i]); } } } So I am worried about the array 'arr' and not the other one. I need to make this more cache-friendly and also boost the speed. I was thinking perhaps transposing the array but I wasn't sure how to do that. My implementation turns out to only work for square matrices. How would I make it work for non-square matrices? Also, would mapping the 2D array into a 1D array boost the performance? If so, how would I do that? Finally, any other advice on how else I can optimize this... I've run out of ideas, but I know that arr[j][i] is the place where I need to make changes because I'm accessing columns by columns instead of rows by rows so that is not cache friendly at all. Thanks, Hristo
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++) { arrT[c][r] = arr[r][c]; } } Of course, depending on how you're getting arr[][], you can just fill arrT[][] directly instead. However, there may be a simpler solution of simple swapping the order of the loops. for(int k = 0; k < T; ++k) { // for each trainee myscore[k] = 0; for(int j = 0; j < rows; ++j) { // for each expert for(int i = 0; i < cols; ++i) { // for each sample myscore[k] += delta(i, anotherArray[k][i], arr[j][i]); } } }
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 standard states that "The typedef specifier shall not ... be combined in a decl-specifier-seq with any kind of specifier except a type-specifier." Essentially, it must be a list of type-specifiers, which includes the two cv-qualifiers, const and volatile. C99 defines typedef similarly, except that its list of qualifiers includes restrict. It would seem reasonable to anticipate similar support in typedefs for the nonstandard __restrict... but you never know! A clever and easy way to test this is as follows: extern void link_fail(); typedef int *__restrict restricted_int_p; void test(restricted_int_p a, restricted_int_p b) { *a = 1; *b = 2; if (*a == 2) link_fail(); } This simply exploits the fact that if the unresolved link_fail symbol is found in the object file, the linker will throw an error. If the compiler is properly restricting the two arguments, then it should know the value of a, even after b is changed. Thus, it should strip the entire if block from the generated object file since it will never be run. Note that although GCC supported the restrict syntax since at least version 3.0, it really didn't perform the proper optimizations until version 4.5.
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(string &&) overload should be chosen, because arg needs to be converted to a temporary no matter what, and the temporary matches the rvalue reference better than the lvalue reference. This is not what happens in GCC and MSVC (edit: Thanks Sumant: it doesn't happen in GCC 4.3-4.5). In at least G++ and MSVC, any lvalue does not bind to an rvalue reference argument, even if there is an intermediate temporary created. Indeed, if the const ref overload isn't present, the compilers diagnose an error. However, writing f(arg + 0) or f(std::string(arg)) does choose the rvalue reference overload as you would expect. From my reading of the C++0x standard, it seems like the implicit conversion of a const char * to a string should be considered when considering if f(string &&) is viable, just as when passing a const lvalue ref arguments. Section 13.3 (overload resolution) doesn't differentiate between rvalue refs and const references in too many places. Also, it seems that the rule that prevents lvalues from binding to rvalue references (13.3.3.1.4/3) shouldn't apply if there's an intermediate temporary - after all, it's perfectly safe to move from the temporary. Is this: Me misreading/misunderstand the standard, where the implemented behavior is the intended behavior, and there's some good reason why my example should behave the way it does? A mistake that the compiler vendors have somehow all made? Or a mistake based on common implementation strategies? Or a mistake in e.g. GCC (where this lvalue/rvalue reference binding rule was first implemented), that was copied by other vendors? A defect in the standard, or an unintended consequence, or something that should be clarified? EDIT: I have a follow-on question that is related: C++0x rvalue references - lvalues-rvalue binding
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 shall be an rvalue reference and the initializer expression shall be an rvalue or have a function type. Your case for the call to the std::string && matches none of them, because the initializer is an lvalue. It doesn't get to the place to create a temporary rvalue, because that toplevel bullet already requires an rvalue. Now, overload resolution doesn't directly use reference binding to see whether there exist an implicit conversion sequence. Instead, it says at 13.3.3.1.4/2 When a parameter of reference type is not bound directly to an argument expression, the conversion sequence is the one required to convert the argument expression to the underlying type of the reference according to 13.3.3.1. Thus, overload resolution figures out a winner, even though that winner may actually not be able to bind to that argument. For example: struct B { B(int) { /* ... */ } }; struct A { int bits: 1; }; void f(int&); void f(B); int main() { A a; f(a.bits); } Reference binding at 8.5 forbids bitfields to bind to lvalue references. But overload resolution says that the conversion sequence is the one converting to int, thus succeeding even though when the call is made later, the call is ill-formed. Thus my bitfields example is ill-formed. If it was to choose the B version, it would have succeeded, but needed a user defined conversion. However, there exist two exceptions for that rule. These are Except for an implicit object parameter, for which see 13.3.1, a standard conversion sequence cannot be formed if it requires binding an lvalue reference to non-const to an rvalue or binding an rvalue reference to an lvalue. Thus, the following call is valid: struct B { B(int) { /* ... */ } }; struct A { int bits: 1; }; void f(int&); /* binding an lvalue ref to non-const to rvalue! */ void f(B); int main() { A a; f(1); } And thus, your example calls the const T& version void f(const std::string &); void f(std::string &&); // would bind to lvalue! void g(const char * arg) { f(arg); } However, if you say f(arg + 0), you create an rvalue, and thus the second function is viable.
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 at the sorted part because I can see "here" on the screen but not "it failed." The following error message comes up: Debug Assertion Failed! (a long path here...) Expression: vector emplace iterator outside range For more information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts. I'm not sure what's causing the problem now, since I have a similar line of code elsewhere student.insert(student.begin() + position(temp, student), temp); that does not crash (where position returns an int and temp is another declaration of a struct Student). What can I do to resolve the problem, and how is the first insert different from the second one?
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 function I'm looking at is an utility function to rotate an integer array representing pixel colours an arbitrary number of degrees around an arbitrary centre point. It is placed in my abstract Bullet base class, since only the bullets will be using it and I didn't want the overhead of calling it in some utility class. It's a bit too long and used in every single derived bullet class, making it probably not a good idea to inline. How would you suggest I define this function? As a static member function of Bullet, of a non-static member function of Bullet, or maybe not as a member of Bullet but defined outside of the class in Bullet.h? What are the advantages and disadvantages of each?
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 developer effort if you don't already have such a library. Regarding the original question, if the function doesn't obviously pertain to a particular class, then it should be a free function. At the most, it should belong to a namespace, to control its scope. And even if it pertains to a class, most times, I would still prefer the free function unless the function requires access to private members.
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: typedef int Asub; }; class A { public: typedef int Asub; }; int _tmain(int argc, _TCHAR* argv[]) { C theThing; theThing.DoSomething(C::Asub()); return 0; }
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 C : B<C> { void f() { typedef typename C::Asub Asub; } }; You could work around the problem by either passing the types explicitly upward: template<class T, class Asub> struct B { /* ... */ }; class C : B<C, int> { /* ... */ }; ... or by moving them to some traits class if you need to pass more: template<class T, class Traits> struct B { void DoSomething(typename Traits::Asub it) {} }; struct CTraits { typedef int Asub; }; struct C : B<C, CTraits> { typedef CTraits::Asub Asub; };
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 in function displayGrid(int,Cell ( *)[20]) Member function must be called or its address taken in function Turn(int,int,Cell ( *)[20]) Member function must be called or its address taken in function Turn(int,int,Cell ( *)[20]) Warning: Parameter 'grid' is never used in function displayGrid(int,Cell ( *)[20]) Here is all of my code. I am aware It is much more code than necessary, sorry if it makes it more difficult. I was worried that I might accidentally delete something. const int MAX=20; //Struct Cell holds player and their symbol. class Cell { private: int Player; char Symbol; public: Cell(void); void setPlayer(int); void setSymbol(char); int getPlayer(void); char getSymbol(void); }; Cell::Cell(void) { Symbol ='-'; } void Cell::setPlayer(int player_num) { Player = player_num; } void Cell::setSymbol(char rps) { Symbol = rps; } int Cell::getPlayer(void) { return Player; } char Cell::getSymbol(void) { return Symbol; } void Turn(int, int, Cell[MAX][MAX]); void displayGrid(int, Cell[MAX][MAX]); void main(void) { int size; cout << "How big would you like the grid to be: "; cin >> size; //Checks to see valid grid size while(size>MAX || size<3) { cout << "Grid size must between 20 and 3." << endl; cout << "Please re-enter the grid size: "; cin >> size; } int cnt=1; int full; Cell grid[MAX][MAX]; //I use full to detect when the game is over by squaring size. full = size*size; cout << "Starting a new game." << endl; //Exits loop when cnt reaches full. while(cnt<full+1) { displayGrid(size, grid); //calls function to display grid if(cnt%2==0) //if cnt is even then it's 2nd players turn cout << "Player 2's turn." << endl; else cout << "Player 1's turn" << endl; Turn(size, cnt, grid); //calls Turn do each players turn cnt++; } cout << endl; cout << "Board is full... Game Over" << endl; } void displayGrid(int size, Cell grid[MAX][MAX]) { cout << endl; cout << " "; for(int x=1; x<size+1; x++) // prints first row cout << setw(3) << x; // of numbers. cout << endl; //Nested-For prints the grid. for(int i=1; i<size+1; i++) { cout << setw(2) << i; for(int c=1; c<size+1; c++) { cout << setw(3) << grid[i][c].getSymbol; } cout << endl; } cout << endl; } void Turn(int size, int cnt, Cell grid[MAX][MAX]) { char temp; char choice; int row=0; int column=0; cout << "Enter the Row: "; cin >> row; cout << "Enter the Column: "; cin >> column; //puts what is in the current cell in "temp" temp = grid[row][column].getSymbol; //Checks to see if temp is occupied or not while(temp!='-') { cout << "Cell space is Occupied..." << endl; cout << "Enter the Row: "; cin >> row; cout << "Enter the Column: "; cin >> column; temp = grid[row][column].getSymbol; //exits loop when finally correct } if(cnt%2==0) //if cnt is even then its player 2's turn { cout << "Enter your Symbol R, P, or S (Capitals): "; cin >> choice; grid[row][column].setPlayer(1); in >> choice; } //officially sets choice to grid cell grid[row][column].setSymbol(choice); } else //if cnt is odd then its player 1's turn { cout << "Enter your Symbol r, p, or s (Lower-Case): "; cin >> choice; grid[row][column].setPlayer(2); //checks for valid input by user1 while(choice!= 'r' && choice!='p' && choice!='s') { cout << "Invalid Symbol... Please Re-Enter: "; cin >> choice; } //officially sets choice to grid cell. grid[row][column].setSymbol(choice); } cout << endl; } Thanks alot for your help!
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? } }; Is this the same efficiency as calling x+y directly in Foo::add? In other words, does the compiler typically directly replace fct(x,y) with the actual call, inlining the code, when compiling with optimizations enabled?
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_ ; ... call _ZN3FooI4PlusE3addEii ; ... _ZN3FooI4PlusE3addEii: ; ... call _ZNK4PlusclEii ; ... ZNK4PlusclEii: ; ... ; This is the actual add leal (%edx,%eax), %eax ; ... At -O1 or -O2, Foo and Plus disappear entirely from this test. main: ; ... addl 24(%esp), %eax ; ...
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 forward declaration saying that C is a sub-class of A? Thanks, Gokul.
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 class derives from then you're talking about how the class is structured. You must then show the compiler the class' declaration, there's no other way.
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-copyleft LGPL compatible license like Boost/Mit/3-clause BSD. So I can include it in my library. Note - it is quite hard to extract shared_ptr from boost, at least BCP gives about 324 files...
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 and config directory detail/bad_weak_ptr.hpp detail/interlocked.hpp detail/shared_count.hpp detail/sp_counted_base.hpp detail/sp_counted_base_w32.hpp detail/sp_counted_impl.hpp detail/workaround.hpp and finally, shared_ptr.hpp itself. I don't think weak_ptr and enable_shared_from_this will add a lot of files to that.
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 what's the problem, I cannot just guess and go blind all along the project with this... I checked Window's event log, could not find anything. I checked the settings of throwing errors in Visual Studio, in menu Debug - Exceptions, all of them are checked (including C++ exceptions), so, any errors should be thrown. My code looks something like this: tessnet2.Tesseract tessocr = new tessnet2.Tesseract(); tessocr.Init(@"s:\temp\tessdata", "eng", false); tessocr.GetThresholdedImage(bmp, Rectangle.Empty).Save("s:\\temp\\" + Guid.NewGuid().ToString() + ".bmp"); List<tessnet2.Word> words = ocr.DoOCR(bmp, "eng"); //App exits at this line If I put in my code something like int x = Convert.ToInt32("test"); this should throw an error. And it throws, and Visual Studio shows it. Does anyone having any idea why the errors are not being shown? Or where else could be registered? Any help is very appreciated! Thanks!
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 are converted to their representing attributes at import.
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; } void func(int *a) { cout<<sizeof(a)/sizeof(a[0])<<endl; //a is a pointer to the first elem of array } Then I get 1! So why function does not know the array size?
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 Calculating size of an array!
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 avoid coping the data around.
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 the linker/directories in a C++ IDE. So long question short; could I get a general explanation of terms used to link libraries in C++? I'm using c::b w/ MinGW.
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 archive (.a or .lib) along with all the object files into the binary itself. For linking to dynamic shared objects (.so or .dll), the binary is created with calls to the global offset table and you inform the linker that you wish to link with the shared object and the operating system loader builds the proper image when you run the program. A general explanation of terms used to link libraries in C++ Starting with... translation - This is where the high-level code (in C, Fortran or whatever) is translated into assembly code by translation unit. So, every .cpp file is internally translated to assembly for a specific architecture. assemble - Generates object files from the generated assembly. Object files are almost machine code, but they have a lot of "unresolved externals," which you can kind of think of as pointers to actual function definitions. linking - This takes all your object files and puts them into a coherent binary, be it a dynamic shared object or an executable. You need to tell the linker where it should find all those unresolved externals from the previous stage or they will show up as errors here. Now the binary sits on disk, which is waits until... loader - The operating system loads a binary off of the disk, which contains all the information needed to build the program image. While the details are extremely platform specific, the loader is generally tasked with finding all the shared library references generated by the linker, loading those (recursively, since each DSO can have its own dependencies) and putting them into the memory space of the program.
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 get anything useful. Are there any 3d c++ tutorials you can recommend?
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 make it. All programming is about splitting up complex tasks into tiny simple ones. You need to do the same. Instead of wondering "how do I write a FPS game on iPhone", you need to ask: how do I write any app at all how do I initialize and use OpenGL on iPhone in the first place how do I do 3D rendering in general (not API specific, but how does the math work, how does it work, what do I need to do) ... and so on. There are a million steps on the way that can be solved individually. And at the end of the road, you'll have your game. But there is no tutorial in how to make a FPS game on iPhone for the same reason that there are no tutorials in "how to make a fighter jet" or "how to achieve world peace". People who need to tutorials for it won't be able to do it, and a tutorial would be so big and complex, it'd be pointless. You'll have to learn the hard way: by picking up a book on 3D graphics, learning how to program the iPhone, learning how to use OpenGL, learning how to do everything along the way. By looking up resources explaining that speciifc problem, rather than simply reading the next paragraph of your uber-tutorial.
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 enjoy doing it, the simple applications that I have managed to conjure up put a smile on my face. My plan is to eventually (by eventually I'm talking about 6 years+) go into games programming. I have been informed that C++ is the best way to go about this but haven't got the slightest clue what book/sight is optimal for someone who is still learning the very basics. These are my questions: I have been to the Definitive C++ Book Guide but am still unsure which book is best to start of with. Should I stick with Python or Java instead of moving on to C++? Is there any advice you would give to a beginner programmer? Thanks again for all your help. Edit: The book on Java I am currently using is Programming Video Games for the Evil Genius. Sadly it's riddled with errors and he doesn't go into explaining certain important commands.
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 to play is much more important, in my opinion. I would suggest starting with something like PyGame. Yeah, the C++ guys will tell you that nobody uses PyGame in the real game business, but you don't want to sell your game on XBLA/PSN/WiiWare tomorrow, do you? You'd rather learn how to make one, and therefore it's important that you focus more on the game itself rather than having to deal with pointers and garbage collection. So my suggestions are: - Start small, do a platformer or an adventure game, start to understand the systems behind a 2D world like in Mario or Zelda - Don't be afraid to copy! Even making a Zelda/Metroid/Mario clone will help you a lot, since you'll see that even simple things are often not as simple as they appear - After you've written a couple of 2D games, try to extract the reused parts into a generic engine that you can then use as the base of your projects - Learn to be creative, learn how to draw basic stuff. Creating a game is more then coding. Of course you most likely won't end up as a graphics designer, but understanding what those do will help you later, when you have to work with them
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 proccess like this, any idea? Thanks.
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 source code on my machine directly on the above mentioned server? I am a newbie in this area. Would be great if someone could throw light on the standard practices in this kind of situation. Thanks in advance
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 inside a normal Ubuntu install you can also do inside a Xen-hosted Ubuntu. WRT deploying 9.04-built code onto an 8.04 system, it will often just work, though you can hit problems with library dependencies. One trick that may help mitigate this if you get into problems is to use debootstrap (apt-get it). It allows you to deploy a minimal Ubuntu or Debian version of your choice into a chroot environment. I've never used it, so caveat lector. A more heavyweight, but cleaner, option is to run a VM on your own system (e.g., Sun VirtualBox) and run 8.04 on it for doing release builds.
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 usually warn about bad printf arguments).
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 the rejected library Boost.Singleton There are also some libraries that implements C++ idioms as Boost.Pimpl (on the review schedule), Scope Exit (accepted), Memoizer.
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::Entity(void)" (??0Entity@Parsables@Utility@@QAE@XZ) Entity.obj : error LNK2019: unresolved external symbol "public: virtual __thiscall Utility::Parsables::Base::~Base(void)" (??1Base@Parsables@Utility@@UAE@XZ) referenced in function "public: virtual __thiscall Utility::Parsables::Entity::~Entity(void)" (??1Entity@Parsables@Utility@@UAE@XZ) D:\Programming\Projects\Caffeine\Debug\Caffeine.exe : fatal error LNK1120: 2 unresolved externals I really can't figure out what's going on.. can anyone see what I'm doing wrong? I'm using Visual C++ Express 2008. Here are the files.. "include/Utility/Parsables/Base.hpp" #ifndef CAFFEINE_UTILITY_PARSABLES_BASE_HPP #define CAFFEINE_UTILITY_PARSABLES_BASE_HPP namespace Utility { namespace Parsables { class Base { public: Base( void ); virtual ~Base( void ); }; } } #endif //CAFFEINE_UTILITY_PARSABLES_BASE_HPP "src/Utility/Parsables/Base.cpp" #include "Utility/Parsables/Base.hpp" namespace Utility { namespace Parsables { Base::Base( void ) { } Base::~Base( void ) { } } } "include/Utility/Parsables/Entity.hpp" #ifndef CAFFEINE_UTILITY_PARSABLES_ENTITY_HPP #define CAFFEINE_UTILITY_PARSABLES_ENTITY_HPP #include "Utility/Parsables/Base.hpp" namespace Utility { namespace Parsables { class Entity : public Base { public: Entity( void ); virtual ~Entity( void ); }; } } #endif //CAFFEINE_UTILITY_PARSABLES_ENTITY_HPP "src/Utility/Parsables/Entity.cpp" #include "Utility/Parsables/Entity.hpp" namespace Utility { namespace Parsables { Entity::Entity( void ) { } Entity::~Entity( void ) { } } }
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++ actually requires the function to exist. C++ puts things like virtual table maintenance inside your constructors and destructors, so they must be defined even if you don't need to do anything there -- C++ has to do things in there. Are you sure Base.cpp is being included in the build?
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 the world do we need C++? What makes classes different from a struct?
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 other class-like features: no methods, no constructor, no base classes, etc. Although C++ inherited the keyword, it extended the semantics. (This, however, is why things default to public in structs—a struct written like a C struct behaves like one.) While it's possible to fake some OOP in C—for instance, defining functions which all take a pointer to a struct as their first parameter, or occasionally coercing structs with the same first few fields to be "sub/superclasses"—it's always sort of bolted on, and isn't really part of the language.
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 reference. A simple program that shows the difference between operating on copies and references: #include <iostream> class Foo { public: Foo() { this->value = 0; } Foo get_copy() { return *this; } Foo& get_copy_as_reference() { return *this; } Foo* get_pointer() { return this; } void increment() { this->value++; } void print_value() { std::cout << this->value << std::endl; } private: int value; }; int main() { Foo foo; foo.increment(); foo.print_value(); foo.get_copy().increment(); foo.print_value(); foo.get_copy_as_reference().increment(); foo.print_value(); foo.get_pointer()->increment(); foo.print_value(); return 0; } Output: 1 1 2 3 You can see that when we operate on a copy of our local object, the changes don't persist (because it's a different object entirely), but operating on a reference or pointer does persist the changes.
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 byte sequence used, how could you do it portably? The best method I've come up with is: Write a temporary file in text mode with just '\n' in it, letting the run-time do the translation. Read back the temporary file in binary mode to see the actual bytes. That feels kludgy. Is there a way to do it without temporary files? I tried stringstreams instead, but the run-time doesn't actually translate '\n' in that context (which makes sense). Does the run-time expose this information in some other way?
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 really testing what line separator is used and written out. And is portable, since you are using standard library functions to write and read the file.
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() { *m_data = T(); } Which I've now realised is probably not the best idea... wont work under certain cirumstances, if T has a private assignment operator for example. Is there a normal/better way to do what I'm attempting here?
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 method which is used (among others) by the STL container classes to construct objects. Since placement new only constructs an object without allocating memory, it’s usually an error to call delete to get rid of the memory. Destruction has to happen by calling the destructor directly, without freeing the memory: m_data->~T(); Notice that this syntax for calling the destructor doesn’t work for a constructor call, otherwise we wouldn’t need placement new in the first place. I.e. there’s no m_data->T().
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 here" but not "data fetched" I know this code is messy but can anyone help me figure this out? Thanks //Given an inode return all data of i_block data char* fetchData(iNode tempInode){ char* data; data = new char[tempInode.i_size]; this->currentInodeSize = tempInode.i_size; //Loop through blocks to retrieve data vector<unsigned int> i_blocks; i_blocks.reserve(tempInode.i_blocks); this->currentDataPosition = 0; cout << "currentDataPosition set to 0" << std::endl; cout << "i_blocks:" << tempInode.i_blocks << std::endl; int i = 0; for(i = 0; i < 12; i++){ if(tempInode.i_block[i] == 0) break; i_blocks.push_back(tempInode.i_block[i]); } appendIndirectData(tempInode.i_block[12], &i_blocks); appendDoubleIndirectData(tempInode.i_block[13], &i_blocks); appendTripleIndirectData(tempInode.i_block[14], &i_blocks); //Loop through all the block addresses to get the actual data for(i=0; i < i_blocks.size(); i++){ appendData(i_blocks[i], data); } cout << "done here" << std::endl; return data; } void appendData(int block, char* data){ char* tempBuffer; tempBuffer = new char[this->blockSize]; ifstream file (this->filename, std::ios::binary); int entryLocation = block*this->blockSize; file.seekg (entryLocation, ios::beg); file.read(tempBuffer, this->blockSize); //Append this block to data for(int i=0; i < this->blockSize; i++){ data[this->currentDataPosition] = tempBuffer[i]; this->currentDataPosition++; } data[this->currentDataPosition] = '\0'; } void outputFile(iNode file, string filename){ char* data; cout << "File Transfer Started" << std::endl; data = this->fetchData(file); cout << "data fetched" << std::endl; char *outputFile = (char*)filename.c_str(); ofstream myfile; myfile.open (outputFile,ios::out|ios::binary); int i = 0; for(i=0; i < file.i_size; i++){ myfile << data[i]; } myfile.close(); cout << "File Transfer Completed" << std::endl; return; }
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); bmp = CreateCompatibleBitmap(hdc, 600, 600); SelectObject(MemDC,bmp); g = new Graphics(MemDC); for(int i = 0; i < 1; ++i) { SolidBrush sb(Color(255,255,255)); g->FillRectangle(&sb,rct.top,rct.left,rct.right,rct.bottom); } for(int i = 0; i < 250; ++i) { pts[0].X = 0; pts[0].Y = 0; pts[1].X = 10 + mouse.x * i; pts[1].Y = 0 + mouse.y * i; pts[2].X = 10 * i + mouse.x; pts[2].Y = 10 + mouse.y * i; pts[3].X = 0 + mouse.x; pts[3].Y = (rand() % 600) + mouse.y; Point p1, p2; p1.X = 0; p1.Y = 0; p2.X = 300; p2.Y = 300; g->FillPolygon(&b,pts,4); } BitBlt(hdc,0,0,900,900,MemDC,0,0,SRCCOPY); EndPaint(hWnd, &ps); DeleteObject(bmp); g->ReleaseHDC(MemDC); DeleteDC(MemDC); delete g; break; I'm wondering if I'm doing it right, or if I have areas killing the cpu. Because right now it takes ~ 1sec to render this and I want to be able to have it redraw itself very quickly. Thanks In a real situation would it be better just to figure out the portion of the screen to redraw and only redraw the elements withing bounds of this?
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 all the device contexts, brush handles, and the like as class attributes or static variables. That way when it's WM_PAINT time, all the setup is already done, and you only need to handle the actual drawing.
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 private array
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__ ((aligned(16))) { class B : public C __attribute__ ((aligned(8))) { Which will be alignment for C?
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 know there is no difference in the variables. What is the rationale behind introducing void pointers?
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; (*ptr2) will now interpret the bytes of ptr1 as a float instead of an int, giving you a different result. You can change between types. There are some uses for void*s in pointer-to-function typedefs, as well. In addition, if you have char * ptr1 and do ptr1++, you will increment the address ptr1 refers to by sizeof(char). That's not possible with a void*, it will give you a compiler error saying it doesn't know what size to increment by.
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 assembly code where the code is divided into sections with different titles which end with colon. I am asking you what does that mean, and of what use it can be ?
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.) and then displays it. I'm using Windows, simple GDI for preference and I want to avoid custom libraries just because I want to really understand what I'm doing for this test program. Can anyone help? In any way? A website? Advice? Example code? Thanks
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(input, 0, SEEK_END); size_t size = ftell(input); rewind(input); char *buffer = (char *) malloc(size); if (!buffer) { printf("Out of memory, could not allocate %u bytes\n", size); system("PAUSE"); return 1; } if (fread(buffer, 1, size, input) != size) { printf("Could not read from input file '%s'\n", filename); free(buffer); fclose(input); system("PAUSE"); return 1; } fclose(input); // we loaded the file from disk into memory now for (size_t i = 0; (i + 3) < size; i += 4) { if (buffer[i + 0] == 0xFF && buffer[i + 1] == 0x00 && buffer[i + 2] == 0x00 && buffer[i + 3] == 0x00) { printf("Pixel %i is red\n", (i / 4)); } } free(buffer); Sorry, this is C style, but you can easily change the allocation to C++ style. Personally I like the C way of reading files though. Typically you will want the if statement to check if the pixel is red to be a macro / function. This will make the if statement like "if (compare_4bytes(buffer, 0xFF000000))". Also, this assumes the file loaded consists entirely of raw pixel data. If this is not the case, ie. you read a .bmp / .png / .jpg or something else, you must first load and then convert the file in memory to raw pixel data. This would be done at the comment saying "we loaded the file from disk into memory now". BMP is certainly doable (it's almost raw pixel data already), but most other types need A LOT of work / research. They use often complex compression algorithms. I suggest you'd use a library for this, just for converting it to raw pixel data. Corona is a good (small) one (http://corona.sourceforge.net/), or DevIL (http://openil.sourceforge.net/) or thousand others :)
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 print the string but shouldnt this be printing the address of str. I am not quite getting the difference.
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 question you mentioned made a very good point: Typically, the way that a thread terminates is simply to return from the function that defines the thread. Generally, the main thread signals the worker thread to exit using an event object or a simply an integer or boolean value. If the worker thread is waiting in a WaitForSingleObject, you may need to change it to a WaitForMultipleObjects, where one of the objects is an event. The main thread would call SetEvent and the worker thread would wake up and return. Depending on what you've setup in ACE, you can use interprocess communication from your main thread to your worker threads to tell them to stop, which they would pickup and handle on their next event check. Alternatively, you can use linux's select. Hope this points you in the right direction.
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) { for(j = 0; j < Emax; ++j) { for(i = 0; i+4 < N; i+=4) { 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]); } if (i < N) { for (; i < N; ++i) { if (j >= E[i]) continue; array[k] += foo(i, tr[k][i], ex[j][i]); } } } } I will be running this code in parallel using Intel's TBB so that it takes advantage of multiple cores. After this is finished running, another function prints out what is in array[] and right now, with my unrolling, the output isn't identical. Any help is appreciated. Update: I fixed it. I used the answer for this question to do the unrolling... the output wasn't matching because I wasn't doing array[k] = 0; after the first for loop. Thanks, Hristo
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 not identical a better approach to screening (eliminate branching): array[k] += (j < E[i])*foo(i, tr[k][i], ex[j][i]); also, you need to guarantee N is divisible by 4 otherwise you may overshoot. alternatively, truncate N to be divisible by four (N - N%4)
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_file would redirect the standard input of your debugged program.