question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
3,069,375
3,069,403
setting value of string& to string
I have a string& parameter, and i want to assign it to string parameter. How can it be done.
void f(string &param); string myString = "something"; f(myString) Is that what you need?
3,069,545
3,069,570
Handles and pointer to object
I have a python Interpreter written in C++, the PyRun_String function from the Python API is said to return a handle, however in my code I have it assigned to pointer to a PyObject? PyObject* presult = PyRun_String(code, parse_mode, dict, dict); Is this actually correct? Can you implicitly cast this handle to this o...
The word "handle" in API documentation usually does not refer specifically to the HANDLE type, but rather to any type intended to be opaque to the user. PyRun_String in particular returns a PyObject*, there is no cast going on.
3,069,613
3,069,724
Why doesn't g++ pay attention to __attribute__((pure)) for virtual functions?
According to the GCC documentation, __attribute__((pure)) tells the compiler that a function has no side-effects, and so it can be subject to common subexpression elimination. This attribute appears to work for non-virtual functions, but not for virtual functions. For example, consider the following code: extern void ...
Without looking into g++'s internals, I suspect it's because g++ can't assume that every subclass's implementation will be pure (like you said). Can you turn b2 into a non-virtual pure wrapper around a virtual non-pure method?
3,069,801
3,069,814
Where can I define the body for a private function?
I have a header like this (header guards not shown): class GameSystem { public: GameSystem(Game *pcGame); virtual ~GameSystem(); void Setup(); private: void InitGame(); void RunGame(); void ExitGame(); Game *m_pcGame; /* Properties */ int m_nWidth; int m_nHeight; int m_nFps;...
Yes, you can define then in a .cpp file. Just put #include "MyHeader.h" at the beginning of the file. You'll also need to start each function like so void GameSystem::Init(){ //stuff }
3,069,862
3,069,960
Help with Arduino and Analog Min Max settings
Hey there, I have the following code: sVal = analogRead(potPin); // read the value from the sensor valMin = min(sVal, 1); valMax = max(sVal, 128); constrain(sVal,valMin,valMax); itoa(sVal, res, 10); println(res); println(" "); delay(150); clearScreen(); Now for some reason, the output on the gLCD...
Your code indicates a lack of understanding of the min, max and constrain functions. I suggest you read the documentation more carefully. In the meantime, here is what I think you're after: sVal = analogRead(potPin); sVal = sVal / 8 + 1; //scale value [0.. 1023] to [1.. 128] itoa(sVal, res, 10); println(res); println(...
3,069,945
3,070,112
Open source soft modem that runs on Linux?
Can anyone recommend an open source soft modem (a software only emulation of a modem card), that runs on Linux? Preferably, this will be implemented in C/C++
take a look at iaxmodem
3,069,950
3,070,012
Changing number precision
How would you change the precision of a number for example: float n = 1.2345 and store it back to the variable 'n' with changing it to 1.23 ?
float n = 1.2345; int scaled = n * 100 n = static_cast<float>(scaled)/100.0; or in one line: n = static_cast<float>( static_cast<int>(n*100) ) / 100;
3,070,187
3,070,203
C++ / Java: Toggle boolean statement?
Is there a short way to toggle a boolean? With integers we can do operations like this: int i = 4; i *= 4; // equals 16 /* Which is equivalent to */ i = i * 4; So is there also something for booleans (like the *= operator for ints)? In C++: bool booleanWithAVeryLongName = true; booleanWithAVeryLongName = !booleanWithA...
There is no such operator, but this is a little bit shorter: booleanWithAVeryLongName ^= true;
3,070,290
3,070,806
C++ vtable resolving with virtual inheritance
I was curious about C++ and virtual inheritance - in particular, the way that vtable conflicts are resolved between bass and child classes. I won't pretend to understand the specifics on how they work, but what I've gleamed so far is that their is a small delay caused by using virtual functions due to that resolution. ...
There is no hit for calling nonvirtual functions in the child class. If you're calling an overridden version of your pure virtual function as in your example, then the virtual penalty may still exist. In general it's difficult for compilers to optimize away the use of the virtual table except under very specific circum...
3,070,317
3,070,710
question on arrays in c++
int java declaration of array like this int a[][]=new int[3][3] works but in c++ not why? please help me i have not used c++ a long time so please help me
I once had this same problem and ended up creating a class for it. Basically it's stored as a pointer of single dimension array and the pointers are manipulated a bit so that it acts just like a 2D array (matrix). Here's the code I used: #include <utility> #include <memory.h> template <typename T> class Matrix { prote...
3,070,417
3,070,760
ITASK API for Windows Scheduler
Does anybody know what permissions are needed to create ITASK? This is the error I am getting in C++: Error creating ITask. Error: -2147024891
That error is 0x80070005 in hex. Facility 7 = Windows, error code 5 = Access Denied. The user account used to run this code doesn't have sufficient rights. Creating scheduled tasks is a privileged operation. Talk to the server admin about getting the rights to do this.
3,070,425
3,070,566
Best way to write a recursive function in C++?
Question I wish to know if this is a viable way to implement variable depth recursion so that I can run a function at each step and any better/other solutions to the description problem. Description Suppose I wish to have a function that fills an array either in pattern x,y,x,y,x,ywhere x and y are variables defined by...
So, based on your comment you want to know the best way to set up a recursive function. What you have done will work, but it is convoluted and slightly confusing. What I would do to simplify it is: void recurse_n(int n) { if (n <= 0) { // Break-out condition return; } --n; recurse_n(n...
3,070,461
3,070,859
Unexpected termination when pushing a shared_ptr into a list
I have some function: void addNormalLine(int id, LineNumber number, Rate smsRate, Rate callRate) { list<Account>::iterator iAccounts; findAccount(iAccounts, id); if(iAccounts == listOfAccounts.end()){ throw "AccountDoesNotExist"; } if(lineExists(number)){ throw "LineExist...
It's a bad practice to use strings as exception values. Use classes for exceptions, at least something like std::runtime_error() or better create a new class derived from it. Make sure you catch exceptions you're throwing in this method. What's the definition of findAccount?
3,070,625
3,070,658
Is there an open source netflow collector C++ library set?
I am looking for a C++ library set to develop my own C++ daemon in Linux for collecting NetFlow information. Does anyone know of an open source one or a library set that is available? Many thanks
Have you tried Googling? There are plenty of daemons for NetFlow available, for Linux and BSD flavors: http://www.mindrot.org/projects/softflowd/ http://fprobe.sourceforge.net/ http://lionet.info/ipcad/
3,070,730
3,078,106
Video display with openGL
I want to display very high resolution video directly with OpenGL. The image data is going to be processed on the GPU and I want to avoid a round-trip back to the PC to show the video in a standard bitmap based window. Cross platform is nice, Windows only would be OK (so would nvidia only) Anyone have any links to ways...
Assuming OpenGL 2.1, use a buffer object of type GL_PIXEL_UNPACK_BUFFER to stream pixel data to a texture. It's faster than uploading data every frame as the implementation might use DMA for copying when you use glMapBuffer, glMapBufferRange (OpenGL 3.2) or call glBufferData directly. You can also copy several frames i...
3,070,786
3,070,829
C++ Generate and store the co-ordinates of an n-cube
I want to write a function to generate and store the co-ordinates of an n-cube and I have no idea how to start. Specifically, I wish to generate the co-ordinates for an evenly or randomly distributed cloud of points for this n-cube and store them. What would be a good way to start with this or if possible, a quick solu...
I don't want to give C++ source code for this problem, however, here's the thought how you could generate it. A hypercube contains all bit-strings of length n. Thus there are 2^n possibilities for coordinates in total. Now how you can do it recursively: if you want to generate coordinates for n=1, just return 0 and 1...
3,070,805
3,070,815
How to design a utility class?
But I don't know if I should go for static methods, just a header, a class, or something else? What would be best practice? But, I don't want to have an instance of a utility class. I want to add functions like: Uint32 MapRGB (int r, int g, int b); const char* CopyString(const char* char); // etc. You know: utility met...
Don't put them in a class; just make them non-member functions at namespace scope. There's no rule that says every function has to be a member function of some class.
3,070,841
3,071,740
Is stack address shared by Heap addresses?
I read On most operating systems, the addresses in memory starts from highest to lowest. So I am wondering if the heap, stack, and global memory all fall under the same ordering..? If I created... pointerType* pointer = new pointerType //creates memory address 0xffffff And then created a local varible on the stack lo...
the addresses in memory starts from highest to lowest Are the addresses of the houses on your street ordered from highest to lowest, or from lowest to highest? Well, that depends on which way you're driving. Just like postal addresses, memory addresses aren't really ordered at all. Each address simply identifies a ...
3,070,904
3,070,999
C++ compiler error on template specialization
I would like to specialize a template method for a class C that is itself templated by an int parameter. How do I do this? template <int D=1> class C { static std::string foo () { stringstream ss; ss << D << endl; return ss.str();} }; template <class X> void test() { cout << "This is a test" << endl;} templ...
Function template partial specialization is not allowed. Do template <int D> void test () {cout << C<D>::foo() << endl;}
3,070,928
3,070,984
C++ map to track when the end of map is reached
Currently I have a map that prints out the following map<string, map<int,int> > mapper; map<int,int>::iterator inner; map<string, map<int,int> >::iterator outer; for(outer = mapper.begin(); outer != mapper.end(); outer++){ cout<<outer->first<<": "; for(inner = outer->second.begin(); inner != outer->second.end()...
Change your output line to print the comma first and only if it is not the first element: if (inner != outer->second.begin()) std::cout << ","; std::cout << inner->first << "," << inner->second;
3,071,020
3,071,108
IF Statement has strange behavior
I've developed a 'custom' cout, so that I can display text to console and also print it to a log file. This cout class is passed a different integer on initialization, with the integer representing the verbosity level of the message. If the current verbosity level is greater then or equal to the verbosity level of the ...
When you define a static variable outside a class, you're defining a separate variable for each source file into which you include the header -- changing the value in one doesn't affect the value of the variable with the same name in another file. What you almost certainly want is to have int ilralevel_set = 0; int il...
3,071,475
3,071,686
String method crashes program
Alright so i have two identical string methods... string CreateCust() { string nameArray[] ={"Tom","Timo","Sally","Kelly","Bob","Thomas","Samantha","Maria"}; int d = rand() % (8 - 1 + 1) + 1; string e = nameArray[d]; return e; } string CreateFood() { string nameArray[] = {"spagetti"...
The crash is happening because you are accessing an invalid index. This is because array indexes start from 0 and not 1, so you don't want to add a 1 to the rvalue of the modulus operator. Here is a neat trick that you can use to make your code a little more maintainable: template <class T> T getRandElem( const T[] ar...
3,071,652
3,071,707
CPU Process time using GetProcessTimes and FileTimeToSystemTime do not work in 64 bit win
I am trying to measure CPU time. It works great on Win 32, but on 64 bit, it says: error LNK2019: unresolved external symbol __imp_GetProcessTimes referenced in function "unsigned int __cdecl getWINTime(void)" (?getWIN32Time@@YAIXZ) It has similar error for FileTimeToSystemTime error LNK2019: unresolved external symb...
Do you're build settings for the two environments have the same import libraries listed. Both of those functions are in kernel32.dll.
3,071,665
3,071,729
Getting a directory name from a filename
I have a filename (C:\folder\foo.txt) and I need to retrieve the folder name (C:\folder) in C++. In C# I would do something like this: string folder = new FileInfo("C:\folder\foo.txt").DirectoryName; Is there a function that can be used in C++ to extract the path from the filename?
There is a standard Windows function for this, PathRemoveFileSpec. If you only support Windows 8 and later, it is highly recommended to use PathCchRemoveFileSpec instead. Among other improvements, it is no longer limited to MAX_PATH (260) characters.
3,071,710
3,072,061
What is the fastest design to download and convert a large binary file?
I have a 1GB binary file on another system. Requirement: ftp/download and convert binary to CSV on main system. The converted file will be magnitudes larger ~ 8GB What is the most common way of doing something similar to this? Should this be a two step independent process, download - then convert? Should I download...
I would write a program that converts the binary format and outputs to CSV format. This program would read from stdin and write to stdout. Then I would call wget URL_of_remote_binary_file --output-document=- | my_converter_program > output_file.csv That way you can start converting immediately (without downloading the...
3,071,785
3,072,002
does sfinae instantiates a function body?
I want to detect existence of a specific member function for a class, using the usual SFINAE trick. template<typename T> struct has_alloc { template<typename U,U x> struct dummy; template<typename U> static char test(dummy<void* (U::*)(std::size_t),&U::allocate>*); template<typename U> static ...
No, SFINAE is only in effect during overload resolution. Once a resolution has been made and the compiler begins instantiating the function SFINAE is over. Edit: and taking the address of a function instantiates it.
3,071,806
3,071,899
C++ Union, Struct, Member type
If I have a class: class Odp { int i; int b; union { long f; struct { WCHAR* pwszFoo; HRESULT hr; }; }; } Union means that, of all values listed, it can only take on one of those values at a time? How does that work in terms of acce...
This is a very fraught area in the C++ standard - basically a union instance, per the standard can only be treated at any one time as if it contained one "active" member - the last one written to it. So: union U { int a; char c; }; then: U u; u.a = 1; int n = u.a; u.c = 2; char c = u.c; is OK, but: U u; u.a = 1...
3,072,050
3,072,194
Can I reconstruct C++ source code from debug binaries?
I have a C++ application compiled in debug (using MinGW and Qt) but I've lost some major changes because someone in my team forgot to commit his changes in the source control manager and overwrote the source code with other changes. When I run the program in debug (in Qt Creator) I can set a break point in main and the...
When I run the program in debug (in Qt Creator) I can set a break point in main and then see the source code. Really? Find out where your debugger is getting the source code from, and copy it from there. It's more likely that your debugger is just grabbing a file on your system with the same name/path as the original...
3,072,074
3,072,089
sizeof(Structure) Confusion
In the following piece of code, #include<stdio.h> typedef struct { int bit1:1; int bit3:4; int bit4:4; } node; int main(){ node n,n1,n2,ff[10]; printf("%d\n",sizeof(node)); return 0; } How do I predict the size of the structure?
You cannot predict it without knowing the compiler and the target platform it compiles to.
3,072,248
3,072,399
Why aren't template specializations allowed to be in different namespaces?
Please, see what I am trying to do: #include <iostream> namespace first { template <class T> class myclass { T t; public: void who_are_you() const { std::cout << "first::myclass"; } }; } namespace second { using first::myclass; template <> class myclass <int> { int i, j; public: void who_are_you() ...
C++ 2003, §17.4.3.1/1: "A program may add template specializations for any standard library template to namespace std. Such a specialization (complete or partial) of a standard library template results in undefined behavior unless the declaration depends on a user-defined name of external linkage and unless the special...
3,072,421
3,072,448
Difference between (++i) and (i++)
In C++ I understand that (++i) should return a reference to i because the need of concatenation of operators, but what I can't figure out is: Why (i++) should return i by value? Can anyone please clarify.
++i can be written as prefix_inc (this) { increase this by 1 return this } Since the real i is returned, we can take reference of it. However, i++ looks like postfix_inc (this) { set old_this = copy of this increase this by 1 return old_this } as old_this is just a local variable, the reference of it i...
3,072,444
3,072,551
Long long int on 32 bit machines
very simple question, I read that GCC supports long long int type. But how can make math operations with it, when CPU is 32 bit wide only?
The compiler will synthesize math operations (or use function calls) that use more than one CPU instruction to perform the operation. For example, an add operation will add the low order components (the low words) of the long long values and will then take the carry out of that operation and feed it into an add operat...
3,072,464
3,072,604
Displaying Unicode/ASCII Characters on console or window
I couldn't display a 'bullet' of character code DEC 149 which can be found on ASCII Chart. cout << char(149) << endl; it comes out as ò on console window. I know a few characters from charmap that I'd like to use but how would i know their character codes?
The problem is that ASCII only defines character codes 0 through 127. If you want to use codes above that, then you need to specify an ANSI code page. The chart you referenced is using the Latin-1 code page and your console is apparently using something else. You need to set your console code page to Latin-1 for your...
3,072,795
3,072,840
How to count lines of a file in C++?
How can I count lines using the standard classes, fstream and ifstream?
How about this :- std::ifstream inFile("file"); std::count(std::istreambuf_iterator<char>(inFile), std::istreambuf_iterator<char>(), '\n');
3,072,912
3,073,041
boost::this_thread::sleep() vs. nanosleep()?
I recently came across the need to sleep the current thread for an exact period of time. I know of two methods of doing so on a POSIX platform: using nanosleep() or using boost::this_thread::sleep(). Out of curiosity more than anything else, I was wondering what the differences are between the two approaches. Is ther...
The few reasons why use boost that I can think of: boost::this_thread::sleep() is an interruption point in boost.thread boost::this_thread::sleep() can be drop-in replaced by C++0x's std::this_thread::sleep_until() in future For why not -- if you're not using threads at all, or of everything else in your project uses...
3,073,303
3,073,311
Have to use C# dll to call C++ dll?
Do I have to create a C# DLL to call C++ DLL or I can call it directly from my C# application?
You can call it directly with PInvoke and the DllImport attribute. Assuming, of course, that it has standard C entry points, not compiler-specific C++ entry points. Unless you were talking about C++/CLI, in which case you would reference the .NET DLL exactly as you would reference any other .NET DLL.
3,073,418
3,073,456
Capture stdin input without echoing characters to screen
I have a very simple code: char character; std::cin >> character; However, I would like it to behave as follow: Don't echo to console the character I type std::cin should return (unblock) right away when a character is pressed without having to press the Enter key Is this possible? I also have access to Qt.
This is going to be platform dependent, but you can use getch() which is part of conio.h if you're on windows or getch() as part of curses.h if you're on *nix References http://opengroup.org/onlinepubs/007908799/xcurses/curses.h.html http://en.wikipedia.org/wiki/Conio.h
3,073,466
3,073,494
Dynamic creating of typedef
I'm creating event system. It's based under boost::signals. To make the work easier I'm using typedef for the function signatures. Everything is okey until I need creating of some new event trought event's system method. I have to create the typedef dynamically on given type to the template function. The problem is the...
typedefs only matter during compilation. As far as I know it's just an alias for a type.
3,073,563
3,088,126
Creating an Ctablctrl on a CFrameWnd
I want to create a mfc window that has tabs on top. I cannot find a good tutorial or example of this. Can someone give me a link to a good tutorial of example? please help me.
Install the Visual C++ Feature Pack. It comes with newer libraries to do this.
3,073,642
3,073,656
Official C++ language subsets
I mainly use C++ to do scientific computing, and lately I've been restricting myself to a very C-like subset of C++ features; namely, no classes/inheritance except complex and STL, templates only used for find/replace kinds of substitutions, and a few other things I can't put in words off the top of my head. I am wonde...
There is Embedded C++. It sounds mostly similar to what you're looking for.
3,073,753
3,073,810
How can I extract the domain from a URL?
I'm currently making a few changes in the rTorrent source. I have the following code: torrent::Object apply_to_domain(const torrent::Object& rawArgs) { const char * url = rawArgs.as_string().c_str(); char buffer[50]; snprintf(buffer, 50, "URL: %s.", url); return std::string(buffer); } I need to extract the doma...
The only thing that "regex" implementation handles is the wildcard character, *. (BTW, I'm just assuming it's a wildcard, since it's the only character that's recognised and the comments seem to hint as much, but I haven't actually verified it.) Use a proper regex library like Boost.Regex.
3,073,844
3,073,879
Horizontal mouse wheel event? (WinAPI)
Some laptops have a trackpad that can do horizontal scrolling as well as vertical (WM_MOUSEWHEEL), and some desktop mice have ability to tilt their wheels. How can I handle horizontal scrolling from a trackpad or mouse wheel?
WM_MOUSEHWHEEL is sent to the active window when the mouse's horizontal scroll wheel is tilted or rotated, and is also useful for horizontal scrolling from a trackpad's horizontal scrolling control
3,073,965
3,074,042
Specifying test dependencies in CppUnit?
I would like to specify the order of testing in CppUnit. According to my research, the testing order depends on either the compiler or linker and how they came across the files. How does one specify dependencies in CppUnit? For example, let us consider a rectangle class that has four lines. Each line contains two p...
What you're trying to do isn't really unit testing. "Pure" unit testing is intended to test individual units (individual classes), using mocks or fake objects in the place of real dependencies; once you're testing classes' dependencies on each other, that's integration testing, not unit testing. With that disclaimer o...
3,074,202
3,078,208
Can read(2) return zero when not at EOF?
According to the man page for read(2), it only returns zero when EOF is reached. However, It appears this is incorrect and that it may sometimes return zero, perhaps because the file is not ready to be read yet? Should I call select() to see if it is ready before reading a file from disk? Note that nBytes is: 1,445,88...
Figured it out! I had an Uninitialized Memory Read (UMR) and was incorrectly seeking to the end of the file.
3,074,290
3,074,319
How do I get the regex matched value using Boost.Regex?
I'm trying to extract the domain from a URL. Following is an example script. #include <iostream> #include <string> #include <boost/regex.hpp> int main () { std::string url = "http://mydomain.com/randompage.php"; boost::regex exp("^https?://([^/]*?)/"); std::cout << regex_search(url,exp); } How do I print the ...
You need to use the overload of regex_search that takes a match_results object. In your case: #include <iostream> #include <string> #include <boost/regex.hpp> int main () { std::string url = "http://mydomain.com/randompage.php"; boost::regex exp("^https?://([^/]*?)/"); boost::smatch match; if (boost::rege...
3,074,376
3,076,489
How to fix file path case?
I have a set of local paths, and some of them are capitalized (C:\SOMEDIR\SOMEFILE.TXT). I need to convert them to their real names (as shown in Explorer). Suggest a way plz.
Are you looking for that: short names vs. long name? Note that Explorer applies some tricky conversions to the file names. You easiest shot is to test it all and make your own function for the purpose. Otherwise, you can try to access via OLE the Explorer's functions to list files in directory. But that is VERY painful...
3,074,416
3,074,421
Is g++ on cygwin any different from what I get on Linux platform?
Can I start installing boost libraries, ACE framework and use it as my home Linux server?
The G++ on Cygwin is very similar to that on any other platform. You should be able to use it with Boost if you can't find the Boost libraries you want pre-compiled for Cygwin. However, Cygwin is not Linux; you won't be able to use it as your 'home Linux server'. Cygwin gives a Linux-like interface to Windows, but it...
3,074,456
3,074,479
Collision detection in STL's hash_map
I have to create a lookup table for C function names (as keys) to function pointers (as values). I am thinking of using STL's hash_map container, as the access time of a hash table is O(1). Is there any good hash function for this? Currently I am using (31*H + c) as my hash function. Also, does STL's hash_map takes car...
Assuming you've got the full STL, it actually includes a hash function, hash<T>, which in its included form is suitable for a few different key types including char* (C strings). I don't know details of its performance, but the STL is generally engineered to have acceptable performance for most applications. As for col...
3,074,518
3,074,542
Why am I able to create a copy constructor and overload the assignment operator for a QObject subclass?
I was under the impression that QObject disabled the copy constructor and assignment operator... why am I able to compile this QObject derivative containing both of these? #ifndef QVERSION_H #define QVERSION_H #include "silverlocklib_global.h" #include <QtCore> struct SILVERLOCKLIBSHARED_EXPORT QVersion : public QObj...
A derived class can always declare it's own copy constructor and assignment operator. If the base class disables it by making it private and leaving it undefined the derived class can't call the base class' version in its own implementation of course, but it can still implement them.
3,074,643
3,074,649
What is the difference between pointer to function and pointer to WINAPI function?
I came accross a code snippet which detects whether app is running in x32 emulated environment on x64 PC here Generally I understand that code but there is one thing I don't get: 1) typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL); Why does WINAPI have to be there? Why is it so important to know that pointe...
WINAPI expands to __stdcall (in most cases -- you shouldn't rely on that calling convention specifically), which is a different calling convention than the default, __cdecl. The difference is that in __stdcall, the function called cleans the stack, while in __cdecl, the caller cleans the stack. __stdcall does not suppo...
3,074,646
3,074,654
how to catch unknown exception and print it
I have some program and everytime I run it, it throws exception and I don't know how to check what exactly it throws, so my question is, is it possible to catch exception and print it (I found rows which throws exception) thanks in advance
If it derives from std::exception you can catch by reference: try { // code that could cause exception } catch (const std::exception &exc) { // catch anything thrown within try block that derives from std::exception std::cerr << exc.what(); } But if the exception is some class that has is not derived from ...
3,074,738
3,074,777
Algorithms in C++ by Robert Sedgewick experiences
How good is this book for learning algorithm creation, based on experiences ?
Its a good book but this does not mean it is good for you - maybe you find it at google books so you can have a look in it.
3,074,776
3,074,785
how to convert char array to wchar_t array?
char cmd[40]; driver = FuncGetDrive(driver); sprintf_s(cmd, "%c:\\test.exe", driver); I cannot use cmd in sei.lpFile = cmad; so, how to convert char array to wchar_t array ?
From MSDN: #include <iostream> #include <stdlib.h> #include <string> using namespace std; using namespace System; int main() { char *orig = "Hello, World!"; cout << orig << " (char *)" << endl; // Convert to a wchar_t* size_t origsize = strlen(orig) + 1; const size_t newsize = 100; size_t con...
3,074,872
3,074,981
typedef and incomplete type
Recently I am having many problem with typedef and incomplete type when I changed certain containers, allocators in my code. What I had previously struct foo;//incomplete type. typedef std::vector<foo> all_foos; typedef all_foos::reference foo_ref; Though not completely not sure whether the above lines are legal, but ...
A type must be complete to be used in a standard container, or the behavior is undefined (§17​.4.3.6/2). So the only standard solution is to not make that typedef until the class is defined. I don't get what the intermediate container is for: struct foo;//incomplete type. typedef foo& foo_ref; In any case, you'll just...
3,075,049
3,075,077
Why do compilers allow string literals not to be const?
And where are literals in memory exactly? (see examples below) I cannot modify a literal, so it would supposedly be a const char*, although the compiler let me use a char* for it, I have no warnings even with most of the compiler flags. Whereas an implicit cast of a const char* type to a char* type gives me a warning, ...
The C standard does not forbid the modification of string literals. It just says that the behaviour is undefined if the attempt is made. According to the C99 rationale, there were people in the committee who wanted string literals to be modifiable, so the standard does not explicitly forbid it. Note that the situation ...
3,075,208
3,075,214
Calling base class method from derived constructor
class Base { public: Base() {} void Foo(int x) {...} }; class Derived : public Base { public: Derived(int args) { /* process args in some way */ Foo(result); } }; Is it allowed to call a method of the base class in the constructor of the derived class? I would imagine this is...
Is it allowed to call a method of the base class in the constructor of the derived class? Yes. Just watch out for virtual functions. If an class derived from Derived overrides a virtual function, while constructing Derived as a sub-object of that further derived class, the dynamic type always is Derived, so no virtua...
3,075,335
3,075,359
Creating effects in 3D game from scratch, using c++ and DirectX
So the title says it. I couldn't find any info on how actualy build effects into 3D game. I'll maybe stick to some engine later, but for understanding of this whole thing I would need to try it on my own for this time. I found a few about particle systems which may be the right way but any other connection between Dire...
First of all: particle effects are just one kind of effects, it's better you specify the word particle engine :p. Secondly: search int he articles of Gamedev, it's really the best resource if you want things like this. You can find lots of articles and even better, tons of links, and useful information on the discussio...
3,075,494
3,075,528
How to ensure class template argument is derived from particular class Foo?
Possible Duplicate: C++ class template of specific baseclass class Base { ... }; class Derived1 : public Base { ... }; class Derived2 : public Base { ... }; class Unrelated { ... }; I want to have a class template ClassTemplate that accepts as parameter only classes Derived1 and Derived2 but not Unrelated, so I ...
Use boost::is_base_of from Boost.TypeTraits: template<class T> class ClassTemplate { BOOST_STATIC_ASSERT((boost::is_base_of<Base, T>::value)); };
3,075,601
3,075,661
pointers to derived members of the class
if I have for example some class Base and derived from it Derived Also I have some list of shared pointers: list<shared_ptr<Base> > list I create shared pointer: line 5 shared_ptr<Derived> ptr(new Derived(//some constructor)); my question is, can I do something like this: list.push_back(ptr); if Yes, can somebod...
my question is, can I do something like this: list.push_back(ptr); Yes - your problem has nothing to do with inheritance or smart pointers - you simply don't have the constructor declared you are trying to use. A simple example that reproduces the error is: struct X {}; X x(1); Which gives you: no matching function...
3,075,697
3,859,694
"non-existent member function specified as friend" -?
I'm trying to compile CSSTidy with Visual Studio. The problem is that it throws error C2245: non-existent member function 'umap::erase' specified as friend (member function signature does not match any overload) pointing to the friend void umap<keyT,valT>::erase(const typename umap<keyT,valT>::iterator& it); which...
The fix, forward declare "class iterator;" at the top of class umap, and move the impl of "class iterator" to the bottom of class umap. The reason, MickySoft VS appears to have a deficiency that causes it not recognize umap::erase declared below the impl of umap::iterator. template <class keyT, class valT> class umap...
3,076,075
3,076,169
How to compile code generated by a Java or C++ App
I've been learning compiler theory and assembly and have managed to create a compiler that generates x86 assembly code. How can I take this assembly code and turn it into a .exe? Is there some magical API or tool I have to interact with? Or is it simpler than I think? I'm not really sure what's in a .exe, or how much a...
It looks like you need to spawn an assembler process and a linker process. On UNIX, it's as simple as invoking the fork() function, which would create a new process, and the exec() function, specifying the assembler and the linker executable names as the function's parameter, with suitable arguments to those executable...
3,076,163
3,076,722
STL Priority Queue - deleting an item
I want to implement a timer queuing system using the C++ STL priority_queue container adapter. My problem is that I want to occasionally cancel a timer, however there are no interfaces that enable me to easily delete an item in the priority_queue that is not the top item. Any suggestions?. Thank you for your help.
I had the exact same scenario once and did the following: the structure I kept in std::priority_queue contained only the time to sort by and an index to a std::vector<Handler> (in my case Handler was boost::function, but could as well be pointer to interface or function) when adding a timer, I'd find a free index in t...
3,076,206
3,077,033
enable_if and conversion operator?
Any chance to use enable_if with a type conversion operator? Seems tricky, since both return type and parameters list are implicit.
dixit the documentation: There does not seem to be a way to specify an enabler for a conversion operator. Converting constructors, however, can have enablers as extra default arguments.
3,076,243
3,076,261
problems with dynamic_cast
I have this snippet of the code: void addLineRelative(LineNumber number, LineNumber relativeNumber) { list<shared_ptr<Line> >::iterator i; findLine(i, number); if(i == listOfLines.end()){ throw "LineDoesNotExist"; } line 15 if(dynamic_cast<shared_...
shared_ptr does not implicitly convert to a pointer - it is a class-type object - and dynamic_cast, static_cast and const_cast all operate on pointers only. While you could use dynamic_cast on shared_ptr<T>::get(), its better to use dynamic_pointer_cast<FamilyLine>() instead as you might otherwise accidentally introduc...
3,076,343
3,076,392
Application settings with WinAPI
Is there any standard way to work with application settings in WinAPI? What I'm doing currently is this: if(!ReadKey(some_setting)) WriteKey(some_setting, some_setting_setting_default_value) when the settings dialog is initialized. Then I set the widget states to the corresponding values read from the registry. Th...
You could avoid writing hard-coded default values to the registry, and leave the registry empty except when it contains a non-default value: string ReadRegistry( const string& some_setting, const string& some_setting_default_value ) { //try to read user-specified setting from registry string rc; if (ReadKey...
3,076,395
3,076,408
does DEFINE Macro work on all platforms?
I am a newb and I am trying to better myself at good practice and design so consider this before reading the following. I am creating a singleton class, and I have quite a few static members. Instead of calling the members every time like this... THECLASS::member I was thinking about using a define macro to make it sh...
Your define won't work anywhere, actually. It should be: #define shortMember THECLASS::member And a good practice would be to not try to save keystrokes – readability is more important, and someone reading your code wants to see THECLASS::member, not shortMember, because then he knows where to look for a definition.
3,076,517
3,076,530
Good tutorial to create Win32 toolbar?
I want to add a toolbar and know which tool was clicked. I'd also like to be able to change the toolbar's buttons' bitmap after theyve been created MSDN is fairly breif on all of this. Thanks
You might want to check out these tutorials. Grz, Kris.
3,076,968
3,077,027
Converting a void* to a std::string
After perusing the web and messing around myself, I can't seem to convert a void*'s target (which is a string) to a std::string. I've tried using sprintf(buffer, "%p", *((int *)point)); as recommended by this page to get to a C string, but to no avail. And sadly, yes, I have to use a void*, as that's what SDL uses in t...
You just need to dynamically allocate it (because it probably needs to outlive the scope you're using it in), then cast it back and forth: // Cast a dynamically allocated string to 'void*'. void *vp = static_cast<void*>(new std::string("it's easy to break stuff like this!")); // Then, in the function that's using the ...
3,076,975
3,077,001
Weird c++ input escaping and space behavior
I'm having an unpleasant problem with my c++ example. Everything works fine until I enter something with a whitespace. #include <iostream> using namespace std; int main (int argc, char * const argv[]) { int iteration = 0; while (true) { char * input = new char[256]; scanf("%s", input); ...
First of all, never use scanf. It's difficult to use that function and avoid buffer overflows. Replace input with a std::string, and read from std::cin. Both scanf("%s", input) and cin >> input will read one word, delimited by whitespace. If you want to read a whole line, then use getline(cin, input).
3,077,013
3,077,031
Game Development: Should I program my levels or interpret them from a file?
The game will be written in C++ Programming: enemies.puch_back(new DefaultEnemy(200, 300, 3, 5)); enemies.puch_back(new DefaultEnemy(500, 400, 4, 5)); enemies.puch_back(new DefaultEnemy(300, 420, 3, 15)); enemies.at(2).createAward(new Key(4), "pling.wav"); Or Interpret them from a file like this: DefaultEnemy 200 300 ...
First variant is equivalent to hardcoding game resources. This is absolutely bad and is suitable only for debugging. Every games store their resources in external files - xml, archived packages and parse and load them during runtime. Therefore, modern game engines almost every time have their set of tools which is bund...
3,077,135
3,077,138
Type requirements for std::list
I've got a type that can't be moved or copied (by making the necessary constructors and operators private). But when I tried to compile a std::list of them, the operation failed with a very strange error (class name snipped for brevity). 1>C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\xmemory(202) : er...
As of C++03, elements must be copy constructible and copy assignable. §23.1/3: The type of objects stored in these components must meet the requirements of CopyConstructible types (20.1.3), and the additional requirements of Assignable types. In C++0x, requirements are put on a per-operation basis, but in general it'...
3,077,184
3,077,190
Derived classes and singleton
If I have two classes "A" and "B", is it OK to derive B from A and then make B a Singleton?. Thanks for your help.
Um, sure. Nobody is going to stop you. If it's okay to make "some class" a singleton*, just imagine B being a new "some class". (It just happens to be derived from A.) *Though, do you really need a singleton? (No.)
3,077,407
3,097,910
Sharing violation on file which really should be closed
I have an application that modifies an XML file by: (a) opening it, (b) creating a temporary file and writing a modified version to it, (c) closing both files, and (d) replacing the original file with the temporary file. When I test it on my laptop running Vista, everything works just as it should. On an embedded PC ru...
It seems to be a problem with file permissions. After trying various other things which didn't work, I decided to try opening the file with read/write permissions (i.e with the "r+" attribute rather than "r"), and then overwriting the original file contents with the contents of the temporary file. This time, the "_wfop...
3,077,428
3,077,484
Have you ever crashed a debugger?
Recently I was debugging a project and the debugger (GDB 7.1) crashed all of a sudden, because of an endless recursion while trying to print a graph structure. At first I couldn't even imagine that a debugger could crash (a stable version) but it had. So it's really interesting to me, have you ever crashed a debugger?
Yes. My coworkers and I were debugging a nasty concurrency bug. It crashed GDB, so we ran our program under GDB under GDB and eventually found the problem. It was so meta ;)
3,077,450
3,077,464
Viewing data in memory window
why can't I see the variable 'x' in memory window of VS2005 while stepping the code using debugger? int main() { char *c = "String"; //visible char x = 'a'; // not visible }
Both are visible in the memory window. For example in the memory window in the address field type &x and then you will see the character code of the char in hex. For example if you have: char x = 'x'; Then in the memory window you type &x you will see the number 0x78 which is in base10 the number 120. assert('x...
3,077,634
3,077,681
error when compiling c++ code with g++
i get error of this type: "in function ... multiple definition of ..." "... first defined here" "warning: size of symbol ... changed from to in " *the code is compiled with the flags: -ansi -Wall -pedantic-errors -Werror *STL is used is there any explanation for that? thank you in advance
Explanation? The error message you quoted is already an explanation as exhaustive as it can ever get. Something (a variable) is defined more than once in the same scope. The compiler gave you the name of the offending variable. The compiler reported the error at the second definition and supplied an additional message ...
3,077,748
3,077,767
is std::vector same as array[number]?
Possible Duplicate: Are std::vector elements guaranteed to be contiguous? does std::vector always contain the data in sequential memory addresses as array[number]?
For all types except bool, the standard requires the elements are contiguous in memory: 23.2.4/1 ... The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size() Do keep in mind that std::v...
3,077,769
3,078,087
How do I open a Open File dialog in OS X using C++?
I'm working on an application using OpenGL and C++ that parses some structured input from a file and displays it graphically. I'd like to start an Open File dialog when the application loads to allow the user to choose the file they want to have displayed. I haven't been able to find what I need on the web. Is there a ...
You have two choices, a quick one, and a good one: Quick and pretty simple, use the Navigation Services framework from Carbon and NavCreateGetFileDialog(). You'll be done quick, and you'll have to learn almost nothing new, but your code won't run in 64-bit (which Apple is pushing everyone towards) and you'll have to l...
3,077,850
3,077,852
Any way to determine if class implements operator()
I'm trying to find is there's a way to check if a class is a functional because i want to write a template which uses it? Is there an easy way to do this? Or do I just wrap things in a try/catch? Or perhaps the compiler won't even let me do it?
If you have a function template written like: template <typename T> void f(T x) { x(); } you will be unable to instantiate it with any type that is not callable as a function taking no arguments (e.g., a class type that overloads operator() taking no arguments is callable as a function that takes no argument...
3,078,012
3,078,021
Implementing custom STL-like data structures
I have already implemented and tested the data structure and would now like to make it compatible with the collection of STL algorithms. Guidelines for implementing a custom iterator and the like. Specifically: What is the minimum set of operations that must be supported? (e.g. ++, +=, ==, !=?) Are there any propertie...
You should consult the SGI STL documentation. It has detailed requirements for each of the STL components, including containers and iterators. Effectively, for iterators, there are various types--input iterators, output iterators, forward iterators, bidirectional iterators, and random-access iterators. The specificat...
3,078,019
3,078,057
Why doesn't this C++ code work?
int Socket::Connect(const std::string& host, int port) { if(this->_connected) throw "Socket is already connected"; // Get the IP from the string hostent* ip = gethostbyname(host.c_str()); /*if(server == NULL) throw strerror(WSAGetLastError());*/ // Information for WinSock. s...
strerror() returns a char* on windows so you need a catch(char* error)
3,078,053
3,078,086
Trying to use STL without smart pointers - trying to avoid temporary object creation
I particularly like the simplicity of using STL containers in the straightforward way. I have never really figured out how to get the Boost library working on my dev platforms, in fact I don't think I've even tried. I guess you could say I am just trying to delay the inevitable since Boost is clearly a helpful library...
Inserting an object into a container invokes the copy constructor on that object. There's really no way around that (yet), hence why pointer containers are used for large objects: it's dirt cheap to copy a pointer. If you choose to use a container of smart pointers, you can either use one of the Boost pointer contain...
3,078,077
3,078,784
How to iterate through a sequence of bounded types with Boost.Variant
struct A { std::string get_string(); }; struct B { int value; }; typedef boost::variant<A,B> var_types; std::vector<var_types> v; A a; B b; v.push_back(a); v.push_back(b); How can I iterate iterate through the elements of v to get access to the a and b objects ? I'm able to do it ...
Edit: If it's as UncleBens suggests, then you can simply do this: BOOST_FOREACH(var_types& vt, v) { if (vt.which() == 0) cout << get<A>(vt).get_string() << endl; } Original: The template parameter for static_vistor is the return type of its methods. This means the two classes need to share a common retu...
3,078,148
3,078,303
Controlling output of program
I'm writing a code to output fibonacci series in C++, which is simple enough, but since I'm new to programming, I'm considering ways to control I was wondering if there's a way to control time for when outputs come out without processing time being included (e.g. If it takes .0005 seconds to process my input and I want...
If you're on Windows, a quick way to pause is to call system("pause"); This isn't a very professional way of doing things, however. A way to pause with the std namespace would be something like this: cout << "Press Enter to continue . . ." << endl; cin.ignore(numeric_limits<streamsize>::max(), '\n'); As for your main...
3,078,162
3,078,206
Parsing a grammar with Boost Spirit
I am trying to parse a C-function like tree expressions like the following (using the Spirit Parser Framework): F( A() , B( GREAT( SOME , NOT ) ) , C( YES ) ) For this I am trying to use the three rules on the following grammar: template< typename Iterator , typename ExpressionAST > struct InputGrammar : qi::grammar<I...
As far as debugging, its possible to use a normal break and watch approach. This is made difficult by how you've formatted the rules though. If you format per the spirit examples (~one parser per line, one phoenix statement per line), break points will be much more informative. Your data structure doesn't have a way ...
3,078,185
3,078,296
What can glStencil do?
I'm wondering what the stencil buffer is and what it can do.
http://en.wikipedia.org/wiki/Stencil_buffer Basically, the stencil buffers allows you to draw only in parts "marked" in the stencil buffer, rejecting pixels where this "mark" doesn't have certain value. Is used to clip rendering in non-rectangular shapes, and to do shadow volumes.
3,078,237
3,078,241
Defining volatile class object
Can the volatile be used for class objects? Like: volatile Myclass className; The problem is that it doesn't compile, everywhere when some method is invoked, the error says: error C2662: 'function' : cannot convert 'this' pointer from 'volatile MyClass' to 'MyCLass &' What is the problem here and how to solve it? EDIT...
Yes, you can, but then you can only call member functions that are declared volatile (just like the const keyword). For example: struct foo { void a() volatile; void b(); }; volatile foo f; f.a(); // ok f.b(); // not ok Edit based on your code: bool volatile push(struct Data element); declares a non-vo...
3,078,257
3,078,426
Access objective-c from c++
Can somebody point me in the right direction for this. I've found lots of info on using c++ in obj c but not the other way around. I am making an iPhone game in c++ but need to tap into some of the features the iPhone has to offer. Thanks
There's actually no difference between "using C++ in Objective-C" and "using Objective-C in C++" - they're both actually using Objective-C++ (which is a distinct language). Just make sure that you're compiling the source file as Objective-C++: either rename it with a .mm extension, or add the compiler flag -x objective...
3,078,316
3,078,478
Static Linking Function in a DLL Project
I don't know why but I thought I could statically link a function from an Import Library. It would seem I am the only one who has ever tried because I can't for the life of me find a similar post. Is there a way to selectively static link functions from a dynamically linked project without creating a new project and/...
If this is your own project (or you have source code and are willing to modify it), you could use inline functions for the functions you don't want to dynamically link.
3,078,469
3,078,473
C++: overloading mathematical operators
I am looking to overload, let's say, the addition operator and have it add two objects of the same class. When I declare this "operator+" prototype function in the class declaration in the header file, I pass in both objects as parameters. I get a compiler error saying that "binary 'operator +' has too many parameter...
If you declare oparator+ as an instance function then the first argument is being passed as this object and thus you need only one more argument. Read this for more info, in particular try to understand the const concept: http://www.cs.caltech.edu/courses/cs11/material/cpp/donnie/cpp-ops.html The best approach as advis...
3,078,486
13,480,142
How to Create a webservice by Qt
I am looking for a tool or plugin that help me to create web service as DOT NET does for Linux.
From the OP Edit in question: After search, I found that Qt does not have any thing to write web services gSOAP is an Open Source Solution for this problem, currently we use it.
3,078,602
3,078,616
C++: How to add external libraries
I'm trying to add SVL to my project. Without it I'm getting hundreds of errors (undefined reference...). After adding -lSVL all errors are gone, but gcc says: "cannot find -lSVL". Everything else (SDL, SDL_TTF, SDL_Mixer...) works fine.
You should inform gcc of the path where libsvl.a is installed, for example: gcc -lsvl -L/my/path/ Also, pay attention to the case if you work under Linux ("SVL" is different from "svl").
3,078,742
3,078,856
C++: Difference between NVI and Template Method Patterns?
What is the difference between NVI ( Non-Virtual Interface ) and the Template Method patterns? They seem very similar and I've read both that they're basically the same and that they're subtly different with Template being somehow more general.
NVI is an idiom, Template Method is a pattern. NVI is an implementation of the Template Method Pattern using dynamic dispatch in C++; it is also possible to create template methods in C++ using template metaprogramming to eliminate the dynamic dispatch. A pattern is more general than an idiom, and languages may use di...
3,078,851
3,078,881
C++, get the name of the function
In C++, is there a way to get the function signature/name from it's pointer like this? void test(float data) {} cout << typeid(&test).name(); I want to use this data for logging.
If you just want to log the current function name, most of the compilers have __FUNCTION__ macro, which will give you the current function name at compile time. You may also look for stack walking techniques (here is an example for Windows), which can provide you more information about the current call stack and functi...
3,078,897
3,078,910
unsigned _stdcall.... implicitly an int?
A function with this signature: unsigned _stdcall somefunction (LPVOID lParam); does it mean that it implicitly returns an integer? As unsigned really isn't a value by itself? And _stdcall is a calling convention....
unsigned is a shortcut for unsigned int, so this function returns an unsigned integer.
3,078,998
3,079,127
c++ must delete a references?
in the following code: class x { private: someRef& m_ref; public: x(someRef& someRef):m_ref(someRef) { } do I need to do: ~x() { delete m_ref; } which by the way doesnt work without getting the pointer... basically I'm asking: Do I need to call a destructor on a reference member?
No. You can only delete pointers, not references, and even then you must only delete objects that you allocated using the new operator. And then you must be sure to delete them only once. Here is the case in which you would need to use delete in your destructor: class x { private: someObj* m_ptr; public: x():m_ptr(n...
3,079,067
3,079,078
Size of empty class and empty function?
What will be solution in the following code Class A{} void func(){} printf("%d,%d",sizeof(A),sizeof(func));
Size of an empty class is non zero(most probably 1), so as to have two objects of the class at different addresses. http://www2.research.att.com/~bs/bs_faq2.html#sizeof-empty explains it better class A{}; void func(){} std::cout<<sizeof(A)<<std::endl<<sizeof(&func));// prints 1 and 4 on my 32 bit system
3,079,104
3,079,285
Getting shared_ptr to call a member function once its reference count reaches 0
I'm creating a wrapper for a HANDLE that does not work with DuplicateHandle, so instead I am trying to wrap the handle in a shared_ptr. Imagine the following code: class CWrapper { public: CWrapper() : m_pHandle(new HANDLE, &CWrapper::Close) { //code to open handle } private: void Close...
I think you have your abstractions the wrong way around. shared_ptr gives you a copyable "handle" to a shared resource that can't itself be copied. Using shared_ptr with a type that doesn't perform its own cleanup when it is deleted isn't an optimal use. If make your class' single responsibility to clean up this inhere...
3,079,299
3,079,304
why can I not get access to my DLL function
I'm trying to load a DLL dynamically using LoadLibrary(), which works, however I cannot then get the address of the function in the DLL that I'm trying to call. DLL function: (in CPP file) _declspec(dllexport) void MyDllFunc() { printf("Hello from DLL"); } Calling code: typedef void (*MyDllFuncPtr)(); int _tmain(...
Write extern "C" _declspec(dllexport) void MyDllFunc()
3,079,366
3,079,741
2D OpenGL scene slows down with lots of overlapping shapes
I'm drawing 2D shapes with OpenGL. They aren't using that many polygons. I notice that I can have lots and lots of shapes as long as they don't overlap. If I get a shape behind a shape behind.... etc.. it really starts lagging. I feel like I might be doing something wrong. Is this normal and is there a way to fix this ...
Are your two cases (overlapping and non-overlapping) using the exact same set of shapes? Because if the overlapping case involves a total area of all your shapes that is larger than the first case, then it would be expected to be slower. If it's the same set of shapes that slows down if some of them overlap, then tha...