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,254,588
2,254,643
CMake not using appropriate output command line argument for compiler
I'm working with CMake, and my program compiles fine with g++. However, I also wish to compiled it with bcc32 and cl. I am running into an issue -- I'm telling cmake to use those compilers by doing a command line somewhat like "cmake -DCMAKE_CXX_COMPILER=cl" or whatnot, and it picks up the compiler correctly (ie, in th...
You must use the -G parameter which defines for which compiler the make files should be generated. Just start cmake --help to see which generators are available. For example, -G "Visual Studio 9 2008" will create makefiles for 32-bit Visual Studio 2008.
2,254,634
2,254,668
Algorithm for finding possible ways of simple, multiple encryption with the alphabet
When using a simple encryption method in which the letters are replaced by the indexing numbers of the alphabet, there are multiple ways of decrypting them, ex. ABOR is 121518 but 121518 could also be AYEAH or LAER. Well I need an algorithm to calculate how many possible ways there are for a given number to decrypt th...
You can do it recursively. The total number of ways of encoding the first n digits is (the number of ways of encoding the first n-1 digits if the last digit is 1 <= d <= 9) + (the number of ways of encoding the first n-2 digits if the last two digits are 10 <= dd <=26). Cache results or use dynamic programming to preve...
2,254,645
2,254,677
Program crash with pointers trying to make strcpy-like
This is my second problem today, pointers are giving me nightmares . I'm trying to make a program that do the same thing that strcpy() function do.. Once i try it..it crashes and i'm 100% sure that's a pointers issue in my code. I think because there is some sort of an unintiallized pointer(*copied) ..But i've assigned...
Well, your mycpy is almost right (although you could've used brackets instead of arithmetic, i.e. a[i] instead of *(a+1)). In order to print the copied string correctly, the last character must be zero, but the last one is not copied by your function. So it should rather be like void mycpy(char *b , char *a) { int ...
2,254,706
2,254,966
How to start developing with OpenGL and C++, what tools do I need to install on windows
I am inspired to start programming some things in OpenGL, using c++. Can anyone list here what tools should be installed to start this process. Ie IDE Compiler OpenGL download etc?
The Ne-He tutorials (to which @wich has already kindly provided a link) are quite good for what they are (but at least the last time I looked carefully, the OpenGL the teach and work with is quite dated). glut, however, I'd generally avoid. It has a fair number of bugs, and nobody's working on fixing them. It was basi...
2,254,909
2,255,054
Boost random number generator
Does anyone have a favorite boost random number generator and can you explain a little on how to implement it into code. I am trying to get the mersenne twister to work and was wondering if anyone had preference towards one of the others.
This code is adapted from the boost manual at http://www.boost.org/doc/libs/1_42_0/libs/random/index.html: #include <iostream> #include "boost/random.hpp" #include "boost/generator_iterator.hpp" using namespace std; int main() { typedef boost::mt19937 RNGType; RNGType rng; boost::uniform_int<> one_to...
2,255,061
2,255,316
Qt Visual Studio 2008 Add-in problem
I have Qt 2009.05 and Qt VS Add-in 1.1.3 installed on my computer with Visual Studio 2008. When I create simple Qt Application and build it, I'm receiveing this error. 1>LINK : fatal error LNK1181: cannot open input file 'qtmain.lib' When I searched whole disk this file to add in Visual Studio library include variable...
Your qt\lib directory should contain all the lib files. You have probably downloaded qt source package but you haven't built it. Download pre-built version for Visual Studio from here.
2,255,164
2,255,231
Help with geometry problem - don't have any idea
I am preparing myself for programming competitions and i would like to know how can i solve this problem. I guess it's geometry problem, and it seems i can't get any ideas about solving it. Here it is: There is a yard in which there are wolves and sheep. In the yard there are also blocks which do not allow to pass. Th...
What you are looking for here is to find the connected components of the graph, then you just need to count the number of wolves and sheep in each one. using namespace std; int w, h; cin >> w >> h; vector<string> grid(h); for (int i = 0; i < h; ++i) cin >> grid[i]; vector< vector<bool> > seen(h, vector<bool>(w, fal...
2,255,171
2,255,259
Is there a way to check which order symbols are loaded into an application in linux?
I know that there is the /proc/proc#/maps file that shows the libraries that are loaded, but is there a way to find out in which order the symbols are loaded?
You can get all sorts of debug information using the LD_DEBUG environment variable. For example: $ LD_DEBUG=files ls This will execute ls and show you the shared libraries as they are loaded. Use LD_DEBUG=help for a list of other options.
2,255,449
2,255,463
C++ Declaring int in the for loop
Haven't used C++ in a while. I've been depending on my Java compiler to do optimization. What's is the most optimized way to do a for loop in C++? Or it is all the same now with moderm compilers? In the 'old days' there was a difference. for (int i=1; i<=100; i++) OR int i; for (i=1; i<=100; i++) OR int i = 1; f...
I'd say that trivial things like this are probably optimized by the compiler, and you shouldn't worry about them. The first option is the most readable, so you should use that. EDIT: Adding what other answers said, there is also the difference that if you declare the variable in the loop initializer, it will stop to ex...
2,255,496
2,255,507
why are special characters read false from file
Hi my program saves some settings (mostly string) to a text file, to retrieve them later, but alas! The special characters come back unrecognizable! saveSettings saves the strings one by one... void email::saveSettings(string filename){ ofstream savefile(filename.c_str(),ios::out | ios::trunc); email settingse...
Maybe you should consider use a unicode version of getline : ) See this article for further info
2,255,608
2,255,639
Force Application to Wait Until WinExec Has Completed
How do I force my application to wait until WinExec has completed?
WinExec is no longer recommended. You can use CreateProcess and WaitForSingleObject as shown in this example on Creating Processes.
2,255,685
2,255,767
How can I read/load images in C++?
i am more a java developer and there is a standard way of reading images : BufferedImage img = null; try { img = ImageIO.read(new File("strawberry.png")); } catch (IOException e) { } but what is the c++ way of loading images? I want to load all images in a specific directory into an array or so.
Personally, I prefer the ImageMagick library. There are many available graphics processing libraries, and there is not a single choice that stands out as clearly superior to the others. My advice is to make a short list of 3 or 4, take a look at the documentation for each, and try to write a simple half-page program w...
2,255,752
2,255,789
How does operator overloading (especially 'new') arity work?
I've never quite understood how the argument lists for operator overloading are determined in a systematic way, and I'm particularly confused by a problem I have now. When you overload a unary operator it has one argument, or zero if it's a class member. When you overload a binary operator it has two arguments, or one...
The arity of an overloaded operator is whatever you declare. For the operators named after symbols (+), if you define them to have extra args, they will only be invoked via an explicit call. (operator +(a, b, c, d, e)). For operator new, you must give it at least one arg, but you may give it as many as you want. Regula...
2,255,841
2,256,489
Iterating & containers of smart pointers
I have a container of smart pointers to mutable objects. I have to write two for_each loops, one for accessing the objects as read-only data and another for mutable data. The compiler is telling me that std::vector< boost::shared_ptr<Object> > is not the same as std::vector< boost::shared_ptr<const Object> >, note th...
What you're doing resembles both the Composite and Visitor patterns. Those two patterns mesh well together, so it seems you are on the right track. To implement the composite pattern, assign the following roles (refer to Composite pattern UML diagram): Leaf -> Field Composite -> Record Component -> Abstract base class...
2,256,086
2,256,103
std::string::replace standard implementation?
In every language that I can think of, except C++, the function Replace essentially replaces all pieces of a string, whereas C++'s string class does not support simple operations like the following: string s = "Hello World"; s = s.Replace("Hello", "Goodbye"); echo s; // Prints "Goodbye World" This seems the most commo...
You're not missing anything, its not in the standard library. You can either write that yourself using find(), replace() etc. or use an implementation like replace_all() from Boosts string algorithm library.
2,256,160
2,256,218
Is it reasonable to use std::basic_string<t> as a contiguous buffer when targeting C++03?
I know that in C++03, technically the std::basic_string template is not required to have contiguous memory. However, I'm curious how many implementations exist for modern compilers that actually take advantage of this freedom. For example, if one wants to use basic_string to receive the results of some C API (like the ...
I'd consider it quite safe to assume that std::string allocates its storage contiguously. At the present time, all known implementations of std::string allocate space contiguously. Moreover, the current draft of C++ 0x (N3000) [Edit: Warning, direct link to large PDF] requires that the space be allocated contiguously ...
2,256,194
2,256,206
Nested statements in sqlite
I'm using the sqlite3 library in c++ to query the database from *.sqlite file. can you write a query statement in sqlite3 like: char* sql = "select name from table id = (select full_name from second_table where column = 4);" The second statement should return an id to complete the query statement with first statement...
Yes you can, just make sure that the nested query doesn't return more than one row. Add a LIMIT 1 to the end of the nested query to fix this. Also make sure that it always returns a row, or else the main query will not work. If you want to match several rows in the nested query, then you can use either IN, like so: cha...
2,256,238
2,257,547
.NET compiler - CLR assembly metadata access / reflection from non-managed C++
I have a compiler that targets the .NET runtime (CLR). The current version of the compiler is written in standard C++ (non-managed). The compiler currently lacks support to reference assemblies at compile time, so the way I "import" .NET libraries is with a utility stub generator that is written in .NET, which reflects...
I think it is done by CoCreateObject() the CLSID_CorMetaDataDispenser coclass, asking for IID_IMetaDataDispenser interface. IMetaDataDispenser::OpenScope() lets you open the assembly metadata. Ask for IID_IMetaDataAssemblyImport, it has a bunch of methods to iterate the metadata. Watch out for .NET 4.0, it's around t...
2,256,351
2,256,355
Why am I getting "undefined reference to `glibtop_init'" during linking?
I'm building a very small C/C++ project using eclipse and i'm getting the following during build: make all Building file: ../Metric.cpp Invoking: GCC C++ Compiler g++ -I/usr/include/glib-2.0 -I/usr/include/libgtop-2.0 -I/usr/lib/glib-2.0/include -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"Metric.d" -MT"Metric.d" ...
Your library file should be libsomething.a and the g++ option -lsomething The manpage of g++ is more specific about this : -l library ... The linker searches a standard list of directories for the library, which is actually a file named liblibrary.a. The linker then uses this file as if it had been specified precise...
2,256,426
2,256,456
Convert collection of T into collection of QVariant in Qt
In Qt, how can I convert a typed collection of objects such as a QList<T> into a QList<QVariant>? I suppose I could construct a new list and copy the elements over, converting each to a QVariant along the way, but is there a shortcut?
Thanks to the Qt IRC chat room. It was staring me right in the face. QList<MyClass> source = ...; QVariant variant = QVariant::fromValue(source); The variant here is a QList<QVariant>.
2,256,444
2,259,428
how to write pthread_create on the same function?
Could someone please help with this? I have the following: // part_1 if (pthread_create(&threadID, NULL, ThreadMain, (void *) clientSocket) != 0) { cerr << "Unable to create thread" << endl; exit(1); } // part_2 void *ThreadMain(void *clientSocket) { pthread_detach(pthread_self()); ... delete (T...
If all you want to do is simply move the function for part2 inside part1, you can create a local class inside of part1, with a static member function... class LocalFunctor { public: static void *ThreadFunc(void* clientSocket) { pthread_detach(pthread_self()); ... delete (TCPSocket *) clientSocke...
2,256,527
2,257,168
how to clear the unneccessary input stream in C++
I would like to make the user input a center number of character, e.g. 10, however, the user might input more than 10. for(int i = 0 ; i< 10 ; i++) cin>>x; The extra character could make my code crash since I will ask for input later. How can I clear the input at this moment when the user input more than 10? Thanks ...
By the way, to avoid duplicating all that code every time, I once wrote a little template function to do that work: template<typename InType> void AcquireInput(std::ostream & Os, std::istream & Is, const std::string & Prompt, const std::string & FailString, InType & Result) { do { Os<<Prompt.c_str(); ...
2,256,647
2,256,705
is it possible in C or C++ to create a function inside another?
Could someone please tell me if this is possible in C or C++? void fun_a(); //int fun_b(); ... main(){ ... fun_a(); ... int fun_b(){ ... } ... } or something similar, as e.g. a class inside a function? thanks for your replies,
Wow, I'm surprised nobody has said yes! Free functions cannot be nested, but functors and classes in general can. void fun_a(); //int fun_b(); ... main(){ ... fun_a(); ... struct { int operator()() { ... } } fun_b; int q = fun_b(); ... } You can give the functor a constructor and pass refere...
2,256,913
2,256,919
Creating a directory In C or C++
How to create a directory with C code (other than the method of forking and using mkdir) ? Is there anything like dirent.h? dirent.h only allows to read directories. (without using external library)
Use the mkdir function. #include <sys/stat.h> #include <sys/types.h> int mkdir(const char *pathname, mode_t mode);
2,256,945
2,256,974
Removing a non empty directory programmatically in C or C++
How to delete a non empty directory in C or C++? Is there any function? rmdir only deletes empty directory. Please provide a way without using any external library. Also tell me how to delete a file in C or C++?
You want to write a function (a recursive function is easiest, but can easily run out of stack space on deep directories) that will enumerate the children of a directory. If you find a child that is a directory, you recurse on that. Otherwise, you delete the files inside. When you are done, the directory is empty an...
2,256,950
19,513,296
OpenSSL Ignore Self-signed certificate error
I'm writing a small program with the OpenSSL library that is suppose to establish a connection with an SSLv3 server. This server dispenses a self-signed certificate, which causes the handshake to fail with this message: "sslv3 alert handshake failure, self signed certificate in certificate chain." Is there a way I can ...
By default OpenSSL walks the certificate chain and tries to verify on each step, SSL_set_verify() does not change that, see tha man page. Quoting it: The actual verification procedure is performed either using the built-in verification procedure or using another application provided verification function set with ...
2,257,464
2,257,524
Google Test and Visual Studio 2010 RC
Has anyone tried to build gtest 1.4.0 under VS 2010 RC? I get about 400 errors when I try to build it. Thanks in advance.
it fails on its own tr1::tuple implementation - adding GTEST_USE_OWN_TR1_TUPLE=0 to my preprocessor defines fixed the problem for me (bugtracker issue).
2,257,614
2,257,676
Why does my RSS grow with stack allocated memory
I have written a small server application. It stores a lot of data in strings. When stresstesting it, RSS memory grows (spotted by $top). I have ran the program through "Instrument" - Mac OS X memory leak applicaton and it find only some minor leaks - the memory leaked was a couple of hundred bytes and the program cont...
Even though your objects are merely stack allocated, the class implementations may allocate memory in the heap. For example, std::string will do this. Allocating and deallocating memory in the heap can lead to fragmentation, which would explain the increased memory usage. See http://en.wikipedia.org/wiki/Malloc#Heap-ba...
2,257,873
2,257,886
Writing to a class pointer gives me an access violation error
Please view this image of the crash after I choose to debug it in MVS2010: http://i48.tinypic.com/dr8q9u.jpg Here's the Game.h header that shows the Game class structure, and in the picture you will see the offending method that's causing the access violation (setBot(botInfo * b)). class botInfo; // Forward declaration...
I don't think there is enough information for me to help. But I will try. You are writing to memory that is not assigned to your program by the operating system -- you need to allocate the memory before you write to it. You should not be passing the this parameter to other functions -- your offset calculations are p...
2,258,115
2,258,193
Templated Vector and Colour Maths library (Specialisation)
I have created a maths library that operates via templates, it allows the user to specify the size and type of the array within a class which is then used to create a maths vector of any dimension up to four. As soon as I went to create a colour class, it struck me how similar the vector and colour class are. Is there ...
Your classes have a fair amount of duplicated code, it is advisable that you do something about it. A possible solution follows. First, you take the common functionality to a base class: template <class Derived, std::size_t N, typename T> class VectorBase { protected: VectorBase() {} // Prevent instantiation of base ...
2,258,239
2,258,253
Trying to use C++ in an iPhone app
I am trying to use c++ in an iphone app. I added the line #include <cstring> in one of my files. I get "error: cstring: no such file or directory". What do I need to do to get it working? My understanding is that gcc is being called, but not g++. How can I change that, or what flag can I add to force gcc to compile ...
Objective-C++ files must have the .mm extension by default in an iPhone app... otherwise it's probably a crazy path setting. Anything weird in the build settings?
2,258,259
2,258,284
Creating a wchar to multibyte char function
The libc library I'm currently using is missing wctomb() so I'm looking to come up with a replacement implementation. What are some complexities I should beware of? Can I simply grab each byte in the wchar and stick them inside an char array?
You might want to pick up a copy of P.J. Plauger's book, "The Standard C Library" - it provides a basic implementation of wctomb() along with a discussion of wide character support in general.
2,258,353
2,258,396
What API/SDK to use for this Windows Application?
I'm going to create a utility with GUI that will run on Windows operating systems. It should require minimum (or zero!) amount of additional libraries, files or DLLs to run because it will be executed from an installer. Because of this, i don't want to use .NET for it will require user to install .NET Framework. I know...
Win32 API is the only way, and of course there are standard API - for sending data over the internet, you could use WinInet.lib/dll, to obtain information about the MAC, you could use the GetAdaptersInfo by using Iphlpapi.lib/dll,(here's a link on how to use it) for the Hard disk serial number you could use GetVolumeIn...
2,258,365
2,258,388
Vector (push_back); g++ -O2; Segmentation fault
I'm having problem with vector, (in the usage of push_back) but it only appears when using additional g++ flag -O2 (I need it). #include <cstdio> #include <vector> typedef std::vector<int> node; typedef std::vector<node> graph; int main() { int n, k, a, b, sum; bool c; graph g(n, node()); c = scanf("%...
I think you have: graph g(n, node()); c = scanf("%i%i", &n, &k); in the reverse order. As it stands, the variable 'n' which you use to size graph is not initialised.
2,258,409
2,259,814
How can I build an application like Thunderbird? Which language should I select?
I don't want to build the Thunderbird functionality. I just want to build a project with plug-in features, cross platform, and easy to install. Is there any document which point to the development of Firefox or Thunderbird? I know the Thunderbird is build in C++, then how can i get these kind of graphics and all other ...
In the spirit of other answers, I feel obliged to point out that Mozilla provides the platform they used to build their applications, including Firefox and Thunderbird, -- see XULRunner. With XULRunner you develop interfaces in XUL (cross-platform UI description language that Firefox and Thunderbird use) or even HTML...
2,258,539
2,258,571
usage of hashtable and map
The hashtable and map is hashtable is implemented as a hash function but map is implemented as a tree. My question is, in what situation, hashtable can not be used but a map is a must?
One motivation for choosing to use a map over a hashtable is the constraints which each one places on the key type used in the template instantiation. As described in the documentation for hash_map in the SGI implementation of STL, an instantiation hash_map requires provision of a functor which hashes K. The STL incl...
2,258,561
2,258,621
getting the length of an array using strlen in g++ compiler
could someone explain why i am getting this error when i am compiling the source using following g++ compiler #include <cstdio> #include <string> using namespace std; int main() { char source_language[50]; scanf("%16s\n",source_language); int length = sizeof(source_language); int sizeofchar = strle...
C++ programmers normally have to deal with at least 2 flavours of string: raw C-style strings, usually declared as char *str; or char str[123];, which can be manipulated with strlen() etc.; and C++-style strings, which have the type std::string and are manipulated with member functions like string::length(). Unfortuna...
2,258,742
2,277,453
How can I get an NPAPI plugin to read an "src" tag
i'm a little stuck on getting a plugin to work. I need it to take a "src" parameter but I can't seem to make it do this. So i've basically got the npsimple basic plugin. It's probably something really silly i'm missing Joe
You should get src as one of the parameters that are passed to NPP_New(): NPError NPP_New (NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char *argn[], char *argv[], NPSavedData *saved) { char* srcValue = 0; for(int i=0; i<argc; ++i) { ...
2,258,834
2,258,996
Combine boost::lexical_cast and std::transform
I would like to write something like this, which cannot be compiled: std::vector<A> as; std::vector<B> bs( as.size() ); std::transform( as.beginn(), as.end(), bs.begin(), boost::lexical_cast<B> ); But this is not working, so I created a functor which is doing this for me: template<typename Dest> struct lexical_transfo...
lexical_cast has two template arguments: target type and source type. Under normal usage, the second is deduced from the call. However, here you want to take the address of the function, and you need to specify all the template arguments: std::transform( as.begin(), as.end(), bs.begin(), boost::lexical_cast<B, A> );
2,258,885
2,259,019
Do other tasks while a system() command is being executed
I have this c++ program that is doing a simple ping on a specified ip address. I am not into networking so i'm just using the system() command in c++ to execute the ping from a shell and store the results in a file, that's easy. The problem is that i want some dots to be printed on the screen while the system() comman...
You need to create a forked process using fork, like this, and using popen to read the input from the output of the command ping google.com and process it accordingly. There is an interesting guide by Beej on understanding the IPC mechanisms which is included in the code sample below... #include <stdio.h> #include <st...
2,258,900
2,259,152
Unexplained out_of_range in string::substr
I have been getting a really annoying error about an std::out_of_range when calling substr. The exact error is terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::substr I'm absolutely sure that tmp_request has a length greater then 1. No matter what I pass to substr—1, 2, o...
I modified your sample slightly to decrease amount of indentation used. There are 5 "test cases" and none causes any problem. Could you please provide a sample request to reproduce the problem you're having. EDIT: Forgot to mention: if this sample as it is (with commented-out bits) doesn't produce that error, your best...
2,259,025
2,259,163
How do I get boost::condition::timed_wait to compile?
I want to wait on a condition for up to 1 second. I've try passing in time_duration: boost::posix_time::time_duration td = boost::posix_time::milliseconds(50); readerThread_cond_.timed_wait(lock, boost::bind(&XXXX::writeCondIsMet, this), td); but I get the error: /usr/include/boost/thread/pthread/condition_variable.h...
I think it's the argument order. As I've never had a problem with timed_wait, I looked at some details at the boost reference to boost.thread, condition_variable_any, timed_wait. What I find most interesting is this: template<typename lock_type,typename duration_type,typename predicate_type> bool timed_wait(lock_type&...
2,259,193
2,259,218
How do I see the output of my code using Visual C++ 2008?
I wrote some very simple code since I'm just starting C++ and I want to get warmed up with the syntax and compiler before our binary tree assignment. #include <iostream> using namespace std; int main(){ cout << "Hello"; return 0; } The only output I'm receiving is: 1> Build started: Project: First-BinaryTree, Conf...
It seems that you have just built the project, without starting it. If you want to start it, you have to go to Debug->Run. However, keep in mind that in that way the executable will be started, it'll run and its window will disappear in some fraction of second, since it does almost nothing. If you want to be able to se...
2,259,321
2,259,328
usleep() function does not allow a loop to continue
#include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(void) { int i=0; while(i<10) { printf("%d", i); usleep(10000); // or sleep(1) i++; } return 0; } I want the program to last 10 secs, i.e. print 1 - wait 1 sec - p...
Your output buffer is not being flushed. By default, output is written when a new line appears in the stream. Change your printf to this: printf("%d\n", i); or try this: printf("%d", i); fflush(stdout); Also, if you want to remove the line-buffering behaviour, you can use setvbuf() and the _IONBUF mode.
2,259,395
2,259,444
How can I convert this C++ function from using long to this other type?
I have this original C++ function called "s": long s(long n) { long sum = 0; long m; m = (long) sqrt(n); for (long i = 2; i < m; i++) if ((n % i) == 0) sum += (i + (n/i)); if (n>1) sum += 1; if ((m*m) == n) sum += m; return sum; } I've been struggling to convert this function over to using the GMP's...
You were mostly on the right track. However, both function parameters should be of type mpz_t. So the header's like: void s(mpz_t n, mpz_t final) You don't need final = sum at the end. Instead, just use final everywhere you use sum. Also, do: mpz_t i; for (mpz_init_set_ui(i, 2); mpz_cmp(i,m) < 0; mpz_add_ui(i, i, 1...
2,259,476
2,259,502
Rotating a point about another point (2D)
I'm trying to make a card game where the cards fan out. Right now to display it Im using the Allegro API which has a function: al_draw_rotated_bitmap(OBJECT_TO_ROTATE,CENTER_X,CENTER_Y,X ,Y,DEGREES_TO_ROTATE_IN_RADIANS); so with this I can make my fan effect easily. The problem is then knowing which card is un...
First subtract the pivot point (cx,cy), then rotate it (counter clock-wise), then add the point again. Untested: POINT rotate_point(float cx,float cy,float angle,POINT p) { float s = sin(angle); float c = cos(angle); // translate point back to origin: p.x -= cx; p.y -= cy; // rotate point float xnew = p...
2,259,544
2,259,615
Is wchar_t needed for unicode support?
Is the wchar_t type required for unicode support? If not then what's the point of this multibyte type? Why would you use wchar_t when you could accomplish the same thing with char?
No. Technically, no. Unicode is a standard that defines code points and it does not require a particular encoding. So, you could use unicode with the UTF-8 encoding and then everything would fit in a one or a short sequence of char objects and it would even still be null-terminated. The problem with UTF-8 and UTF-16 is...
2,259,565
2,259,768
New To Socket Programming, Need Help Understanding How To Connect
I have a C++ Program listening for incoming socket connections on port 2222. I have an Adobe AIR/Flex application that attempts to connect to it, when I click a button. When I Connect To My Socket Over My Intranet, My C++ program hears and accepts the incoming socket connection and Everything Works Fine: var Sock:Socke...
Port forwarding does not mean that you can use an external IP address, your laptop is still on the private 192.168 network. What it means is that when someone tries to connect on 78.18.24.118:2222 the router converts the IP address to 192.168.1.100:2222. This effectively allows you to run a server inside your network b...
2,259,612
2,259,878
"nice" keyword in c++?
So I was doing some simple C++ exercises and I noticed an interesting feat. Boiled down to bare metal one could try out compiling the following code: class nice { public: nice() {} }; int main() { nice n; return 0; }; The result is a compilation error that goes something like this: <file>.cpp: In function ‘...
It is a namespace problem but not with namespace std. The header <iostream> is pulling in <unistd.h> If you try class nice { public: nice() {}; }; int main(int argc, char *argv[]) { nice n; return 0; } there is no problem. Simply add #include <unistd.h> and you will get the "expected ‘;’ before ‘n’...
2,259,678
44,711,819
Easiest way to rotate by 90 degrees an image using OpenCV?
What is the best way (in c/c++) to rotate an IplImage/cv::Mat by 90 degrees? I would assume that there must be something better than transforming it using a matrix, but I can't seem to find anything other than that in the API and online.
As of OpenCV3.2, life just got a bit easier, you can now rotate an image in a single line of code: cv::rotate(image, image, cv::ROTATE_90_CLOCKWISE); For the direction you can choose any of the following: ROTATE_90_CLOCKWISE ROTATE_180 ROTATE_90_COUNTERCLOCKWISE
2,259,697
2,259,708
Huge Amount of Linker Issues with Release Build Only
Anyone have idea on this? Linker errors are way out of my wheelhouse, especially ones like this. Is there any more info I should include? 1>Linking... 1>freeglut_static.lib(freeglut_window.obj) : warning LNK4075: ignoring '/EDITANDCONTINUE' due to '/OPT:ICF' specification 1>LIBCMTD.lib(dbgheap.obj) : error LNK2005: __h...
You seem to be linking projects built with different CRT library settings, one with Multi-Threaded, another one with Multi-Threaded Debug. Adjust the settings for all the projects to use the very same flavour of the library and the issue should go away!
2,259,864
2,259,871
static variable construction in C++
How do compilers know how to correctly handle this code? struct Foo { int bar; Foo() { bar = 3; } Foo& operator=(const Foo& other) { bar = other.bar; return *this; } int SetBar(int newBar) { return bar = newBar; } }; static Foo baz; static Foo ...
The value of someOtherBaz.bar would be 3. Static objects within a translation unit are constructed in the order they appear within the TU (note, there is no defined order of static object in different translation units). First, baz will be constructed with the default constructor. This will set baz.bar to 3. Next s...
2,260,127
2,260,135
Game Programming: .DAT file?
I've seen a lot of games use something similar to a .DAT file or a specific file type that the game has for itself. I'm just beginning with C++ and DirectX and I was interested in keeping my information in something similar to a .DAT. My initial conception was that it would hold information on the files you wanted to s...
I don't think there is really such thing as .dat file format. It's short for "data," and different applications just put in some proprietary stuff in it and call it ".dat." You can read up on fstream classes to do file IO in C++. See Input/Output with files. What you then do is make up your own file format. For example...
2,260,386
2,260,397
Referring to const value at compile time - when is a const's definition really available?
I tried const int i[] = { 1, 2, 3, 4 }; float f[i[3]]; // g++ cries "error: array bound is not an integer constant" int main() { const int j[] = { 0, 1, 2, 3 }; float g[j[3]]; // compiler is happy :) return 0; } What is the difference between the two aggregates? How come referring to a co...
In C++ sizes in array declaration have to be Integral Constant Expressions (ICE). By definition, ICE in C++ cannot include a value taken from an array, regardless of whether it is a const array or not. So, in both cases i[3] and j[3] are not ICEs and cannot be used as sizes in array declarations. For this reason both d...
2,260,861
2,260,893
Strange occurence with string and special character
#include <iostream> #include <string> using namespace std; string mystring1, mystring2, mystring3 = "grové"; int main(){ mystring1 = "grové"; getline( cin, mystring2 ); //Here I type "grové" (without "") cout << "mystring1= " << mystring1 << endl; cout << "mystring2= " << mystring2 << endl; cout << "mystri...
Assuming you use Microsoft Windows: Your source code has a different encoding from that of the windows command line. Type chcp in the command line to see the current console codepage. (Mine is 850) You have three options: Change the codepage/encoding of your source code to the codepage/encoding of your console. Chan...
2,261,026
2,261,101
Distinguish between const and non-const method with same name in boost::bind
When I use boost::bind with a method name which is declared both const and non-const I am getting in ambiguous error, for example boost::bind( &boost::optional<T>::get, _1 ) How can I solve this problem?
The problem together with workarounds is descibed in FAQ part of Boost.Bind reference. You could also make use of utility functions like the following: #include <boost/bind.hpp> #include <boost/optional.hpp> template <class Ret, class Obj> Ret (Obj::* const_getter(Ret (Obj::*p) () const)) () const { return p; } t...
2,261,054
2,261,080
If i develop c++ win32 GUI in xp ,will i have problem to run in it deferent win os's
i need to develop win32 GUI in c++ (plain win32 windows.h thing ) , I'm developing it in xp os how much problem will i have to port it to vista and windows 7 ?
There's a 'define' in Microsoft Visual Studio that allows you to indicate the minimum Windows platform that you want to support. It's WINVER. If you compile with WINVER=0x0501, then you are targetting Windows XP and above. This means that you cannot call e.g. Windows 7 specific functions since they will only be define...
2,261,169
2,261,182
concatenate files without copying their contents
(In C/C++/Linux) Is there a way to concatenate file A and file B (or actually append one A's content to that of B) only by altering the file system without the overhead of data copying? File A then can be discarded. Thanks
If the files were block-structured, and if the OS supported block-structured files (as some do) then (in principle) yes. But as you are asking about Linux, I assume you are talking about a byte-stream oriented file system, where a disk block may not be completely used. In this case, some copying is inevitable and in pr...
2,261,202
2,261,224
Why is scanf results different from user input?
char* ReadNumericFormat = "%i"; int Read(void) { int Storage; __asm { LEA EAX, [Storage] PUSH EAX PUSH DWORD PTR [ReadNumericFormat] CALL DWORD PTR [scanf] ADD ESP, 8 MOV EAX, DWORD PTR [Storage] } } when the user enters "023919" the p...
Actually that's because you've entered an octal number. In C, numbers starting with 0 will be interpreted as octal (base-8) literals. Hence, in your input 023919 scanf find a leading zero without an x following, so assumes it's an octal number. Then it consumes 2 and 3, until 9 which is not a valid octal digit and sto...
2,261,348
2,264,393
Clean way to refactor test code
Background: I currently write test cases for the client side of a network protocol. As part of the tests I have to simulate several different expected and unexpected responses from the server (wrong header, connection lost, unexpected messages, timeouts). Each of these test-cases can be accessed by its unique address. ...
I have had similar problems as you did. The approach I usually take is manage this via a script in order to automate the addition of code to the different places. A comment marks the point for the script to process the file so you don't need to write a complicated parser. Something like: /* automatic code insertion poi...
2,261,351
2,261,565
How to add menubar in my program with Visual Studio 2008?
I managed to create the menubar in the menu editor by clicking and writing text to each menu item i wanted. I cant see any button to get the code to include the menu in my program. How i can get this menu working? C++
depends on whether you are using pure win32 api or MFC. But being a newbie i will first assume that you are using win32 api. do a simple google search for forgers win32 tutorials. just to satisify you, edit the main.cpp file and change the WNDCLASSEX structure, under the lpszMenuName part. See, you just cant keep ...
2,261,366
2,261,396
put different class in hierarchy in one container in C++
Some times we have to put different objects in the same hierarchy in one container. I read some article saying there are some tricks and traps. However, I have no big picture about this question. Actually, this happens a lot in the real word. For example, a parking lot has to contain different types of cars; a zoo has...
The problem with vector<vehicle> is that the object only holds vehicles. The problem with vector<vehicle*> is that you need to allocate and, more importantly, free the pointers appropriately. This might be acceptable, depending on your project, etc... However, one usually uses some kind of smart-ptr in the vector (vect...
2,261,440
2,261,447
Dynamic allocation of memory
Lets consider following two codes First: for (int i=0;i<10000000;i++) { char* tab = new char[500]; delete[] tab; } Second: for (int i=0;i<10000000;i++) { char tab[500]; } The peak memory usage is almost the same, but the second code runs about 20 times faster than the first one. Question Is it because in ...
Is it because in first code array is stored on heap, and in the second one array is stored on stack? Yes, Stack allocation is much faster as all the second code sample is doing is moving (adding/subtracting) the stack pointer rather than manipulating the heap. If you want to know more, these two questions cover the s...
2,261,482
2,261,522
Multithreaded Server Issue
I am writing a server in linux that is supposed to serve an API. Initially, I wanted to make it Multi-threaded on a single port, meaning that I'd have multiple threads working on various request received on a single port. One of my friends told me that it not the way it is supposed to work. He told me that when a req...
What your friend told you is similar to passive FTP - a client tells the server that it needs a connection, the server sends back the port number and the client creates a data connection to that port. But all you wanted to do is a multithreaded server. All you need is one server socket listening and accepting connectio...
2,261,496
2,261,525
How to write Cyrillic text in C++ console
For example, if I write: cout << "Привет!" << endl; //it's hello in Russian In the console it would be something like ╧ЁштхЄ!. OK, I know that we can use: setlocale(LC_ALL, "Russian"); But after that, command line arguments in Russian do not work (if I start my program through a BAT file): StartProgram.bat chcp 1251 ...
See this entry from Michael Kaplan's blog: http://www.siao2.com/2008/03/18/8306597.aspx
2,261,536
2,261,545
how to discover .dlls my application is using
i am trying my hand at using the crystal space api in my graphics applications. crystal space website The applications compile fine but i am having hell with the dlls(dynamic link libraries). The compiled application crashes at run time and i suspect its because of not finding the needed dlls. The only solution i c...
You can use Dependency Walker. Dependency Walker is a free utility that scans any 32-bit or 64-bit Windows module (exe, dll, ocx, sys, etc.) and builds a hierarchical tree diagram of all dependent modules.
2,261,635
2,261,729
Partially truncating a stream (fstream or ofstream) in C++
I am trying to partially truncate (or shorten) an existing file, using fstream. I have tried writing an EOF character, but this seems to do nothing. Any help would be appreciated...
I don't think you can. There are many functions for moving "up and down" the wrapper hierarchy for HANDLE<->int<->FILE *, at least on Windows, but there is no "proper" to extract the FILE * from an iostreams object (if indeed it is even implemented with one). You may find this question to be of assistance. Personally I...
2,261,756
2,261,819
Overloaded operator is never called in C++
I'm writing a math library as a practical exercise. I've run into some problems when overloading the = operator. When I debuged it, I noticed that the call to vertex1 = vertex2 calls the copy constructor instead. In the header file I have: //constructors vector3(); vector3( vector3 &v ); vector3(float ix, float iy, fl...
There are mistakes in your code. Your copy-constructor must take a const&. The reference will avoid making a copy (which you wouldn't be able to do, being the copy-constructor), and it should be const since you're not modifying it: vector3(const vector3&); Temporary variables can be bound to const&, but cannot be boun...
2,261,847
2,262,748
GetRawInputData vs GetAsyncKeyState()
Well, I'm trying to avoid using the deprecated DirectInput. But I need, at each "frame" or "iteration" of the game to snatch ALL KEY STATES so that I can act accordingly. For example, if the player is down on the VK_RIGHT key then he will move just a smidgen right on that frame. The problem with WM_INPUT messages is t...
You can use GetKeyboardState instead. What you generally want is two arrays; one stores the previous frames' input state, and one stores the current. This allows things like differentiating between being held and being triggered. // note, cannot use bool because of specialization std::vector<unsigned char> previous(256...
2,261,848
2,265,617
How to print each function call during execution in WinDbg?
I am debugging an application written in VC++. How do i make WinDbg print the function name and all the values of the arguments to the functions during execution of the debuged process?
Ok, i just found out that it can be done using the "wt" command.
2,261,858
2,262,650
boost::python Export Custom Exception
I am currently writing a C++ extension for Python using Boost.Python. A function in this extension may generate an exception containing information about the error (beyond just a human-readable string describing what happened). I was hoping I could export this exception to Python so I could catch it and do something ...
The solution is to create your exception class like any normal C++ class class MyCPPException : public std::exception {...} The trick is that all boost::python::class_ instances hold a reference to the object's type which is accessible through their ptr() function. You can get this as you register the class with boos...
2,261,897
2,261,908
What library I can use for sending POST and GET requests in C++?
Possible Duplicate: What C++ library should I use to implement a HTTP client? What library I can use for sending POST and GET requests in C++
You can use libcurl or its c++ wrapper curlpp
2,261,917
2,261,926
Which IDE Should I use for C++ on Windows?
Which IDE for C++ should I use on Windows? Is there an IDE with support for editing over SSH on a GNU/Linux server? I have very big C++ project without docs and editing it with text editor very difficult =(
On Windows I prefer: Visual Studio + WinSCP
2,262,011
2,262,395
Adding C++ Object to Objective-C Class
I'm trying to mix C++ and Objective-C, I've made it most of the way but would like to have a single interface class between the Objective-C and C++ code. Therefore I would like to have a persistent C++ object in the ViewController interface. This fails by forbidding the declaration of 'myCppFile' with no type: #import...
You should use opaque pointers and only include C++ headers in the file that implements your Objective-C class. That way you don't force other files that include the header to use Objective-C++: // header: #import <UIKit/UIKit.h> #import "GLView.h" struct Opaque; @interface GLViewController : UIViewController <GLView...
2,262,029
2,262,216
Is there a way to find out whether a class is a direct base of another class?
I'm wondering whether there is a way to find out whether a class is a direct base of another class i.e. in Boost type trait terms a is_direct_base_of function. As far as I can see, Boost doesn't seem to support this kind of functionality, which leads me to think that it's impossible with the current C++ standard. The r...
I asked myself, "What C++ constructs do differentiate between direct inheritance vs. indirect?" It comes to mind that C++ constructors of derived types directly call constructors for their direct base(s) only. So code like this: Derived::Derived() : Base() {} Is only valid if Base is is a direct base of Derived. An...
2,262,232
2,262,268
What does the "c" mean in cout, cin, cerr and clog?
What does the "c" mean in the cout, cin, cerr and clog names? I would say char but I haven't found anything to confirm it.
The "c" stands for "character" because iostreams map values to and from byte (char) representations. [Bjarne Stroustrup's C++ Style and Technique FAQ]
2,262,386
2,458,382
Generate sha256 with OpenSSL and C++
I'm looking to create a hash with sha256 using openssl and C++. I know there's a similar post at Generate SHA hash in C++ using OpenSSL library, but I'm looking to specifically create sha256. UPDATE: Seems to be a problem with the include paths. It can't find any OpenSSL functions even though I included #include "ope...
Here's how I did it: void sha256_hash_string (unsigned char hash[SHA256_DIGEST_LENGTH], char outputBuffer[65]) { int i = 0; for(i = 0; i < SHA256_DIGEST_LENGTH; i++) { sprintf(outputBuffer + (i * 2), "%02x", hash[i]); } outputBuffer[64] = 0; } void sha256_string(char *string, char output...
2,262,574
2,262,614
Pass by reference impossible?
I'm trying to use a for_each loop in my code, but I'm getting the following error: cannot convert parameter 1 from 'std::pair<_Ty1,_Ty2>' to 'std::pair<_Ty1,_Ty2> &' here's the offending code: typedef stdext::hash_map< std::string, std::list<DefaultTestContext> > CompleteTestList; static void RunMappedTes...
std::map<T1, T2>::value_type is std::pair<const T1, T2>. Change the parameter of RunMappedTests to pair<const string, list<DefaultTestContext>> &.
2,262,628
2,262,694
Changing background of text in edit control
Can you change the background of text in area of edit control that would stay static?
In the parent of the edit control, handle the WM_CTLCOLORSTATIC message, the wParam of this message is the HDC that the Edit control is about to draw with, for most CTLCOLOR messages, if you set text and background colors into this DC, the control will use the colors you set. You can also return an HBRUSH and the con...
2,262,652
2,264,425
binding to member variables
The following example from boost bind does not work for me: #include <boost/bind.hpp> struct A { int data; }; int main() { A a; boost::bind(&A::data, _1)(a) = 1; } error: assignment of read-only location 'boost::bind [with A1 = boost::arg<1>, M = int, T = A](&A::data, (<unnamed>::_1, boost::arg<1>())).bo...
UncleBens' solution is fine but I thought I'd add that if you use Boost.Lambda the problem disappears: #include <boost/lambda/bind.hpp> struct A { int data; }; int main() { namespace bll = boost::lambda; A a; bll::bind(&A::data, bll::_1)(a) = 1; } And so it does if you use boost::mem_fn: #include <...
2,262,689
2,262,719
Faster method for exporting embedded data
For some reasons, i'm using the method described here: http://geekswithblogs.net/TechTwaddle/archive/2009/10/16/how-to-embed-an-exe-inside-another-exe-as-a.aspx It starts off from the first byte of the embedded file and goes through 4.234.925 bytes one by one! It takes approximately 40 seconds to finish. Is there any o...
Once you know the location and size of the embedded exe , then you can do it in one write. LPBYTE pbExtract; // the pointer to the data to extract UINT cbExtract; // the size of the data to extract. HANDLE hf; hf = CreateFile("filename.exe", // file name GENERIC_WRITE, // open for ...
2,262,883
2,263,046
URLDownloadToFile API, how can it be used asynchronously?
How can this API URLDownloadToFile be used asynchronously? I need to show the progress of the download via SendMessage to a client window, which can't be done as the API appears to be synchronous and it never sends the OnProgress until the download completes. I have also seen some example codes involving IMoniker inter...
Use URLOpenPullStream instead.
2,262,984
2,264,101
Graphics Gems IV. Binary Image Thinning Using Neigborhood Maps
What does this expression's algorithm mean? p = ((p<<1)&0666) | ((q<<3)&0110) | (Image->scanLine(y+1)[x+1] != 0); Algorithm "Binary Image Thinning Using Neigborhood Maps" in a book "Graphics Gems IV": static int masks[] = {0200, 0002, 0040, 0010}; uchar delete_[512] = { 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, ...
(See commented source code) The variables m, p, q, and elements of the qb array are 9-bit numbers that represent the 3x3-pixel "neighborhood" of a pixel. Suppose your image looks like this (each letter represents a pixel, which is either 'on' or 'off' (1 or 0, black or white): ---x--- 0123456 | 0 abcdefg | 1 hi...
2,263,145
2,263,157
.Net-like IntelliSense for VC++?
Up until now in VC++, when I want to see everything I do :: . This shows all of my objects. Is there a way to make it like c# so it checks as you type without needing :: . Thanks
I don't know of a free way to do this, but you could check out Visual Assist.
2,263,154
2,263,172
"using typedef-name ... as class" on a forward declaration
I'm doing some policy-based designs here and I have the need to typedef lots of template types to shorten the names. Now the problem comes that when I need to use a pointer to one of those types I try to just forward-declare it but the compiler complains with a test.cpp:8: error: using typedef-name ‘Test1’ after ‘class...
That's correct. A typedef-name cannot be used in such a forward declaration (this is technically called an elaborated type specifier, and if such a specifier resolves to a typedef-name, the program is ill-formed). I don't understand why you actually need the forward declaration in the first place. Because if you alrea...
2,263,193
2,263,213
How to extract the Windows OEM Key from Windows
How would I go about extracting the Windows OEM Key from the Registry and saving it to a file.
You're well into unsupported territory here. The product key is stored in encrypted form in the registry. You might want to look at Magical Jellybean Keyfinder's code, which is available under the GPL.
2,263,249
2,263,316
Shatter Glass desktop Win32 effect for windows?
I would like a win32 program that takes the desktop and acts like it is shattering glass and in the end would put the pieces back together is there way reference on Doing this kind of effect with C++?
I wrote a program (unfortunately now lost) to do something like this a few years ago. The desktop image can be retrieved by creating a DC for the screen, creating a compatible bitmap, then using BitBlt to copy the screen contents into the bitmap. Then use GetDIBits to get the pixels from this bitmap in a known format. ...
2,263,474
2,264,742
Can I write Windows drivers with Delphi 2010?
I've always heard that Delphi can do almost anything C++ can do...except write Windows drivers. Is this correct, and if so, why is that? I recently read a blog post online that may indicate a possible solution for writing drivers with Delphi, but it's 3 years old and I don't know how accurate this information is. So, ...
It may be technically possible to write some drivers with Delphi, but as far as a general answer goes, I'd say: you can't easily write drivers with Delphi. First, there's a difference between user-mode driver (UMDF) drivers and kernel-mode (KMDF) drivers. UMDF drivers should be possible with Delphi. KMDF drivers aren't...
2,263,514
2,263,545
How to get keyboard input in an Homemade OS?
How to get keyboard input in an Homemade OS?
Given that no further explanations are given, I'll assume a x86 platform. You need to install a handler for the keyboard interrupt. Here is an example as a Linux module that you can probably get inspiration from: http://tldp.org/LDP/lkmpg/2.4/html/x1210.html And also: http://wiki.osdev.org/Interrupts If you give more d...
2,263,643
2,263,664
How to get the cursor point in a Window instead of whole desktop?
How to get the cursor point in a Window instead of whole desktop?
In Win32 you use ScreenToClient or MapWindowPoints to convert from system coordinates to window coordinates
2,263,681
2,263,700
c++ compile error: ISO C++ forbids comparison between pointer and integer
I am trying an example from Bjarne Stroustrup's C++ book, third edition. While implementing a rather simple function, I get the following compile time error: error: ISO C++ forbids comparison between pointer and integer What could be causing this? Here is the code. The error is in the if line: #include <iostream> #inc...
You have two ways to fix this. The preferred way is to use: string answer; (instead of char). The other possible way to fix it is: if (answer == 'y') ... (note single quotes instead of double, representing a char constant).
2,263,690
2,263,733
What claims, if any, can be made about the accuracy/precision of floating-point calculations?
I'm working on an application that does a lot of floating-point calculations. We use VC++ on Intel x86 with double precision floating-point values. We make claims that our calculations are accurate to n decimal digits (right now 7, but trying to claim 15). We go to a lot of effort of validating our results against ot...
Unless your code uses only the basic operations specified in IEEE 754 (+, -, *, / and square root), you do not even know how much precision loss each call to library functions outside your control (trigonometric functions, exp/log, ...) introduce. Functions outside the basic 5 are not guaranteed to be, and are usually ...
2,263,960
2,264,064
Errors thrown from stl when compiling a module which uses the "Meschach" library
I'm working on a module which uses a shared library, which in turn has a static library linked to it. The shared library build works fine and generates a .so. When I try to use it in the module, I get a variety of errors, most of which are based on stl (stl collections to be specific), at the compilation stage. The err...
Doing some googling it seems like the Meschach library has a macro called catch (defined err.h indirectly included by matrix2.h) causing c++ code having exception catching to fail. Try #undef catch after you are done including the meschach headers and see if works better.
2,264,137
2,264,224
Unwind a function call
This is a difficult problem to describe so please let me know if anything is unclear. I am trying to solve a possible deadlock situation in my C++ app and I am having trouble visualizing an appropriate solution. The restrictions placed on me by the two libraries I am trying to connect make my problem very complex and ...
If you're destroying the timer handler, I figure you're exiting the program. Before you try to exit and begin killing the timers, can you set a flag to prevent Action 1 and have Thread 1 terminate itself? I hope I'm reading your diagram right, because it doesn't exactly match with the text...
2,264,486
2,264,512
Is down-casting 'this' to a derived class is correct?
Have a class Hero. Sometimes I need a deep copy (when all members are copied by value) of this class as a kind of some derived class: class Hero { public: // members, w/o getters/setters public: // Constructors Hero(); Hero(...) ~Hero(); inline SuperHero* asSuper...
Why not just have the derived class's constructor use the base class's copy constructor? eg: class SuperHero : public Hero { ... SuperHero(const Hero &hero) : Hero(hero) { } ... };
2,264,565
2,264,636
Debugging in Linux using core dumps
What are the 'best practices' when it comes to debugging core dumps using GDB? Currently, I am facing a problem: The release version of my application is compiled without the '-g' compiler flag. The debug version of my application (compiled with '-g') is archived (along with the source code, and a copy of the release ...
It sounds like there are other differences between your release and debug build then simply the absence/presence of the -g flag. Assuming that's the case, there is nothing you can do right now, but you can adjust your build to handle this better: Here's what we do at my place of work. Include the -g flag when buildin...
2,264,588
2,264,901
Vim search for class
How do I define a vim function such that when called with Foo it searches via vimgrep for \s*class Foo or \s*struct Foo ? [This is poorman's cscope/ctag; I want to be able to type in a class name, and have it search for the class.] If this is easy, is there a way I can tell it to look under my cursor to use that 'wo...
Here's a hack from a vim novice which seems to work: function! SearchFunc() let l:filenames = substitute(glob("*.c") . glob("*.cpp") . glob("*.h"), '\n', ' ', 'g') try execute 'vimgrep /^\s*\(struct\|class\)\s*' . expand("<cword>") . '/ ' . l:filenames catch echon 'No results found.' sleep 800m end...
2,264,615
2,264,648
how to search properly the vector for a value
The problem I have, I have to add to a vector, the missing chars. For example I have initially s,a,p,i,e,n,t,i,a and I have to add missing chars to it s,a,p,i,e,n,t,i,a,b,c,d ... I am trying to use this code to search for an existing value. for(char c='a';c!='z';++c) { if (vec.end()!=find(vec.begin(),vec.en...
Nope, end() is not the last element of the vector but past it. To iterate over all elements you normally do for(it= vec.begin(); it!= vec.end(); it++) ... So whatever your problem is, this is ok.
2,264,637
2,264,845
Using Intel Threading Building Blocks (TBB) in Linux
I want to use Intel Threading Building Blocks (TBB) in Linux. Can anyone suggest a good IDE for that and possibly any steps to integrate TBB with that IDE? Thanks, Rakesh.
As long as I know TBB is a set of C++ libraries which purpose to handle task of parallelization of code. So there is no need in any integration(exactly as you using STL) and you can use whatever IDE you wish, e.i. Eclipse, KDevelop and more.
2,264,760
2,264,768
Efficient way of finding distance between two 3D points
I am writing a code in C++ and want to compute distance between two points. Question 1: I have two points P(x1, y1, z1) and Q(x2, y2, z2) , where x, y and z are floats/doubles. I want to find the distance between these two points. One way to do it is : square_root(x_diffx_diff + y_diffy_diff + z_diff*z_diff) But t...
Do you need the actual distance? You could use the distance squared to determine if they are the same, and for many other purposes. (saves on the sqrt operation)