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
1,681,564
1,681,670
c++ problem with build
I have this method declaration in Util.h file 30:string to_string(const bit_vector& v); Util.cc file has the definition string to_string(const bit_vector& v){ string str = ""; for (bit_vector::const_iterator i = v.begin(); i < v.end(); ++i){ if(*i == 1) str += "1"; else str += "0"; } return str; } wh...
It seems bit_vector is not defined. There are claims that it should be included in <vector>, but that doesn't seem to be the case on Visual Studio 2008. Try typedef vector<bool> bit_vector; before the first usage of bit_vector.
1,681,637
1,690,991
COleDataSource/COleDropTarget cancel drag&drop operation
I have implemented my custom drag&drop by deriving from COleDataSource and COleDropTarget. Everythings work fine but I have an scenario that makes the application crashes. That happens when the dialog where the drag&drop controls are placed is destroyed while the user is in the middle of a drag&drop operation. This is ...
I'm not sure if this would work but you could try overriding the QueryContinueDrag method of the COleDropTarget instance and returning DRAGDROP_S_CANCEL in the case where the dialog has been closed
1,681,677
1,681,742
MSBuild / Visual Studio distributed builds
I develop / maintain an application that takes a long time to build (as in, a full build takes in excess of six hours!). After having spent most of the day building our application I've started looking into ways of improving build time. The suggestions on this Stack Overflow question were: Fixing compile warnings Unit...
Go have a look at http://www.xoreax.com/ for Incredibuild. It is not free, but we use it and it's pretty impressive. It is well integrated into Visual Studio and extremely simple to use. You can run into a problem every now and then, but it's definitely worth a look. Once it's installed, in Visual Studio, the principle...
1,681,748
1,688,417
Oracle 7 ProC++ pre-compiled code
I am modifying an old DLL which uses Oracle 7 ProC++ precompiled code (SQLLIB18.LIB) and don't have any documentation for this release. No joy back from Oracle either. Does anyone know what the numbers in the following compilation unit data represent? static const short sqlcud0[] = {8,4130,2,0,0,1,189,0,6,49,0,11,11,0,...
Unfortunately, I believe this is code produced by the Oracle ProC precompiler, and is not likely to be documented for the general public, even if you have the entire set of manuals. I did find a link to V7.3.4 documentation on Oracle's website. I don't suppose you still have the original ProC source code?
1,681,900
1,682,492
OpenMP: Causes for heap corruption, anyone?
EDIT: I can run the same program twice, simultaneously without any problem - how can I duplicate this with OpenMP or with some other method? This is the basic framework of the problem. //Defined elsewhere class SomeClass { public: void Function() { // Allocate some memory float *Data; Data = new float[1...
Check out MemAllocFunctionInDLL, FunctionDefinedInDLL, MemDeallocFunctionInDLL are thread-safe, or re-entrant. In other words, do these functions static variables or shared variables? In such case, you need to make it sure these variables are not corrupted by other threads. The fact without omp-for is fine could mean y...
1,681,903
1,698,474
Submitting QSqlRecord to MySQL database in Qt
I want to access a MySQL database and I want to read+write data from+to the database within my Qt/C++ program. For the read write process, I try to use QSqlTableModel, QSqlTableRcord and QSqlDatabase as this is a very pleasant approach without too much of SQL commands which I dislike for the one or other reason (to han...
Your QSqlRecord doesn't have any fields defined. You need to add rec.append(QSqlField("x", QVariant::Double)); rec.append(QSqlField("y", QVariant::Double)); rec.append(QSqlField("img", QVariant::Image)); before you set the values
1,681,964
1,682,019
Explicit Address Manipulation in C++
Please check out the following func and its output void main() { Distance d1; d1.setFeet(256); d1.setInches(2.2); char *p=(char *)&d1; *p=1; cout<< d1.getFeet()<< " "<< d1.getInches()<< endl; } The class Distance gets its values thru setFeet and setInches, passing int and float arguments res...
This is a really bad idea: char *p=(char *)&d1; *p=1; Your code should never make assumptions about the internal structure of the class. If your class had any virtual functions, for example, that code would cause a crash when you called them. I can only conclude that your Distance class looks like this: class Distanc...
1,682,844
1,682,885
Templates: template function not playing well with class's template member function
This is a minimal test case of some code that I actually have. It fails when it tries to evaluate a.getResult<B>(): test.cpp: In function 'void printStuff(const A&)': test.cpp:6: error: expected primary-expression before '>' token test.cpp:6: error: expected primary-expression before ')' token The code is: #include <i...
When you refer to a template that is a member of dependent type, you have to prepend it with a keyword template. This is how the call to getResult inside printStuff should look size_t value = a.template getResult<B>(); This is similar to using the keyword typename when referring to nested typenames in a dependent type...
1,683,051
1,683,917
FILE * and istream: connect the two?
Suppose I "popen" an executable, I get a FILE* in return. Furthermore, suppose I'd like to "connect" this file to an istream object for easier processing, is there a way to do this?
There is no standard way but if you want a quick solution you can get the file descriptor with fileno() and then use Josuttis' fdstream. There may be similar efforts around but I used this in the distant past and it worked fine. If nothing else it should be a very good map to implementing your own.
1,683,081
1,844,929
What's the most efficient way to do recursive XPath queries using libxml2?
I've written a C++ wrapper function for libxml2 that makes it easy for me to do queries on an XML document: bool XPathQuery( const std::string& doc, const std::string& query, XPathResults& results); But I have a problem: I need to be able to do another XPath query on the results of my first query. Current...
You should reuse the xmlXPathContext and just change its node member. #include <stdio.h> #include <libxml/xpath.h> #include <libxml/xmlerror.h> static xmlChar buffer[] = "<?xml version=\"1.0\"?>\n<foo><bar><baz/></bar></foo>\n"; int main() { const char *expr = "/foo"; xmlDocPtr document = xmlReadDoc(buffer,NULL...
1,683,162
1,683,233
Best way to port MFC COM Server to Managed code
I am working on an application suite comprising of multiple Automation servers written using MFC and this is legacy code. These apps inter communicate via COM interfaces and other events. Most of these apps provide multiple form views with various input controls to capture information. I was wondering what would be the...
You could write new parts of server using C++/CLI. It looks like a less painful option.
1,683,241
1,683,288
Iterating over subsets of any size
I can iterate over the subsets of size 1 for( int a = 0; a < size; a++ ) { or subsets of size 2 for( int a1 = 0; a1 < size; a1++ ) { for( int a2 = a1+1; a2 < size; a2++ ) { or 3 for( int a1 = 0; a1 < size; a1++ ) { for( int a2 = a1+1; a2 < size; a2++ ) { for( int a3 = a2+1; a3 < size; a3++ ) { But how to do t...
You can use recursion: void iterate(int *a, int i, int size, int n) { for(a[i] = 0; a[i] < size; a[i]++) { if(i == n-1) DoStuff(a, n); // a is the array of indices of size n else iterate(a, i+1, size, n); } } ... // Equivalent to 4 nested for loops int a[4]; iterate(...
1,683,263
1,683,401
Convert std::vector<char*> to a c-style argument vector arv
I would like to prepare an old-school argument vector (argv) to use within the function int execve(const char *filename, char *const argv[],char *const envp[]); I tried it with the stl::vector class: std::string arguments = std::string("arg1"); std::vector<char*> argv; char argument[128]; strcpy(argument, arg...
I think the char[128] is redundant as the string local will have the same lifetime, also, try adding the program as argv[0] like rossoft said in his answer: const std::string arguments("arg1"); std::vector<const char*> argv; argv.push_back("bashscriptXY"); // The string will live as long as a locally allocated cha...
1,683,367
1,683,377
How to make two arrays into a function in c++?
I have two string arrays "Array1[size]" and "Array2[size]". They both have the same size. I would like to write a function which contains this two arrays but I am having problems in the way that I am declaring them. I am declaring it like this: void Thefunction (string& Array1[], string& Array2[], int size); And wh...
You're declaring a function which takes arrays of string references. You almost certainly want to take arrays of strings. Like this: void TheFunction(string Array1[], string Array2[], int size);
1,683,540
1,684,836
HttpSendRequest blocking when more than two downloads are already in progress
In our program, a new thread is created each time an HTTP request needs to be made, and there can be several running simultaneously. The problem I am having is that if I've got two threads already running, where they are looping on reading from InternetReadFile() after having called HttpSendRequest(), any subsequent a...
The HTTP 1.1 standard mandates a maximum of 2 simultaneous connections per server. If you have IE5, IE6, or IE7 installed, the versions of WinInet they install allow you to use InternetSetOption() to increase the limit (look at INTERNET_OPTION_MAX_CONNS_PER_SERVER and INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER options)....
1,683,665
1,684,009
Where is Boost.Process?
I need to execute a program and retrieve its stdout output in c++. I'd like my code to be cross-platform too. Having recently discovered the wonderful world of the Boost c++ libraries for all your cross platform needs, I figured I'd just go to boost.org and read up on the documentation of Boost.Process. Much to my surp...
Julio M. Merino Vidal, who is, I beleive, the original author, wrote in this 2007 post that he did not have time to complete it. Development was taken over by Boris Schaeling. This is the version that you found at http://www.highscore.de/boost/process/. According to this post, he is still actively developing it. There ...
1,683,952
1,683,970
C++ compilation error using string and istream_iterator
When trying to compile the following: #include <string> #include <iterator> #include <iostream> using namespace std; int main() { string s(istream_iterator<char>(cin), istream_iterator<char>()); return s.size(); } g++ 4.4.1 gives me: main.cc: In function ‘int main()’: main.cc:6: error: request for member ‘size’ in...
You're accidentally declaring a function instead of instantiating a string. Try declaring variables for your istream_iterator objects and then passing those to the std::string constructor. And here's a good read that describes exactly your problem: http://www.gotw.ca/gotw/075.htm
1,684,004
1,684,521
Heap fragmentation and windows memory manager
I'm having trouble with memory fragmentation in my program and not being able to allocate very large memory blocks after a while. I've read the related posts on this forum - mainly this one. And I still have some questions. I've been using a memory space profiler to get a picture of the memory. I wrote a 1 line prog...
First, thank you for using my tool. I hope you find it useful and feel free to submit feature requests or contributions. Typically, thin slices at fixed points in the address space are caused by linked dlls loading at their preferred address. The ones that load high up in the address space tend to be Microsoft operatin...
1,684,418
1,684,439
Why does the map size returns 0
using namespace std; class A { public: A() {} ~A() {} map<int, string*>& getMap() { return mapStr; } void setMap(const map<int,string*> m) { mapStr = m; } private: map <int, string*> mapStr; }; class B { ...
Your getA method is returning a temporary copy of a, so your call to setMap is modifying that copy, not the original. One way to fix this would be to have getA return a reference or pointer to a
1,684,542
1,684,562
C++ compiler - resolving name of a class member
When the compiler sees this code: SomeClass foo; int x = foo.bar; What is the process it goes about in retrieving the value of bar? I.e. does it look at some data structure representing the class definition? If so is this data structure generated at compile time or runtime?
The process starts when the compiler sees the definition for SomeClass. Based on that definition, it builds an internal structure that contains the types of the fields in SomeClass, and the locations of the code for the methods of SomeClass. When you write SomeClass foo; the compiler finds the code that corresponds to ...
1,684,638
1,684,670
a very simple c++ oop question
im struggling with syntax here: hopefully this question is v simple, im just miising the point. specifically, if i nest a class within another class, so for instance class a { a //the constructor { b an_instance_of_b // an instance of class b } }; class b { public: foo() { cou...
Your an_instance_of_b is not a member of a, but a local variable in the constructor of a (and the constructor declaration is missing the parenthesis). What will happen here is that when you create an instance of a, it creates and immediately destroys an instance of b, then it leaves the constructor for a and the a inst...
1,684,815
1,684,845
Expected constructor, destructor, or type conversion before '=' token
I have some extern'd variables in a namespace in a header file, and I'm trying to initialize them in its corresponding cpp file. However, I keep getting the error given in the topic title. I'm not sure what the problem is. EX: // Some header namespace foo { extern SDL_Surface* bar; } // In the impl file #include "...
At the file level, you can only define types (you've only written an assignment expression). So you need to change that to: SDL_Surface* foo::bar = 0;
1,684,817
1,684,831
c++: what exactly does &rand do?
This is an excerpt of some c++ code, that i'll have to explain in detail in some days: std::vector<int> vct(8, 5); std::generate(vct.begin(), vct.end(), &rand); std::copy(vct.rbegin(), vct.rend(), std::ostream_iterator<int>(std::cout, "\n")); i think i understand everything about it, except that tiny mystical &r...
The & in &rand returns the address of the rand() function. You're passing a function pointer to generate() so generate() can call rand() to generate random numbers.
1,684,821
1,692,323
is there a flag "M_FAST" in FreeBSD kernel for Malloc Call?
if you know there is one, can you let me know what its for ? if not please say so : ) thanks. Signature : void * malloc(unsigned long size, struct malloc_type type, int flags); for example. other flags are... M_ZERO Causes the allocated memory to be set to all zeros. M_WAITOK Indicates that it i...
M_FAST is not a flag, below. The answer was always there in the question I posted :P It is a malloc_type type argument, which is used to perform statistics on the memory allocation. For more information refer to the documentation from FreeBSD below, (where, M_FOOBUF = M_FAST) The type argument is used to perform statis...
1,684,941
1,686,584
Need a little help with the Qt painting classes
I'm trying to write a paint program (paint where ever a mouse press/hold is detected), but I'm having trouble using the Qt QPainter. I have read the documentation on their web site and I'm still kind of lost. A link to a tutorial that isn't on their web site would be nice or maybe explain to me how I can accomplish thi...
Check the Scribble example that comes with Qt, it does exactly what you want. We reimplement the mouse event handlers to implement drawing, the paint event handler to update the application and the resize event handler to optimize the application's appearance. In addition we reimplement the close event han...
1,684,975
1,685,124
Strange segmentation fault C++ in _vfprintf_r()
Someone please see my code at this link for input taken from 2.2 mb file. This produces seg fault. By gdb, it shows seg fault in _vfprintf_r(). But when I comment line 41 and uncomment 38 (a null statement), there is no segmentation fault. line no 41 is just print statement. The output is written into result.txt file.
You have a stack overflow. That's right, a Stack Overflow. I was able to reproduce by doing ulimit -s 1024. You need to not recurse so deeply, or you need to increase your stack size.
1,684,978
1,685,011
Which one is preferred, return const double& OR return double
Given the following scenario, which one of the following is preferred. m_state is a member rater than a local variable. class C { private: double m_state; public: double state() const { return m_state; } // returns double double& state() { return m_state; } } =========================================== cla...
I wouldn't do this: double& state() { return m_state; } You may as well make m_state public if you did that. Probably what makes the most sense is: const double & state() const { return m_state; } Then again, when you're talking about saving the copy of a 64 bit variable (ie micro-optimization) and the fact that the ...
1,685,083
1,685,177
Compiling Matlab to C++ Problem: fatal error C1083: Cannot open include file: 'windows.h'
I got this weird error when I was trying to compile matlab to C++ using the following command: 'mcc -W lib:cshared -d ' clibdir ' -T link:lib ' mfile The error I got was: fatal error C1083: Cannot open include file: 'windows.h': No such file or directory Now, I was using lcc as my compiler ( instead of the Visua...
The error message you quote comes from Visual C++, so you're clearly not using lcc, and thus it won't make any difference what files you put in lcc's directories. Try running mbuild -setup to configure Matlab to use a different compiler command. If you (or Matlab, on your behalf) are going to run the Visual C++ command...
1,685,109
1,685,274
Downloading HTTP URLs asynchronously in C++
What's a good way to download HTTP URLs (e.g. such as http://0.0.0.0/foo.htm ) in C++ on Linux ? I strongly prefer something asynchronous. My program will have an event loop that repeatedly initiates multiple (very small) downloads and acts on them when they finish (either by polling or being notified somehow). I wo...
Libcurl is the way to go. See http://curlpp.org for C++ bindings and an excellent set of tutorials.
1,685,127
1,685,194
Ability of SHFileOperation
Does SHFileOperation support to move and rename files at the same time? I'v got a set of files : c:\ f1.bmp f2.bmp f3.bmp f4.bmp I want to move each to new folder, and rename them: d:\ b1.bmp b2.bmp b3.bmp b4.bmp Can I use SHFileOperation? and just do it once? Many thanks!
SHEFILEOPSTRUCT msdn You can use the FOF_MULTIDESTFILES as stated in the msdn article: "The pTo member specifies multiple destination files (one for each source file in pFrom) rather than one directory where all source files are to be deposited." Perform a FO_MOVE operation with this flag.
1,685,339
1,685,399
Verify Knuth shuffle algorithm is as unbiased as possible
I'm implementing a Knuth shuffle for a C++ project I'm working on. I'm trying to get the most unbiased results from my shuffle (and I'm not an expert on (pseudo)random number generation). I just want to make sure this is the most unbiased shuffle implementation. draw_t is a byte type (typedef'd to unsigned char). items...
Well, one thing you could do as a black-box test is take some relatively small array size, perform a large number of shuffles on it, count how many times you observe each permutation, and then perform Pearson's Chi-square test to determine whether the results are uniformly distributed over the permutation space. On the...
1,685,372
1,685,418
Does the array key determine array size in C++?
im storing some settings for objects in an array. the id's of objects are used as the key. the id's start from 100000 and go up. if i was to input data for an object with id 100 000, would cpp automatical create 99999 blank key entries starting from 0?
Array size is determined when you create an array. To access object at index 100 000 you need to have array of at least that size, which answers your question. If the array is smaller you will access memory at array begin address + (index*object size) which is not a good thing. E.g. the following will print some d...
1,685,549
1,685,562
Returning pointer to structure to main function, getting segmentation error
#include<iostream> using namespace std; struct sample { int data[3][2]; }; struct sample* function() { struct sample s; int c=1; for(int i=0;i<3;i++) for(int j=0;j<2;j++) s.data[i][j]=c++; cout<<"Matrix contents are "; for(int i=0;i<3;i++) { for(int j=0;j<2;j++) ...
Your s variable is allocated on the stack, and then you are returning a pointer to it; however, when the function ends, s no longer exists and the pointer is no longer valid. You could either dynamically allocate s and return a reference/pointer to it, or you could return a copy of s rather than a reference. In other...
1,685,556
1,685,596
C++ vector to pointer of pointers
Is there a way to convert a vector to a pointer to a pointer (ptr-to-ptr). Background: I have an arbitrary length set of data stored in a vector. But I have a library of algorithms that accept ptr-to-ptr (for image array access). I need to get the data from my vector to a ptr-to-ptr. How is that possible?
If you have a function void f(int **array) and a vector std::vector<int*> vect you can call f like this: f(&vect[0]). Is this what you were looking for?
1,685,808
1,685,903
How to get the file/resource path for a QIcon
So let's say I do something like this: QIcon myIcon(":/resources/icon.ico"); How can I later determine the path for that icon, e.g. QString path = myIcon.getPath(); The problem is, there is no getPath() member, and I can't find anything similar, but surely there must be a way! I guess I could inherit the QIcon class ...
The filename isn't stored in QIcon, it's only used for constructing the image.
1,685,819
1,685,831
How to convert _bstr_t to CString
I have a _bstr_t variable bstrErr and I am having a CString variable csError. How do I set the value which come in bstrErr to csError?
Is it not possible just to cast it: _bstr_t b("Steve"); CString cs; cs = (LPCTSTR) b; I think this should work when the project is Unicode.
1,685,836
1,695,159
File backed Trie (or Prefix Tree) implementation
I have to store lot of strings in c++ map to keep unique strings and when ever duplicate string occurs I just need to increment the counter (pair.second). I've used c++ map and it well fits to this situation. Since the file that processing is gone now upto 30gig I am trying to keep this in a file instead of memory. I...
If you can sort your file containing the strings, then reading the sorted list and counting duplicates would be easy. (You can retain the original file and create a new file of sorted strings.) Sorting large files efficiently is old technology. You should be able to find a utility for that. If you can't sort, then c...
1,685,858
1,685,879
STL Sorting with Abstract Classes
I'm having a problem sorting my derived classes with the STL sort function. Example - The header: vector<AbstractBaseClass *> *myVector; In the ImpL: sort(myVector->begin(), myVector->end(), compareBy); The comparator: bool MyClass::compareBy(AbstractBaseClass& a, AbstractBaseClass& b) { return (a->someMethod()...
An example: struct Abstr { virtual int some()const == 0; virtual ~Abstr() = default; }; bool abstrSmaller( const Abstr* a1, const Abstr* a2 ) { return a1->some() < a2->some(); } int main() { vector<Abstr*> v; sort( v.begin(), v.end(), abstrSmaller ); } The compare function should not be a member...
1,686,002
1,686,039
How to know the internet connection details using Visual C++ Win32 API
I have to create a log file for all internet connections made by PC. It should have details of the username, time of connection, etc. I do know about the InternetGetConnectedState() function which returns the boolean value. Know how do I get the other details. Can some one help me out thanks in advance. I am using Win3...
You could use Network List Manager API to get list of networks using IEnumNetworks. Then use INetwork interface to get network information.
1,686,204
1,686,421
Why should I not include cpp files and instead use a header?
So I finished my first C++ programming assignment and received my grade. But according to the grading, I lost marks for including cpp files instead of compiling and linking them. I'm not too clear on what that means. Taking a look back at my code, I chose not to create header files for my classes, but did everything in...
To the best of my knowledge, the C++ standard knows no difference between header files and source files. As far as the language is concerned, any text file with legal code is the same as any other. However, although not illegal, including source files into your program will pretty much eliminate any advantages you wo...
1,686,332
1,686,384
How do I use _W64 and __w64 in VC++?
There's such thing as __w64 in Visual C++ 9. I came across it while trying to port my native C++ DLL to 64 bit. In particular in crtdefs.h there's this nice snippet: #if !defined(_W64) #if !defined(__midl) && (defined(_X86_) || defined (_M_IX86)) && _MSC_VER >= 1300 #define _W64 __w64 #else #define _W64 #endif #endif ...
The answer is, you don't. It's a compiler feature for use by the 32 bits compiler. The original idea was that Microsoft wanted to prepare programmers for the upcoming 32->64 bits transition. Therefore, the 32 bits compiler gained the ability to label certain typedefs as __w64. Microsoft then used that ability to label ...
1,686,348
1,687,113
What is #defined if a compiler is Cpp0x compliant?
Is there any official, or inofficial, #defines for when a compiler is Cpp0x compliant? Even better, for specific Cpp0x functionality (~#cpp0xlambda, #cpp0xrvalue etc)? (Haven't found anything about this on the net)
Bjarne's C++0x FAQ says: __cplusplus In C++0x the macro __cplusplus will be set to a value that differs from (is greater than) the current 199711L.
1,686,385
1,687,020
Overloading operator>> to a char buffer in C++ - can I tell the stream length?
I'm on a custom C++ crash course. I've known the basics for many years, but I'm currently trying to refresh my memory and learn more. To that end, as my second task (after writing a stack class based on linked lists), I'm writing my own string class. It's gone pretty smoothly until now; I want to overload operator>> th...
To read characters from the stream until the end of line use a loop. char c; while(istr.get(c) && c != '\n') { // Apped 'c' to the end of your string. } // If you want to put the '\n' back onto the stream // use istr.unget(c) here // But I think its safe to say that dropping the '\n' is fine. If you run out of ro...
1,686,390
1,686,400
Python-equivalent of short-form "if" in C++
Possible Duplicate: Python Ternary Operator Is there a way to write this C/C++ code in Python? a = (b == true ? "123" : "456" )
a = '123' if b else '456'
1,686,423
1,686,957
Downside of this macro construct and possible alternatives
I recently saw some code using macros like #define CONTAINS(Class, Name)\ private:\ std::list<Class> m_##Name##s;\ public:\ void add_##Name(const Class& a_##Name) {\ m_##Name##s.push_back(a_##Name);\ }\ int get_##Name(int pos) {\ return m_##Name##s.at(pos)...
How about: #include <vector> template<typename T> class Plop { std::vector<T> data; public: void add(T const& v) {data.push_back(v);} T get(int pos) {return data.at(pos);} // at() is not valid on lists. }; class my_class { public: Plop<int> integer; Plo...
1,687,085
1,687,121
C++ map really slow?
i've created a dll for gamemaker. dll's arrays where really slow so after asking around a bit i learnt i could use maps in c++ and make a dll. anyway, ill represent what i need to store in a 3d array: information[id][number][number] the id corresponds to an objects id. the first number field ranges from 0 - 3 and each...
1) Your code is buggy: You store a pointer to a local object objSettingsMap which will be destroyed as soon as it goes out of scope. You must store a map obj, not a pointer to it, so the local map will be copied into this object. 2) Maps can become arbitrarily large (i have maps with millions of entrys). If you need sp...
1,687,152
1,687,186
stl vector and c++: how to .resize without a default constructor?
How do I tell STL, specifically for the method resize() in vector, to initialize objects with a constructor other than default, and with which parameters? For example: class something { int a; something (int value); } std::vector<something> many_things; many_things.resize (20); More generally, how do I force...
Use the 2-argument overload: many_things.resize(20, something(5));
1,687,358
1,687,370
C++ positional parameters
This is a very basic question, so please bear with me. Consider the following function in C++: void foo(int a, int b, int c) { //do something } can I call this function like this: foo(b=2, c=3, a=2) ? I suppose this have some sort of name (positional parameters, possibly). If you could clarify it in the answer too,...
Not in standard C++, no. You'll have to provide the parameters in the order specified by the function prototype.
1,687,437
1,687,461
How to call C++ functions/methods via JavaScript
does anybody know how to call C++ functions or methods via JavaScript. Need scripting like Lua/Python-C++ but with JavaScript. Thanks in advance.
You can try Google's V8: open source JavaScript engine. V8 is written in C++ and is used in Google Chrome, the open source browser from Google. V8 implements ECMAScript as specified in ECMA-262, 3rd edition, and runs on Windows XP and Vista, Mac OS X 10.5 (Leopard), and Linux systems that use IA-32 or ARM processors. ...
1,687,558
1,687,611
Calling unmanaged function from C#: should I pass StringBuilder or use unsafe code?
I've got a C# program that needs to pass a char buffer to an unmanaged function. I've found two ways that seem to work reliably, but I'm not sure which I should choose. Here's the unmanaged function's signature. extern "C" __declspec(dllexport) int getNextResponse(char *buffer); The first option is to define the buffe...
I'd strongly prefer using the StringBuilder version. There's not going to be a huge difference between the two, and using unsafe code is not nearly as clean. In my opinion, since there is a way to solve the problem using a core library class, using unsafe code without a clear (and needed) benefit is a premature optimiz...
1,687,579
1,687,617
boost serialization access to protected data
When I try to serialize class with protected members, I get the following errors: "cannot access protected member declared in class NetElement". The idea is that I'd like to have one serialization function outside of class definition. What am I doing wrong? best regards, mightydodol Here is the code... // class defin...
Like any other non-member function, your serialize function can only access the public members of NetElement. If, as is often the case, the public interface doesn't expose enough state to serialize the object, then you'll need to make the serialize function a member. In this case, though, the state is protected, so you...
1,687,860
1,688,142
Why is type_info declared outside namespace std?
I'm using VS2005 and the MS implementation of STL. However, the class type_info in is declared outside of "namespace std". This creates some problems for third party libs that excepts to find a std::type_info. Why is this so, and is there any workaround? Here is a sample from the beginning of typeinfo: class type_info...
That's interesting - the standard does say that (17.4.1.1. Library contents) All library entities except macros, operator new and operator delete are defined within the namespace std or namespaces nested within namespace std. And clearly says that (5.2.8 Type identification) The result of a typeid expression is an ...
1,687,888
1,687,993
Is there a good way of setting C/C++ member variables from string representations? (introspection-lite)
I've got a struct with some members that I want to be able to get and set from a string. Given that C++ doesn't have any introspection I figure I need some creative solution with macros, the stringize operator and maybe boost::bind. I don't need full serialization or introspection, more an 'introspection-lite' I'd lik...
If all of them have the same type, you can use something like this: std::map<std::string,int MyType::*> mapper; mapper["fieldA"]=&MyType::fieldA; mapper["fieldB"]=&MyType::fieldB; ... MyType obj; obj.*(mapper["fieldA"])=3;
1,689,019
1,689,069
Watch a memory location/install 'data breakpoint' from code?
We have a memory overwrite problem. At some point, during the course of our program, a memory location is being overwritten and causing our program to crash. the problem happens only in release mode. when in debug, all is well. that is a classic C/C++ bug, and a very hard one to locate. I wondered if there's a way to ...
If you can control the location of the variable then you can allocate it on a dedicated page and set the permissions of the page to allow reads only using VirtualProtect (on Windows ... not sure for Linux). This way you will get an access violation when someone tries to write to it. With an exception translator functi...
1,689,148
1,689,469
Error in Visual Studio
I get this error in visual studio and I don't know the reason. It doesn't even show the line number. Any clue? Error 1 error LNK2028: unresolved token (0A000041) "void __cdecl free_img(struct Image *)" (?free_img@@$$FYAXPAUImage@@@Z) referenced in function "double * __cdecl calc_zernike_moments(struct Imag...
free_img() is a function that is either defined in a .cpp file that you haven't included in the project, or it is in a DLL or static library that you haven't linked against. If it is the former, you need to search for the function in your source files and then add that .cpp file to the project. If it is the latter, the...
1,689,195
1,689,267
What the C++ rules in regard to covariant return types?
Like in the example below, what is allowed, how and why? class Shape { public: //... virtual Shape *clone() const = 0; // Prototype //... }; class Circle : public Shape { public: Circle *clone() const; //... };
C++ Standard 2003. 10.3.5 The return type of an overriding function shall be either identical to the return type of the overridden function or covariant with the classes of the functions. If a function D::f overrides a function B::f, the return types of the functions are covariant if they satisfy the fo...
1,689,896
1,704,255
Qt Dialog Window Opens in Same Window
I managed to get a QPushButton to open a new window when pressed by using the following code (just snippets of code): AppDialog::AppDialog(QWidget *parent) : QDialog(parent) { QPushButton *button3 = new QPushButton(tr("Apps")); QHBoxLayout *hLayout = new QHBoxLayout; hLayout->addWidget(button3); ...
You might want to look at this question. My answer here is the same... use a QStackedWidget as your main widget, and the stuff you want to be different on each page inside it. (If that is the whole dialog, then make the stacked widget cover the whole dialog). Then you can set the current page of the stacked widget b...
1,690,082
1,690,112
Combining wide string literal with string macro
I have a macro for a character string as follows: #define APPNAME "MyApp" Now I want to construct a wide string using this macro by doing something like: const wchar_t *AppProgID = APPNAME L".Document"; However, this generates a "concatenating mismatched strings" compilation error. Is there a way to convert the APPNA...
Did you try #define APPNAME "MyApp" #define WIDEN2(x) L ## x #define WIDEN(x) WIDEN2(x) const wchar_t *AppProgID = WIDEN(APPNAME) L".Document";
1,690,212
1,690,288
Cross-platform C++ application with .NET GUI?
I have a few years of experience in cross-platform desktop development (Windows and MacOSX, not Linux (at least not for GUI apps)). Usually I create the GUI on MacOSX with Cocoa, and on Windows I use the old-fashioned Windows API. I have not used Qt because when I started it was still under the GPL license. I find the ...
Yes, you need to bundle the .NET framework with the installer or notify the user that they need to install it and provide a link if it's not already installed. In my experience, the added .NET code does add some appreciable weight to the executable, but I've found it to be more inconvenient having to install the .NET f...
1,690,261
1,797,938
Why do I get a CL_MEM_OBJECT_ALLOCATION_FAILURE?
I'm allocating a cl_mem buffer on a GPU and work on it, which works fine until a certain size is exceeded. In that case the allocation itself succeeds, but execution or copying does not. I do want to use the device's memory for faster operation so I allocate like: buf = clCreateBuffer (cxGPUContext, CL_MEM_WRITE_ONLY, ...
clCreateBuffer will not actually create a buffer on the device. This makes sense, since at the time of creation the driver does not know which device will use the buffer (recall that a context can have multiple devices). The buffer will be created on the actual device when you enqueue a write or when you launch a kerne...
1,690,675
1,690,694
Implementing a default constructor
I am trying to implement a DateTime class in C++: class DateTime { public: DateTime(); DateTime(time_t ticks); DateTime(int day, int month, int year); DateTime(int day, int month, int year, int hour, int minute, int second); //... private: time_t ticks; int day; int month; //... } ...
Typically, the default constructor would initialize you to a "default" reference time. If you're using a time_t internally, setting it to time_t of 0 (Unix epoch, which is 1/1/1970) would be a reasonable option, since "0" values are common defaults. That being said, a default constructor is not required in C++ - you ca...
1,691,007
1,691,310
What's the right way to overload operator== for a class hierarchy?
Suppose I have the following class hierarchy: class A { int foo; virtual ~A() = 0; }; A::~A() {} class B : public A { int bar; }; class C : public A { int baz; }; What's the right way to overload operator== for these classes? If I make them all free functions, then B and C can't leverage A's versio...
For this sort of hierarchy I would definitely follow the Scott Meyer's Effective C++ advice and avoid having any concrete base classes. You appear to be doing this in any case. I would implement operator== as a free functions, probably friends, only for the concrete leaf-node class types. If the base class has to have ...
1,691,100
1,691,135
Is there anything wrong with the way that this C++ header is laid out?
#pragma once #include "LudoCore/Singleton.h" class LudoTimer : public Singleton<LudoTimer> { friend class Singleton<LudoTimer>; public: void Update(); void ShortenDay(); void LengthenDay(); UINT64 GetDeltaTime() const; float GetPercentageOfDayElapsed() const; private: LudoTimer(); ~Lu...
Have a look in the other header (LudoCore/Singleton.h). The second error implies that the error is before the class LudoTimer declaration at the top. My guess is that Singleton.h defines a class, and there's a missing ';' after that class definition.
1,691,395
1,691,624
How to statically link using link.exe
I've been trying to statically link against a C++ library called Poco on Windows using the Visual Studio 2008 command line tools. I build my program with: cl /I..\poco\lib /c myapp.cpp link /libpath:..\poco\lib myapp.obj PocoNet.lib This results in an exe that at runtime requires PocoNet.dll and PocoFoundation.dll. I ...
You have to define POCO_STATIC on the command line and link with both PocoFoundationmt and PocoNetmt.lib: C:\test>cl /MD /WX /nologo /EHsc /DPOCO_STATIC /DUNICODE /D_UNICODE /I..\poco\Foundation\include /I ..\poco\Net\include /c exp.cpp exp.cpp C:\test>link /libpath:..\poco\lib /WX /nologo exp.obj PocoNetmt.lib PocoF...
1,691,473
1,691,506
Somehow register my classes in a list
I would like to be able to register my classes within a std::map or a vector, don't think about duplicates and such for now, but I don't want to register it within the class constructor call or any within function of the class, somehow do it outside the class so even if I never instantiate it, I would be able to know ...
Here is method to put classes names inside a vector. Leave a comment if I missed important details. I don't think it will work for templates, though. struct MyClasses { static vector<string> myclasses; MyClasses(string name) { myclasses.push_back(name); } }; #define REGISTER_CLASS(cls) static MyClasses myclass...
1,691,491
1,691,558
how to build a vector of different objects after reading a file
everyone! I am new for C++ and now work on a C++ project.The whole structure has been completed.But I have been wondering about how to build the vector of different objects and how to read the file since the beginning. In my problem, first I have to read a txt file with readObstacles(std::istream &fs) that has the fol...
You could try just reading the whole line at a time then tokenize the values... vector<Obstacle*> obsdata; string line; while(getline(fs, line)) { char *token = strtok(line.c_str(), " "); string shape(token); vector<double> numbers; stringstream ss; while(token = strtok(NULL, " ")) { doubl...
1,691,609
3,670,717
Using Qt to make an almost native Windows Application?
I love that Qt is cross-platform but I want to make an application that will call into some Windows specific .dll's. Kinda like Google Chrome does with the glass on Windows Vista/7 (I know Chrome isn't written using the Qt framework just thought it was a good example). How can I do this in Qt? Is it feasible?
You can of course call WinAPI functions directly from your Qt code, then it's better to include qt_windows.h not windows.h. If you just want to add the cool new Windows 7 features to your application then you are better of using a dedicated Qt add-on. There is one called Q7Goodies.
1,691,759
1,691,849
What questions should an expert in STL be expected to answer, in an interview
I was looking at a job posting recently and one of the requirements was that a person be a 9/10 in their knowledge of STL. When I judge my skills, to me a 10 is someone that writes advanced books on the subject, such as Jon Skeet (C#), John Resig (JavaScript) or Martin Odersky (Scala). So, a 9/10 is basically a 10, so ...
Funny -- I don't consider myself a 9/10 in STL (I used to be, but I'm a bit rusty now), and I do fully agree with @joshperry's important terminological distinguo (I've often been on record as berating the abuse of STL to mean "the parts of the C++ standard library that were originally inspired by SGI's STL"!-), yet I c...
1,692,084
1,692,966
How Non-Member Functions Improve Encapsulation
I read Scott Meyers' article on the subject and quite confused about what he is talking about. I have 3 questions here. Question 1 To explain in detail, assume I am writing a simple vector<T> class with methods like push_back, insert and operator []. If I followed Meyers' algorithm, I would end up with all non-member ...
Question 1 In this case, following Meyers's algorithm will give you member functions: Do they need to be virtual? No. Are they operator<< or operator>>? No. Do they need type conversions? No. Can they be implemented in terms of the public interface? No. So make them members. His advice is to only make them friends wh...
1,692,156
1,692,167
Erasing a vector element by key
ive defined the following and filled it with elements: vector <vector<double> > my_vector; but i want a delete an element with a specific key... my_vector.erase(int(specific_key)); but it doesnt allow me. how would i properly dispose of the elements assigned to that key properly?
Assuming by specific_key you mean the element at that position in the vector: my_vector.erase(my_vector.begin() + specific_key); Would be the "most correct" answer. If you meant to delete the element that matches specific_key (which will have to be of type vector<double> in the given example: my_vector.erase(find(my_v...
1,692,184
1,692,210
Converting epoch time to "real" date/time
What I want to do is convert an epoch time (seconds since midnight 1/1/1970) to "real" time (m/d/y h:m:s) So far, I have the following algorithm, which to me feels a bit ugly: void DateTime::splitTicks(time_t time) { seconds = time % 60; time /= 60; minutes = time % 60; time /= 60; hours = time % 24...
Be careful about leap years in your daysInMonth function. If you want very high performance, you can precompute the pair to get to month+year in one step, and then calculate the day/hour/min/sec. A good solution is the one in the gmtime source code: /* * gmtime - convert the calendar time into broken down time */ /*...
1,692,188
1,692,200
Dynamic Memory Allocation in C++
What is the difference between the 'delete' and 'dispose' C++ operators with regards to dynamic memory allocation?
delete will free memory dynamically allocated in unmanaged C++ Dispose will force custom object implemented maintenance of disposable objects in managed C++/CLI
1,692,300
1,692,338
Aligning a class to a class it inherits from? Force all stack alignment? Change sizeof?
I want to have a base class which dictates the alignment of the objects which inherit from it. This works fine for the heap because I can control how that gets allocated, and how arrays of it get allocated in a custom array template. However, the actual size of the class as far as C++ is concerned doesn't change at all...
If a base class has a particular alignment requirement, then any derived classes will have at least that alignment (they could get a stricter alignment requirement due to their own members). Otherwise the compiler couldn't guarantee that accessing the base members would meet the requirements they have. However, there's...
1,692,319
1,692,328
Declaration inside if/switch
I'm trying to do something like this in C++: if(){ int a; } else if(){ char a; } else { double a; } f(a); But I get an error from the compiler saying that a was not declared in this scope. I need to do a conditional declaration, how can I do it? Many thanks edit: I cannot move the function inside the cond...
It appears that you want different overloads to be called depending on the path taken through the conditional structure. This is not possible in a static language like C++ because the compiler needs to decide which overload to call at compile time, and can only pick one for each call. Do this instead: if (...) { in...
1,692,418
1,692,860
How to solve linear equations using a genetic algorithm?
I want to solve a system of n linear equations containing n variables using a genetic algorithm. I am having difficulty in defining the crossover operation as the solution may consist of floating point values. How do I proceed? It seems possible, but this is my first encounter with genetic algorithms. Suppose we have t...
One route is to pick your own floating point representation, which frees you to much with values as you want. Of course, that makes you responsible for implementing arithmetic operations. Perhaps you could find a bignum library you could alter. You could also decompose platform-native floating points using e.g. frexp d...
1,692,680
1,692,724
Compiling a shared library with Qt on Ubuntu 9.10
I am new to both Qt and Linux C++ development (although I have many years C and C++ development experience on Windows). I have some legacy C projects (source files and headers - [not using Qt]) that I want to compile into shared libs on Linux. I am proposing to store my projects under the following structure: /home/use...
An Ubuntu system doesn't come with build tool chain by default. Instead it has a meta package that you will need to install: sudo apt-get install build-essential This will install, among other the g++ compiler, although I am not sure about the Qt headers an such. For them you will need the qt4-dev package (I assume yo...
1,693,042
1,693,068
How do STL containers copy objects?
I know STL containers like vector copies the object when it is added. push_back method looks like: void push_back ( const T& x ); I am surprised to see that it takes the item as reference. I wrote a sample program to see how it works. struct Foo { Foo() { std::cout << "Inside Foo constructor" << std::e...
It probably uses "placement new" to construct the object in-place in its internal array. Placement new doesn't allocate any memory; it just places the object where you specify, and calls the constructor. The syntax is new (address) Class(constructor_arguments). The copy constructor T::T(T const &) is called to create t...
1,693,089
1,693,123
Fastest way to write large STL vector to file using STL
I have a large vector (10^9 elements) of chars, and I was wondering what is the fastest way to write such vector to a file. So far I've been using next code: vector<char> vs; // ... Fill vector with data ofstream outfile("nanocube.txt", ios::out | ios::binary); ostream_iterator<char> oi(outfile, '\0'); copy(vs.begin(),...
There is a slight conceptual error with your second argument to ostream_iterator's constructor. It should be NULL pointer, if you don't want a delimiter (although, luckily for you, this will be treated as such implicitly), or the second argument should be omitted. However, this means that after writing each character, ...
1,693,098
1,693,293
How dynamic casts work?
Let's say I have type A, and a derived type B. When I perform a dynamic cast from A* to B*, what kind of "runtime checks" the environment performs? How does it know that the cast is legal? I assume that in .Net it's possible to use the attached metadata in the object's header, but what happen in C++?
Exact algorithm is compiler-specfic. Here's how it works according to Itanium C++ ABI (2.9.7) standard (written after and followed by GCC). Pointer to base class is a pointer to the middle of the body of the "big" class. The body of a "big" class is assembled in such a way, that whatever base class your pointer point...
1,693,134
1,693,160
Declaring an array whose size is declared as extern const
I have a problem initializing an array whose size is defined as extern const. I have always followed the rule that global variables should be declared as extern in the header files and their corresponding definitions should be in one of the implementation files in order to avoid variable redeclaration errors. This appr...
The constant is external, so it is defined in another compilation unit (.o file). Therefore the compiler cannot determine the size of your array at compilation time; it is not known until link time what the value of the constant will be.
1,693,336
1,693,348
Overloading both operator< and operator> in the same class
In my homework, I have to design a class Message; among other attributes, it has attribute "priority" (main goal is to implement priority queue). As in container I must check if one object is greater than other, I have overloaded operator '>'. Now, I have a few general questions about it... Question one: If I overload ...
If I overload operator '>', should I overload operator '<' for argumenst (const Message&, const Message&)? Yes. In fact, it’s convention in most code to prefer the usage of < over > (don’t ask me why, probably historical). But more generally, always overload the complete set of related operators; in your case, this w...
1,693,345
1,693,355
Tool for program statistics
Is there a tool which is able to parse my source code (fortran, C or C++) and return statistics such as the number of loops, the average loop size, the number of functions, the number of function calls, the number, size and type of arrays, variables, etc ? Something similar to this which does not run easily on my archi...
The magic Google term is "code metrics". Wikipedia has a list.
1,693,523
2,458,711
StAX Writer Implementation for C/C++
Are there any other STaX Writer implementation for C/C++ except libxml2?
LLamaXML Its one of the few C++ pull parsers.
1,693,579
1,693,591
Bitflag enums in C++
Using enums for storing bitflags in C++ is a bit troublesome, since once the enum values are ORed they loose their enum-type, which causes errors without explicit casting. The accepted answer for this question suggests overloading the | operator: FlagsSet operator|(FlagsSet a, FlagsSet b) { return FlagsSet(int(a)...
Runtime implications in terms of correctness? No - this should be exactly what you want. Runtime implications in terms of speed? I would expect any decent compiler to optimize this away properly to the minimal number of instructions for a release build (although you might want to add inline just to be sure).
1,693,615
1,693,643
What are the best RSS feeds for C++?
What are the best RSS feeds for C++ ?
This post lists C++ blogs, most of those blogs have rss feeds. Also...don't forget the rss feed for the Stackoverflow C++ tag!
1,693,871
1,693,901
Problem with priority_queue - Writing memory after heap
I am trying to use priority_queue, and program constantly fails with error message HEAP CORRUPTION DETECTED. here are the snippets: class CQueue { ... priority_queue<Message, deque<Message>, less<deque<Message>::value_type> > m_messages; ...}; class Message has overloaded operators > and < Here I fill up...
I think the problem is that your Message objects are keeping pointers to raw C strings which are then getting deallocated. In these lines: cin >> str; Message p(str.c_str(), rand()%12); On each iteration of the loop, you're reading in a new value to str, which invalidates any old pointers returned by its c_str() met...
1,693,908
1,693,919
C++: pass variable by value
This is the situation: int f(int a){ ... g(a); ... } void g(int a){...} The problem is that the compiler says that there is no matching function for call to g(int&). It wants me to pass the variable by reference and g() recieves parameters by value. How can I solve this?
Well, there's not much here, but the first thing is: make sure you have a declaration for g that's included before f is defined. void g(int a); Otherwise, when you get to f, function f has no idea what function g looks like, and you'll run into trouble. From what you've given so far, that's the best I can say.
1,694,041
1,694,099
Rotating coordinates around an axis
I'm representing a shape as a set of coordinates in 3D, I'm trying to rotate the whole object around an axis (In this case the Z axis, but I'd like to rotate around all three once I get it working). I've written some code to do this using a rotation matrix: //Coord is a 3D vector of floats //pos is a coordinate //angl...
Where you do your rotation in rotateByMatrix, you compute the new pos[0], but then feed that into the next line for computing the new pos[1]. So the pos[0] you're using to compute the new pos[1] is not the input, but the output. Store the result in a temp var and return that. Coord<float> tmp; tmp[0] = (cosf(zrot) * po...
1,694,063
1,694,069
Templates and nested classes/structures
I have a simple container : template <class nodeType> list { public: struct node { nodeType info; node* next; }; //... }; Now, there is a function called _search which searches the list and returns a reference to the node which matched. Now, when I am referring to the r...
that's because node is a dependent type. You need to write the signature as follows (note that I have broken it into 2 lines for clarity) template <class nodeType> typename list<nodeType>::node* list<nodeType>::_search() { //function } Note the use of the typename keyword.
1,694,320
1,694,333
how many strings in a const char* str[]?
const static char *g_szTestDataFiles[] = { ".\\TestData\\file1.txt", ".\\TestData\\file2.txt", ".\\TestData\\file3.txt", ".\\TestData\\file4.txt", ".\\TestData\\file5.txt", ".\\TestData\\file6.txt" }; Is there way to programmatically determine how many items is in that thing? I could alway...
Arkaitz has given you the preferred way of handling this, but as we're talking about an array of const char * here, you should be able to do the following: int size = sizeof(g_szTestDataFiles) / sizeof(g_szTestDataFiles[0]);
1,694,518
1,695,779
Hiding a QWidget on a QToolbar?
I have directly added some QWidgets to a QToolbar but simply going widget->setVisible(false) did not work. Can someone please give me an example of how to show and hide a widget that is on a QToolbar? Thanks!
You need to call setVisible() on the appropriate QAction instead. For example, addWidget() returns a QAction*: QAction* widgetAction = toolBar->addWidget(someWidget); widgetAction->setVisible(false);
1,694,665
1,694,669
static variable vs. member
If you have data for a class that will be modified and needs to be retained throughout the program, but is only used in one member function, is it preferred to make that variable a local static variable of the routine that it is in or make it a member of the class?
The question isn't "will the data be used throughout the program", but rather "if you make two objects of this class, do you want them to share this data?" If yes, make it static. If no, don't.
1,694,785
1,694,895
What should I do with this strange error?
Everything is fine and the final problem is so annoying. Compile is great but link fails: bash-3.2$ make g++ -Wall -c -g Myworld.cc g++ -Wall -g solvePlanningProblem.o Position.o AStarNode.o PRM.o PRMNode.o World.o SingleCircleWorld.o Myworld.o RECTANGLE.o CIRCLE.o -o solvePlanningProblem **Undefined symbols: "vtable...
You declare a non-abstract class Obstacle, but you don't implement all its member functions. Better declare it as abstract class: class Obstacle{ public: Obstacle(){} // this is superfluous, you can (and should) remove it virtual bool collidesWith(double x,double y) = 0; virtual void writeMatlabDisplayCode(...
1,694,798
1,694,807
C++ error converting a string to a double
I am trying to convert a string to a double. The code is very simple. double first, second; first=atof(str_quan.c_str()); second=atof(extra[i+1].c_str()); cout<<first<<" "<<second<<endl; quantity=first/second; when trying to convert extra, the compiler thr...
It sounds like extra is a std::string, so extra[i+1] returns a char, which is of non-class type. It sounds like you are trying to parse the string extra starting from the i+1th position. You can do this using: second = atof(extra.substr(i + 1).c_str());
1,694,902
1,695,838
Hash/key creation function for latitude longitude?
I have blocks of data associated with latitude/longitude values. I'd like to create a lookup key/hash value from the latitude/longitude value so it can be used as a lookup into a map or something similar. I'm using negative values for West and South... therefore 5W, 10S is represented as -5, -10 in the program. I'...
You could also encode it in nicely into a 64-bit integer using some bit manipulation longitude ranges from -180 to 180 so needs a minimum of 9 bits. lattitude rangs from -90 to +90 so needs a minimum of 8 bits. minutes go from 0 to 60 so require 6 bits. same for seconds. 9+12 = 21 bits for longitude and 20 bits for lat...
1,694,963
1,694,981
Thread-safe, lock-free increment function?
UPDATED: Is there a thread-safe, lock-free and available on all Linux distros increment function available in C or C++ ?
GLib has functions to do this. You might check out http://library.gnome.org/devel/glib/stable/glib-Atomic-Operations.html Specifically, it sounds like you want g_atomic_int_inc()
1,695,042
1,695,087
Is garbage collection automatic in standard C++?
From what I understand, in standard C++ whenever you use the new operator you must also use the delete operator at some point to prevent memory leaks. This is because there is no garbage collection in C++. In .NET garbage collection is automatic so there is no need to worry about memory management. Is my understandi...
The long answer to it is that for every time new is called, somewhere, somehow, delete must be called, or some other deallocation function (depends on the memory allocator etc.) But you don't need to be the one supplying the delete call: There is garbage collection for C++, in the form of the Hans-Boehm Garbage Collec...
1,695,288
1,695,296
Getting the current time (in milliseconds) from the system clock in Windows?
How can you obtain the system clock's current time of day (in milliseconds) in C++? This is a windows specific app.
To get the time expressed as UTC, use GetSystemTime in the Win32 API. SYSTEMTIME st; GetSystemTime(&st); SYSTEMTIME is documented as having these relevant members: WORD wYear; WORD wMonth; WORD wDayOfWeek; WORD wDay; WORD wHour; WORD wMinute; WORD wSecond; WORD wMilliseconds; As shf301 helpfully points out below, Get...
1,695,303
1,695,306
Private static variables to establish invariants
Is it reasonable to use private static variables to establish invariants in your class? Ex: class MovingObject { public: //...Stuff private: // Invariants static const double VELOCITY; // Moving objects always move at this velocity // etc. for any other invariants //... } ---------------------------...
Sure. This is a common idiom across several OO languages including Java.
1,695,389
1,695,544
Odd behavior of mktime()
Continuing on my attempt to create a DateTime class , I am trying to store the "epoch" time in my function: void DateTime::processComponents(int month, int day, int year, int hour, int minute, int second) { struct tm time; time.tm_hour = hour; time.tm_min = minute; time...
You're passing 0 as the day parameter and putting that into time.tm_mday. That component (and only that component) of struct tm is 1-based, not 0-based. Don't ask me why. To specify 01 Jan 1970, 12:00:00am you'd want to call it like so: processComponents(0,1,1970,0,0,0); And as sdtom mentioned, you'll want to make su...