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
5,754,239
5,754,314
C++ What can I use instead sleep() function?
I'm building scrobbler, and I want my program to wait 10 seconds after song change, before scrobbling. I have been using sleep but I realized that if song change during these 10 seconds, program submit old song and get new one. I want If I change song, code start all over again. I'm using Music Player Daemon (MPD) and...
It depens a lot on how your program works, but in principle, the easiest way would be to keep using sleep and check whether the user changed the song before sending out that data (after sleep has returned). So, instead of "try to sleep better", the goal would be "check that the data you send is really valid before send...
5,754,315
5,754,417
C convert char[] to timestamp;
I have char date[] = "2011-04-01"; How it convert to timestamp in C or C++ ?
Try this: char date[] = "2011-04-01"; date[4] = date[7] = '\0'; struct tm tmdate = {0}; tmdate.tm_year = atoi(&date[0]) - 1900; tmdate.tm_mon = atoi(&date[5]) - 1; tmdate.tm_mday = atoi(&date[8]); time_t t = mktime( &tmdate );
5,754,577
5,757,017
how to run same jar file multiple times by forking new child process every time?
i am trying to write a c++ program. the program is required to run some jar files, run every jar file two times. the problem is that the program runs every file just one time correctly. at the second time i got an error message, as if the VM got a wrong command. However, it is the same command that run the jar files th...
strtok() changes your string when you call it. You set the pointer "commands" to either checkers_command or castle_command but strtok is just going to overwrite the memory pointed to at each of the latter. If you copy checkers/castle rather than just point to it before calling your parse function you will have a fres...
5,754,660
5,754,942
Disallow a specific function template instantiation
I would like to define a template function but disallow instantiation with a particular type. Note that in general all types are allowed and the generic template works, I just want to disallow using a few specific types. For example, in the code below I wish to prevent using double with the template. This doesn't actua...
I would use a static assert within your function call to create the proper failure during function instantiation: template<typename T> class is_double{ static const int value = false; } template<> class is_double<double>{ static const int value = true; } template<typename T> T convert( const char *argument ){ BOO...
5,754,679
5,755,380
How to stretch a bitmap image to some specific Co Ordinates using WIN32 core and VC++?
I just want to create a program which crops an image and sends the cropped image to some remote location. I have loaded the image using BitBlt(). I dont know, How to uniformly display all the images ? all of same size. stretching is allowed. I have created a static control and now I want to display all the images insi...
You might want to try using StretchBlt() instead of BitBlt(). It allows you to specify the source and destination rectangles which will crop and stretch the image. http://msdn.microsoft.com/en-us/library/dd145120(v=vs.85).aspx
5,755,238
5,755,296
How to check if parameter passed to Lua is of user defined type?
I am implementing scripting for my Ogre3d based application using Lua and I have encountered a problem with checking whether a parameter fed into function is of particular type - Ogre::SceneNode*. Anybody knows how can I do it ? There are some basic Lua functions doing this for built in types like int or string e.g. if...
I guess lua_isuserdata(L, yourParam) ? Would be logical.
5,755,265
5,755,351
How to set source address when sending using and UDP socket
I've two pc using VRRP for redundancy. So every PC (Linux) has a physical and a Virtual IP address. I've a software (C++) with a client/server architecture with UDP protocol. The software bind the listen socket on "0.0.0.0" and use a new socket every time it needs to send some data to the other party. With wireshark I ...
When the kernel needs to send something through a socket it performs these steps if the socket is bound, use that source address is the socket is not bound, it looks around for interfaces and selects a source address So you need to bind(2) your socket to your desired address. For more information: "Source Address Sel...
5,755,412
5,756,096
ShellExecute using an URL is resulting in unassociated error message. Which file association is missing?
I am using "ShellExec" in c++ and windows to open an url in the default browser. For very few customers it is failing with the following message:"This file does not have a program associated with it for performing this action". I understand that this means that the "http" file type association is missing or invalid i...
You are not telling what action you want to perform. In this case, the action you want is open. ShellExecute(0, "open", "http://www.website.com/function?key=9271", 0, 0, SW_SHOWNORMAL); With ShellExecuteEx, it means you would add : execInfo.lpVerb = "open"
5,755,622
5,759,455
parsing an XMPP stream with libxml2
I'm a beginner when it comes to libxml2, so here is my question: I'm working at a small XMPP client. I have a stream that I receive from the network, the received buffer is fed into my Parser class, chunk by chunk, as the data is received. I may receive incomplete fragments of XML data: <stream><presence from='user1@do...
You probably want a push parser using xmlCreatePushParserCtxt and xmlParseChunk. Even better would be to choose one of the existing open source C libraries for XMPP. For example, here is the code from libstrophe that does what you want already.
5,755,627
5,768,284
What type of multithreading would be best to learn?
I want to learn multi-threading in C++ but I'm not sure what type would be most useful. The ones I've seen tutorials on are: Windows native calls OpenMP Boost (I'm sure that there are probably more.) What is each one's key features and what are they best used for? Note: I've already done some multi-threading in C# by...
How about TBB? It is portable and has easy to use parallel template patterns, concurrent containers, task scheduler and scalable memory allocaturs. TBB will let you manage threads directly, but that is not necessary in most of the cases. Personally I would stay away from platform specific threads, unless there an urge...
5,755,630
5,764,858
What happens if I didn't call delete operator after allocating data using new and ending program?
What happens if I didn't call delete operator after allocating data using new. I know that the data that has been allocatted, won't be available until releasing it, but after ending the program ? Why the PC seems to have nausea xD, i mean that it is very slow but after a while its performance become better but not like...
I think you're seeing the effects of evicting useful programs from main memory to the disk. Your intentionally-leaky program is trying to allocate all memory on the system. To satisfy your program's demand, Windows is finding other programs on the system, writing their memory to the page file, and reallocating their m...
5,755,845
5,756,377
Passing lambda with parameter
I would like to pass a lambda to a funciton. This boost::function<void()> fncPtr(boost::bind<void>([](){/* something */})); works, but if the lambda had a parameter, I don't know how to do it properly: boost::function<void(bool)> fncPtr(boost::bind<void,bool>([](bool){/* something */}, _1)); does not work. Where I a...
You have a problem in the compiler probably. I have an error in Visual Studio 2010 too. You can help compiler to convert a lambda to a function using helper function: template <typename T> void closureToFunction(bool x){ T f; return f(x); } int main() { auto exp = [](bool x){/* something */}; boost::function<v...
5,755,904
5,757,283
h264 syntax (P frames syntax details)
I'm parsing h264 NAL Units. In my sequence - there are NAL Units with picture parameters set, sequence parameters set, I frames (they are also IDR) and P frames (I and P frames consits of single slice). (No B frames at all) So I have the stream of NAL Units looks like: [SPS] [PPS] [I(IDR)] [P] [P] [P] ... [P] [P] [SPS]...
It looks like you have interlaced data. With interlaced data, one frame is composed of two fields. The other field of each frame will have the odd values for pic_order_cnt_lsb. pic_order_cnt_lsb is just the least significant bits of a counter tracking the order of the pictures. If (as in typical interlaced data) you ha...
5,755,931
5,756,027
Open declaration feature in VI
I'm a vi user for coding in Python. I love it: powerful, lowlevel, minimal gui without useless buttons, etc. Now I'm approaching C++ with an opensource project that—as usual happened in opensource project—has poor documentation and sometimes (well, a lot of times) I have to open declaration and implementation and see w...
Vim doesn't offer a feature like that by itself. A rudimentary way would be to use gd in command mode. If you want more sophisticated support, take a look at ctags and cscope. Those tools offer which you ask for and integrate nicely into Vim. A quick google search brought me to this link, which explains how to use csco...
5,756,127
5,760,949
What is WSAAsyncSelect() function analogue in Apple GCC?
Please tell me the most painless way of porting WSAAsyncSelect() function to GCC...
While select() and pselect() may work for your application, they are very much not the same thing as WSAAsyncSelect(). Those functions let you do controlled blocking on an otherwise non-blocking socket, or collection of sockets. The same goes for poll(). Winsock's asynchronous sockets, on the other hand, do not block, ...
5,756,169
5,756,213
Conversion from built in types to Custom Classes
I have a custom class that acts as an int called Integer, I would like to tell compiler how to convert certain types to Integer automatically so that I can avoid typing same thing over and over again, someCall(Integer(1), Integer(2)); would become someCall(1,2); I've googled but all I could find is to do the oposite,...
Write a constructor that takes int, as: class Integer { public: Integer(int); }; If the class Integer has this constructor, then you can do this: void f(Integer); f(Integer(1)); //okay f(1); //this is also okay! The explanation is that when you write f(1), then the constructor of Integer that tak...
5,756,304
5,756,378
"noexcept" vs "Throws: nothing"
While going through the last edits of the C++0x Working draft I found a lot of removal of the keyword noexcept addition of textual Throws: nothing at the same place and vice versa. Just some examples: replacement of noexcept against Throws: nothing: 20.6.4 Pointer safety [util.dynamic.safety] template<class T> T*und...
In Madrid we were strongly influenced by N3279 which includes the following guidelines: Adopted Guidelines No library destructor should throw. They shall use the implicitly supplied (non- throwing) exception specification. Each library function having a wide contract, that the LWG agree cannot throw, should be marked ...
5,756,792
5,757,542
Locality and shared access to objects
Profiling my code, i see a lot of cache misses and would like to know whether there is a way to improve the situation. Optimization is not really needed, I'm more curious about whether there exist general approaches to this problem (this is a follow up question). // class to compute stuff class A { double compute()...
Unfortunately, I'm not sure if I'm understanding your question correctly, but I'll try to answer. Cache misses are caused by the processor requiring data that is scattered all over memory. One very common way of increasing cache hits is just organizing your data so that everything that is accessed sequentially is in th...
5,756,796
5,757,078
boost regex tokenizer and newline
I'm currently trying to split up a text file into a vector of strings whenever a newline is encountered. Previously I have used boost tokenizer to do this with other delimiter characters but when I use the newline '\n' it throws an exception at runtime: terminate called after throwing an instance of 'boost::escaped_lis...
escaped_list_separator's constructor expects the escape character, then the delimiter character, then the quote character. By using a newline as your escape character, its treating the first character in every line in your input as part of an escape sequence. Try this instead. escaped_list_separator<char>('\\', '\n') h...
5,756,813
5,757,048
Simple but fast IPC method for a Python and C++ application?
I have a GNU Radio application which utilizes both Python and C++ code. I want to be able to signal the C++ code of an event. If they were in the same scope I would normally use a simple boolean, but the code is separate to the point where some form of shared memory is required. The code in question is performance-crit...
Assuming this is two separate applications on one machine and you need decent real time performance you don't want to go with sockets. I would use a flag in shared memory, and probably use a semaphore to make sure both programs can't be accessing the flag at once. This library provides access to the semaphores and shar...
5,756,832
5,756,873
Temporary and expression behavior
Is this well defined behavior? const char* p = (std::string("Hello") + std::string("World")).c_str(); std::cout << p; I am not sure. Reasons?
No, this is undefined behavior. Both std::string temporaries and the temporary returned by operator+ only live until the end of the initialization of your const char* (end of full expression). Then they are destroyed and p points to uncertain memory.
5,757,037
5,757,124
Unresolved external symbols in Visual Studio 2010
I am coming from Xcode, trying to compile a project in Visual Studio 2010, and I get the following errors: 2>ofxCLeye.obj : error LNK2019: unresolved external symbol "struct _GUID __cdecl CLEyeGetCameraUUID(int)" (?CLEyeGetCameraUUID@@YA?AU_GUID@@H@Z) referenced in function "public: static int __cdecl ofxCLeye::listDev...
Apologies if this is overly pedantic. If this is a pre-built library (not built as part of the project/solution) then make sure you a) #include the correct header b) #define any requisite macros c) speciy additional .lib dependencies as shown below. You will need to specify a fully qualifed path (d:\src\project\libs...
5,757,213
5,757,249
Why can't we return anything from the constructor?
C++ says that we can't return anything from the constructor? What is the historical reason behind it? Why did Bjarne disallow contructors to return something unlike any other member function?
Because when an object is being constructed in a new statement or in a variable initializer, the object that is returned is that new object which is being constructed. What would you ever do with an object returned from a constructor? It couldn't ever be returned anywhere; it's the object being constructed that is retu...
5,757,282
5,757,602
Expression transformation problem
Let's say we have the following statement: s = 3 * a * b - 2 * c, where s, a, b and c are variables. Also, we used Shunting Yard algorithm to build RPN expression, so now we can assign values to variables a, b and c and calculate s value by using simple RPN evaluator. But, the problem is that I should be able to calcul...
See this first: Postfix notation to expression tree to convert your RPN into a tree. Once you have the equation left expression = right expression change this to left expression - right expression = 0 and create a tree of left expression - right expression via Shunting Yard and the above answer. Thus when you evaluate...
5,757,285
5,757,529
opengl rendering half a cylinder
ok so im new to opengl and im creating a pool game using only the core opengl and glut i am writing in c++ i know how to draw a cylinder: { GLUquadric *quadric = gluNewQuadric(); glBegin; gluCylinder(quadric, 0.5f, 0.5f, 5.0f, 40, 40); glEnd(); } i want to know if i can half this cylinder so ...
The function gluCylinder is too specific to accomplish this. glu is built as a layer on top of opengl so you can always go to more low level drawing functions if the high level ones don't solve your problem. This tutorial should give you an introduction to some of the lower level drawing functionality in opengl: http:/...
5,757,294
5,757,361
CUDA textures and clamping
Is there any way to clamp out of range texture addresses to a certain value? In my case, I want them to be set to a simple zero, but the address mode I need doesn't seem to exist. Thanks. Edit: Any idea what the cudaAddressModeBorder setting does?
I don't think there's a way to specify the clamp but you can do the obvious and add a 1 pixel black (zero) border around the edge and offset your addressing by 1. It shouldn't be much more data and it'll get you the clamping for free. If you have a maximum size 2D texture (for CUDA 2.x it is 64k x 64k) with 16 bytes p...
5,757,523
5,758,411
File transfer using Sockets in C++
I wish to make a file transfer using sockets from client to server using C++ language... The code I have only transfers strings to client and server. How can I transfer files? Any help or reference materials would also help.
If a Winsock-specific solution is okay with you, take a look at the TransmitFile() function. Linux and Solaris both have a sendfile() function that perform in a similar way, although I believe Linux and Solaris have a slightly different sendfile() API. These functions provide the added benefit of not having to copy c...
5,757,540
5,757,975
How to Set custom text Color in QTextEdit?
I have resisted asking this seemingly n00b question, but all my recent effort to achieve this task have failed. Here are the things I have tried already, all have failed! Could it be that my OpenSuse 11.3 sets system-wide style settings that apply to even my Qt app by default? //I have some QTextEdit created in QDesign...
I've had success changing text color of QLabel and QPlainTextEdit by changing the Palette: QPalette pal; pal.setColor(QPalette::Window, bgColor); pal.setColor(QPalette::WindowText, fgColor); pal.setColor(QPalette::Text, fgColor); mylabel->setPalette(pal);
5,757,566
5,758,467
C++ Dynamic Library Compiling/Linking
I know that if I link my c++ program to a dynamic library (DLL) that was built with a different version of Visual Studio, it won't work because of the binary compatibility issue. (I have experienced this with Boost library and VS 2005 and 2008) But my question is: is this true for all versions of MSVS? Does this apply ...
Hi. I know that if I link my c++ program to a dynamic library (DLL) that was built with a different version of Visual Studio, it won't work because of the binary compatibility issue. (I have experienced this with Boost library and VS 2005 and 2008) I do not remember ever seeing MS changing the ABI, so technically dif...
5,757,720
5,757,758
What is wrong with this forward declaration
Several times I used the pimple idiom to get a short compilation time. To get a "good" header file I return a pointer of a vector that contains pointer of QPoint (an Qt-object). Lets have a look at my header file: #ifndef CHEXAGON_H #define CHEXAGON_H class QPoint; class QVector; class CHexagon { public: CHexagon...
QVector isn't a class, it is a class template and can't be declared as you did. template <typename T> QVector; and then using QVector<QPoint*> should do what you want.
5,757,721
5,757,851
use getline and while loop to split a string
for example i have a string: string s = "apple | orange | kiwi"; and i searched and there is a way: stringstream stream(s); string tok; getline(stream, tok, '|'); but it only can return the first token "apple" I wonder that is there any way so it can return an array of string? Thank you. Let assume that the string s ...
As Benjamin points out, you answered this question yourself in its title. #include <sstream> #include <vector> #include <string> int main() { // inputs std::string str("abc:def"); char split_char = ':'; // work std::istringstream split(str); std::vector<std::string> tokens; for (std::string each;...
5,757,993
5,758,093
Compiler optimization Duplicate Classes
I am using C++ as intermediate language, for each function object I am creating a unique class with a call method. What I am avoiding is checking if a similar function is already used and its corresponding class defined, so I may end up with exact same class with a different name. So I am wondering if compiler (g++) wi...
Just to clarify on both previous answers (which are good answers): The compiler will absolutely not merge your classes, at all. Some linkers might have some optimizations along those lines, but it's by no means a standard feature and neither the standard Microsoft nor GNU/Linux linkers do that. Usually the linker wil...
5,758,045
5,812,705
Boost-Build: Building windows executable from linux
I have a c++ codebase that I need to build both windows and unix versions of. It is important that the windows executable work without cygwin or similar installed. Oh, and I'm trying to achieve this from ubuntu. I've been trying to figure out how to make boost-build take care of it, but have so far come up short.. For ...
Unfortunately I don't think this can be done (I've failed many times) and I think the reason is because mingw is not suppported for compiling Boost. The only way people seem to have accomplished this is to maintain a separate build environment under win32 using MS Visual Studio. From your question it's unclear if you'...
5,758,256
5,758,702
Working on a solid Command Pattern with shared_ptr
I am trying to implement a very clean Command Pattern in a library. I have the following structure right now (a few parts are still being finished up): users (client-code) have some Object, call it "Manager" Manager holds a collection of shared_ptr<Foo> Manager provides access to the collection by returning shared_ptr...
Since it wouldn't make any sense to me otherwise, I'm going to assume that your library provides the Manager class (or at least a base class), and clients have to use that class to invoke a Command. In that case, maybe something like this could work: void Manager::execute(Command& cmd, shared_ptr<Foo const> const& ta...
5,759,039
5,759,049
Why does this program keep crashing
It crashes on execution: #include <iostream> int main () { if(main()); return 0; } Why?
It crashes due to Stackoverflow of course, since, there is no terminating condition, but technically the C++ Compiler is allowed not to compile it, since in C++: main() cannot be called from within a program. The address of main() cannot be taken. The main() function cannot be overloaded. What the standard says: Annex...
5,759,102
5,759,164
std::map, storing pointer (to object) by pointer (to some object's related struct). Which types to use?
To overcome the impossibility of giving C library a callback to C++ member function, wanted to implement something like this: SomeObject* findSomeObjectByHandlePointer(datahandle *dh) { }.. by using a map, which contains addresses of *datahandle as an index, and addresses of *SomeObject's as value. When SomeObject is ...
Normally, C-like callbacks take a void* user_data parameter, which allows you to pass in anything you want: void c_func(void (*fptr)(void*), void* user_data){ // do some stuff fptr(user_data); } Now, simply make the following static member function: class A{ public: static void c_callback(void* my_data){ A* ...
5,759,221
5,759,620
job interview question -data structures
Suppose I have set of files and in every files there are include# to other files in the same set.Suppose I have function that load all the includes in certain file.I need to write function that load all the includes in some given source file so I will avoid infinite loop and circular call for the include. To solve the ...
I think that you want to look at Topological sorting.
5,759,232
5,759,296
std::vector, default construction, C++11 and breaking changes
I ran today against a quite subtle issue I'd like to have your opinion on. Consider the following garden-variety shared-body-idiom class: struct S { S() : p_impl(new impl) {} private: struct impl; boost::shared_ptr<impl> p_impl; }; The fun appears when you try to put those into vectors in the following way...
Does the C++03 standard mandate that std::vector must have a constructor defined as above, i.e. with a default argument? In particular is there a guarantee that the entries of the vector object get copied instead of default constructed? Yes, the specified behavior is that x is copied n times so that the container i...
5,759,353
5,759,444
Is g++ both a c++ compiler and a linker?
I was looking at the output from my build in Eclipse. I'm cross compiling for a ColdFire processor. The compilation line looks like this: m68k-elf-g++ -O2 -falign-functions=4 -IC:\nburn\include -IC:\nburn\MOD52... followed by more include file, obvious "compiler" flags and finally the one source file I changed. The ne...
g++ and gcc are drivers. Usually, they run the preprocessor (cpp), compiler proper (cc1plus for C++ and cc1 for C) and the linker (gold or GNU ld) and all other things necessary. The difference between gcc and g++ is that the latter includes one additional library to link against (libstdc++). Depending on what type of...
5,759,487
5,759,702
Cross Platform Windows / OS X Development, with large existing code base
There is a large existing code base for a complex app that is written in C++ using MFC and WinAPI which needs to be ported to Mac OS X. The ideal solution is to have as much code common between the different platforms, especially code such as business logic. The GUI might be different depending on how good tools are a...
We had to make a similar decision a couple of years ago and decided to go with Qt. The application was a Windows Forms/Managed C++ combination (we did not have the crossplatform requirement), we did an evaluation of some of the ui kits out there we also considered Java. If you are familiar with MFC you might find WxWi...
5,759,668
5,759,731
Accessing members in a vector of objects as vectors
I have a c++ class that is contained as a vector of objects in another class. class Small { public: int a; int b; int c; }; class Big { public: vector< Small > getSmallVec() const { return m_smallVec;} private: vector< Small > m_smallVec; }; I'd like to be able to access the members of t...
If this is how you expect to access data and performance is important, have you considered using parallel vectors? Instead of std::vector<Small> In "Big" you actually maintain 3 vectors std::vector<int> aVec; std::vector<int> bVec; std::vector<int> cVec; All elements at 0 correspond to the 0'th "Small", and ...
5,759,692
5,759,803
How to declare foward a template of template (of a class)
Sorry I'm new to templates and I searched a lot, but I can't find a solution how to declare forward a template of template (of a class). Here my code: #ifndef CMAP_H #define CMAP_H #include "qvector.h" class CMap { public: CMap(const unsigned int & width, const unsigned int & height, const unsigned int & hexagonR...
This will do template <typename T> class QVector; See on codepad: #ifndef CMAP_H #define CMAP_H template <typename T> class QVector; class CMap { public: CMap(const unsigned int & width, const unsigned int & height, const unsigned int & hexagonRadius); CMap(const unsigned int & width, const unsigned int & ...
5,759,758
5,761,172
Allegro draw_sprite()
I have a 114x114 bitmap called "x.bmp" in my debug folder and this simple code #include <allegro.h> BITMAP *Sprite; int main(){ allegro_init(); install_keyboard(); set_color_depth(16); set_gfx_mode( GFX_AUTODETECT, 640, 480, 0, 0); Sprite = load_bitmap( "x.bmp", NULL); acquire_screen(); ...
The bitmap most likely can't be loaded. When you start an application from the Visual Studio debugger, the default working directory is the project directory. When you start an application via explorer, the working directory is the directory the executable is in. Normally, the project directory will be ...\SolutionName...
5,759,894
5,759,992
how to read line from console and store it into string in c++?
I have to read a whole line from the console and store it into a std::string and a char array, e.g. "Hi this is balaji" Now I have to read the above string and store it into string. I tried it using the getline() function.
Try: #include <string> #include <iostream> int main() { std::string line; std::getline(std::cin, line); // read a line from std::cin into line std::cout << "Your Line Was (" << line << ")\n"; std::getline(std::cin, line); // Waits for the user to hit enter before closing the program }
5,760,066
5,760,143
If(), else if() alternative in c++(Is this AI?)
First off, I am a noob. I am also a Janitor that has never made a dime writing code. This is just something that I love doing. It is for fun:) That being said, I wrote this console based tic-tak-toe game that has enough ai to not lose every game. (I guess ai is what it should be called.) It has something like 70 if/els...
The standard algorithm for this is called Minimax. It basically builds a tree, where the beginning of the game is the root, and then the children represent every possible move X can make on the first turn, then the children of each of those nodes are all the moves O can make in response, etc. Once the entire tree is ...
5,760,144
5,760,166
c++ formating error with cstrings when using tolower
Hi so I am trying to take a cstring and make it lowercase, but when I am printing the cstring at the end I am getting a weird format box where some of the letters should be. Do anyone have any ideas? #include <string> #include <iostream> #include <string.h> using namespace std; int main () { int i=0; char*...
The problem is that you are calling strcat incorrectly. The second parameter is not a null-terminated string. You really don't need to call strcat at all. Just write directly to the output string: Try: while (str[i]) { c = str[i]; c = tolower(c); cstr[i] = c; i++; } cstr[i] = 0; or, equival...
5,760,186
5,760,231
Use CString in console app when using VS Express
I have a problem when trying to use CString. I have a console application written using VS2010Express. I have a piece of code I would like to use, but it uses CString. When I try to include the appropriate header atlstr.h (as far as I know) I get the famous error: Cannot open source file. After Goggling around for a wh...
You could replace CString with CStdString
5,760,252
5,760,466
How can I print 0x0a instead of 0xa using cout?
How can I print 0x0a, instead of 0xa using cout? #include <iostream> using std::cout; using std::endl; using std::hex; int main() { cout << hex << showbase << 10 << endl; }
This works for me in GCC: #include <iostream> #include <iomanip> using namespace std; int main() { cout << "0x" << setfill('0') << setw(2) << right << hex << 10 << endl; } If you are getting sick and tired of iostream's formatting quirkiness, give Boost.Format a try. It allows good-old-fashioned, printf-style...
5,760,356
5,760,562
Building Python extension module with distutils
I'm using distutils to build a Python extension module written in C++. The problem I have is that in order to compile the extension module, I need to link with a certain shared library. This requires setting an additional compiler flag. So, I searched through the Python docs and found out about the extra_compile_arg...
There's actually a special option for that. For example: libraries=["rt"] You leave off the option and lib parts.
5,760,423
5,760,439
Why am I getting a linker error?
I am getting the error: "undefined reference to 'yClass::yClass()' when attempting to create an instance of the class in main. Anyone know why? Header: #ifndef header_h #define header_h #include <cstdlib> #include <iostream> using namespace std; class yClass { public: void one(); void ...
You have declared yClass's constructor, but not defined it. Or, if you have defined it in another file (i.e. the .cpp file that corresponds to "header.h"), then you haven't linked with that. The constructor is used when the object in main is initialized, so its definition must be present. The "one" and "two" methods, b...
5,760,551
5,760,577
Calling a chain of functions at different class inheritance levels
Given: class Foo { public: void Method1(); } class Bar extends Foo { public: Bar* Method2(); } class Baz extends Bar { public: Baz* Method3(); } So, someObject *b = new Baz(); b->Method3()->Method2()->Method1(); This will work, as Baz() contains all methods including Method2(), Bar contains Method1(); But...
That's what virtual methods are for. From the syntax errors I gather that you are new to C++ struct Base { virtual Base* One() { return this; }; void TemplateMethod() { this->One(); } }; struct Derived : public Base { virtual Base* One() { /* do something */ return Base::One(); } }; When you call Template...
5,760,592
5,760,619
another c++ pool ball object array issue
So I'm having a problem where I always seem to be getting the location of the last ball drawn when I'm requesting the location. As though the values in the objects are not being assigned properly when I'm declaring the object. Here is what I have at the moment ball TestBall[2]; Declaring variables inside a method void...
In C++, array indexing is 0-based, so valid indices for ball TestBall[2]; are TestBall[0] and TestBall[1]. Accessing TestBall[2] invokes undefined behavior, and writing to it certainly causes memory corruption. EDIT: (In response to the question being edited to show ball's definition) Remove static from xPos, yPos, zPo...
5,760,642
5,760,838
OpenAL: how to play multiple sounds at the same time and mix them?
I have used SDL_Mixer before, and it does this job correctly: when i play one sound with one single function call 10 times in sequence, all the sounds will get mixed together. But in OpenAL when i play a sound with alSourcePlay(), it just plays one sound without mixing into the previous sounds. So, how can i play more ...
You need one source per sound. A buffer holds the raw sound samples, and can feed one or several sources (at a time and simultaneously). A listener defines where your "ear" is (there is only ever one!). A source is a single instance of a sound, given a location in space, a volume, a buffer to pull samples from, and so ...
5,760,774
5,760,788
Write a recursive function that reverses the input string
I've been reading the book C++ For Everyone and one of the exercises said to write a function string reverse(string str) where the return value is the reverse of str. Can somebody write some basic code and explain it to me? I've been staring at this question since yesterday and can't figure it out. The furthest I've go...
I'll instead explain the recursive algorithm itself. Take the example "input" which should produce "tupni". You can reverse the string recursively by If the string is empty or a single character, return it unchanged. Otherwise, Remove the first character. Reverse the remaining string. Add the first character above t...
5,760,804
5,760,860
find interval from value
Suppose I've a list of intervals: [1, 90], [104, 234], [235, 300], .... Every interval has a name A1, B, B1, .... Given a value I want the name of the interval (112 -> B, 100 -> special_value). What's the best and faster implentation? Something better than a list of if / else if. The intervals are sorted in order, and ...
Idea: make a map object for the begin value of interval. If we found the possible interval, check if the value is in the interval. class MyInterval { public: MyInterval( double begin, double end ) : m_begin(begin), m_end(end) { }; double m_begin, m_end; }; bool operator < ( const MyInterval& left, const My...
5,760,934
5,764,919
c++ wxwidgets nested frame
i have two frames , how can i put one frame in the other and not open it in a new window ? something like tabs..
You should not be trying to 'stick a frame in a panel'! Panels go inside frames, not the other way around. As Thomas Matthews said, if you want tabs, use wxNoteBook
5,761,108
7,382,665
How to save an entry after changing date in QCalendarWidget?
I want to choose a day at a QCalendarWidget and save text for this particular day in a database. Now I'm looking for a good save-strategy. At the moment I'm using the QTextEdit::textChanged()-Signal, but of course this has very bad performance. Best choice would be to save after changing the day in the calendar or when...
I realized this, that I will save the text if the user changes the day or closes the program. So I save everytime when I change the date on the calendar.
5,761,124
5,761,149
Read Usernames and Passwords from a txt file
I need to pull usernames and passwords from a .txt file and I am having a difficult time wrapping my mind around how exactly to do this. I'll try to break this down. Open the file Read in the Usernames Compare a username against a user input Compare a password against a user input associated with the username return t...
Try this: http://www.learncpp.com/cpp-tutorial/136-basic-file-io/
5,761,246
5,761,334
Templates instead of the cpp preprocessor to avoid linking?
Is it possible to use C++ templates to avoid linking against a library containing a function which is not ultimately called? For example, with code such as: template <typename T> struct Foo { void bar() { zod(); } }; int main(int argc, char *argv[]) { return 0; } GCC 4.5 will reject it: error: there are no argume...
I think you're confusing linking with providing a prototype for zod() (i.e. a declaration, e.g. by including a header file). Many implementations will happily compile and link a program that has inline functions (or templates) which call functions without a definition. So, this works just fine (with at least MSVC 10, G...
5,761,251
5,761,278
Need help with my recursive program that reverses the input
Possible Duplicate: Write a recursive function that reverses the input Recently, I've been reading the book C++ For Everyone and I've been having trouble putting together a recursive function (Confusing to think about...) The question was: Write a recursive function string reverse(string str) that returns the revers...
This would do the work: Delete return last_letter; Change ` word += reverse(str_copy); to word = last_letter+reverse(str_copy); I'll leave the thinking to you! Best.
5,761,254
5,761,282
Creating 2-dimensional vector in class C++
I need to create a vector of vectors full of integers. However, I continuously get the errors: error: expected identifier before numeric constant error: expected ',' or '...' before numeric constant using namespace std; class Grid { public: Grid(); void display_grid(); void output_grid(); private: vec...
You cannot initialize the member variables at the point where you declare them. Use an initialization list in the constructor for that: Grid::Grid() : row(5,0), puzzle(9, row), rows_(5), columns_(9) { }
5,762,042
5,762,323
const overloaded operator[] function and its invocation
I define two versions of overloaded operator[] function in a class array. ptr is a pointer to first element of the array object. int& array::operator[] (int sub) { return ptr[sub]; } and int array::operator[] (int sub) const { return ptr[sub]; } Now, if I define a const object integer1 the second function ca...
In your second example, the non-const version will be called, because no conversion is required, and a call that requires no conversion is a better match than one that requires a conversion. Ultimately, however, you have a basic problem here: what you really want is behavior that changes depending on whether you're usi...
5,762,420
5,762,436
Overloading operators with non-member functions
The answer to this question seems to escape me, but how do you go about overloading with non-member functions. Do you just create a program level function and where ever the prototype (or definition) exists the operator is overloaded for that class type?
With a member function, this would be the left hand side parameter, meaning your operator would only have one argument (or none for unary operators). With a freestanding function, you must supply either two or one arguments for binary or unary operators, respectively. A good example is the << operator for streams: clas...
5,762,448
5,762,474
Callback in c++ - Could not understand
I tried to understand how call back works...In the below program passing the (void*)&obj and receiving it in (void* pt2Object) is confusing me... *pt2Object will hold the value and not the address of some variable but here the reference is paased to it.. I could not understand how the ClassA::Wrapper_To_Call_Display fu...
DoIt((void*)&obj,ClassA::Wrapper_To_Call_Display); The &obj is not a reference. & returns the address of the obj which is an instance of the ClassA class. The next parameter (ClassA::Wrapper_To_Call_Display) is the address of the function (note that it comes without the () that are required for a function call). *pt2...
5,762,465
5,762,481
Case-Label question in C/C++
I came across this code #include<stdio.h> int main() { int a=1; switch(a) { int b=20; case 1: printf("b is %d\n",b); break; default:printf("b is %d\n",b); break; } return 0; } I expected the output to be 20 but got some ga...
Either that's a programming puzzle or a heinous bug. switch acts like a computed goto. So it will either goto 1; or goto default;. In either case, it jumps past b = 20; and prints an uninitialized, garbage value! A C++ compiler should improve the situation somewhat by refusing to compile this.
5,762,506
5,762,529
Problems with classes and types
I have a class that I'm trying to use as a type class ship{ public: vector <int> xp; vector <int> yp; vector <bool> pos; shipType vessel; bool active; ship(){} void randommethods(){ blah; } }; I want to include in a fleet class an array of type ship. clas...
In your code for fleet class you declare an array of ship( shop boat[7] ) named boat AND a function member returning int ( boat(){} ) named boat. You try to declare two distinct entities with the same name in one namespace and this is error. That what compiler tries to tell you. I guess you wanted to wright a default c...
5,762,642
5,762,656
ios_base and static members
Static constants in the ios_base class are initialized when created, which makes sense for constants. Can non-constant static member variables be initialized the same way, or is this concept only allowed for constant static members? For non-constant static members with gnu compilers must use always define/allocate sp...
Class members can be created and initialized only for the static const (integral data type, like int, char, double etc.) members in current C++ standard. For non-static member it's not possible. However, in C++0x that facility is introduced. Edit: For non-const static member, you can do initialization but you have to d...
5,762,704
5,762,738
Large integer value causes performance hit in c++?
I'm working on a home made board game (computer board game of course). As part of the game I have a strength value for each unit on the board. One of these units is special and has practically unlimited power. I want to represent this with integer max value (the strength is an int var). My problem is that this value is...
As long as you're sticking to max value, no. An integer comparison on most any hardware architecture you're likely to use will perform that comparison in bit-wise parallel on the whole word, and do it one instruction. Now, should you happen to use a packed decimal representation like COMP-3 in COBOL, it could.
5,762,903
5,762,911
C++: Templates in Header files are destroying me
I'm fluent in Java, but very new to C++. I'm definitely not understanding what is wrong -- at all. Here's the code: // Sort_Search.h #ifndef SORT_SEARCH_H #define SORT_SEARCH_H using std::vector; template<typename T> void printVector(vector<T> &list); #endif // Sort_Search.cpp #include <iostream> #include <vec...
In the header, you need to provide the namespaces. template<typename T> void printVector(std::vector<T> list); // ^^^^^ There are several things you need to consider: In C++, parameters (except arrays) are always passed as value type if you don't specify it, unlike Java where every...
5,762,933
5,763,172
vector iterators incompatible error
I'm getting a vector iterators incompatible error during runtime. the line where it happens is at the very end of the code section, inside the for loop (humans.push_back( Human(&deck, (*iter)) );) When I first got the error, I was using a different iterator than 'iter' by mistake, so the runtime error totally made sens...
The error is in code that you do not show. The following code, which I have written based on your code and your descriptions, does not produce any errors: #include <vector> #include <string> #include <iostream> #include <cstdlib> #include <cstring> #include <cctype> using namespace std; class Deck { }; class Player(...
5,763,260
5,763,292
Receiving object in the reference variable
Possible Duplicate: Difference between pointer to a reference and reference to a pointer Hi, I could not understand get(Event*& pEvent)... Is it passing the address of the object pEvent to the reference of pEvent..(Event*& pEvent)...The reference will exist as a local scope within the function isnt it.... void cl...
foo(someType& o) means that a reference of an object is passed rather than a copy of the object. In your case a reference to an Event pointer is passed. Basically that means that changes inside the function will make changes to the variable being passed visible to the caller of the function. E.g. void get(Event* e) { ...
5,763,337
5,763,378
wxwidgets aui manager problem
i am using auimanager to show frame in a frame , however it keeps showing the second frame in a new window instead in the same window, or any other suggestions on how to do it ?
Your "outer frame" should be a aui.AuiMDIParentFrame, whereas the "inner frame" should be aui.AuiMDIChildFrame. In any case: post some code, then it is easier to advise. Example code: import wx import aui class MainFrame(aui.AuiMDIParentFrame): def __init__(self, parent): aui.AuiMDIParentFrame.__init__(s...
5,763,409
5,763,453
Ellipsis and va_args trick needed
TraceMessage is an WinAPI function with variable number of arguments. It is a tracing function, with a notation similar to printf, which generates a trace message in Windows tracing. The weird part here is that it receive a format string as part of the ellipsis, not as a dedicated argument. It is possible to 'override'...
With a va_list you can pass it to a function which takes a va_list after having used va_arg on it already to have extracted one or more arguments. The va_list will then act like it "contains" only the rest of the arguments. I have no experience with TraceMessage itself, but I've given an example using standard vprintf ...
5,763,532
5,763,603
convert CStdStringW to TCHAR *
I have a piece of code that originally used CString. Since it is not available to VSExpress users I replaced it with a CString "clone" found at: http://www.codeproject.com/KB/string/stdstring.aspx This clone works just fine but one problem remains when using it: TCHAR *GetConnectionString(){return m_szConnectionString)...
Once you commit to a non-standard string class, you're stuck with having to use it. You ought to change the return value type: CStdString GetConnectionString() { return m_szConnectionString; }; The other option is to change the return type from TCHAR to const TCHAR: const TCHAR* GetConnectionString() { return...
5,763,607
5,763,802
need explanation on boost::mpl
typedef vector<long,float,short,double,float,long,long double> types; typedef fold< types , int_<0> , if_< is_float<_2>,next<_1>,_1 > >::type number_of_floats; BOOST_MPL_ASSERT_RELATION( number_of_floats::value, ==, 4 ); I don't understand the way fold works, why int_<0>? why is_float<_2> ? Could so...
int_<0> is the starting value of the accumulator used for the fold. Try to use int_<1> and see what happens. The third argument is the operator used to fold the sequence. This needs to be a binary metafunction. if_< is_float<_2>,next<_1>,_1 > is turned into a lambda expression with two arguments where _1 and _2 refer t...
5,763,710
5,765,847
How to create iterator to solve this problem?
So we have 3 maps. args, headers and params maps. They are string to string maps. We also have a set<settings> Settings_Set where: struct settings { string name; set<string> args; set<string> headers; set<string> params; }; We want to compare all of our maps->first strings with all our sets in all it...
You don't need boost at all. Also, I don't see any instances of std::map even though you call them "maps". I only see sets. This is not a solution per se, but more a hint to figuring it out. You can loop over the elements of set<settings> Settings_Set with: set<settings>::iterator ite = Settings_Set.begin(); while(i...
5,763,919
6,060,622
What does mean for a name or type to have a certain language linkage?
According to (c) ANSI ISO/IEC 14882:2003, page 127: Linkage specifications nest. When linkage specifications nest, the innermost one determines the language. A linkage specification does not establish a scope. A linkage-specification shall occur only in namespace scope (3.3). In a linkage-specification, the specif...
Language linkage is the term used for linkage between C++ and non-C++ code fragments. Typically, in a C++ program, all function names, function types and even variable names have the default C++ language linkage. A C++ object code can be linked to another object code which is produced using some other source language (...
5,764,106
5,766,889
boost::dynamic_bitset concat performance
I want to concat a big bitset with a smaller one in a way that wont kill performance. Currently my application spends 20% of cpu time in just the following code: boost::dynamic_bitset<> encode(const std::vector<char>& data) { boost::dynamic_bitset<> result; std::for_each(data.begin(), data.end(), [&](unsigned ...
I wrote my own bitset class. I appreciate any suggestions for improvements. I will try to look into SSE and see if there is anything useful there. With my very rough benchmark I got a 11x performance increase while appending 6 bits at a time. class fast_bitset { public: typedef unsigned long block_type; static ...
5,764,364
5,764,420
Base class and derived class constructors calling in C++
#define DECLARE_NEWMSG(ClassName,ClassID) static ClassName* FromMsg(ClassA* psg) { return dynamic_cast<ClassName*>(psg); } static ClassA* newMsg() ...
static const GetEvent cGetEvent; GetEvent::GetEvent():ClassA( ID, newMsg, NULL, NULL, 0 ) { //no stmts inside; } This syntax is called an initialization list, and can be used to initialize class members during construction. When you construct a derived class object, its parent classes will also be initialized (startin...
5,764,425
5,901,635
How to set Qt QStateMachine animation duration
I'm trying to learn the Qt framework. My QStateMachine code does the correct thing (pressing the button makes the chat window popup change size). I can't change the speed of the animation to get a nice visual transition. Any suggestions? Here's the code: MainWindow::MainWindow() { widget.setupUi( this ); // chat...
The code ChatWindowOpenAnimation = new QPropertyAnimation( widget.pushButton, "geometry" ); should be ChatWindowOpenAnimation = new QPropertyAnimation( widget.groupBox, "geometry" ); The animation was being applied to the wrong widget.
5,764,482
5,765,323
Threads ordering in C++/Linux
I'm currently doing a simulation of a hard disk drive IOs in C++, and I'm using pthread threads and a mutex to do the reading on the disk. However I'm trying to optimize the reading time by ordering my threads. The problem is that is my disk is currently reading a sector, and a bunch of requests to read arrive, any of...
It is very rarely a good idea to rely on the exact behaviour of process priority schemes, especially on a general purpose operating system like Linux, because they don't really guarantee you any particular behaviour. Making something the very highest priority won't help if it references some address in memory or some I...
5,764,678
5,764,738
File Input Not Returning Good
Apologies to ask such a basic question but I really cant see why In3 is not good. I suppose there is something fundamental here which I dont know Thanks in advance the contents of the file "testIn1.txt" are: a b c a I am using MS Visual C++ 2010 Express. #include <fstream> #include <iostream> using namespace std; int...
Works for me (using MinGW g++ as a compiler): C:\>echo a b c a > testIn1.txt C:\>g++ test.cpp -otest.exe C:\>test Is In3 Good? 1 Is OUt3 Good? 1 Note that testIn1.txt should be in the same directory as the executable or you should give the program a path to the file. You can verify that you're in the correct directo...
5,764,764
5,764,837
How can I grasp the concept of pure OOD?
I still have a little problem grasping the concept of pure OOD. Let's say we have a class Human and we live in a world where sometimes the human walks (the brain commands the legs), where sometimes trees disappear (the human notices that) and sometimes humans randomly hit each other. The first two cases are really a no...
I think that you are falling into the trap of trying to model the "real" world in classes without having a purpose to your design. What is your program supposed to do? Once you've worked that out, then you can start to design which aspects of the real world you want to model and which parts of the real world don't matt...
5,764,888
5,764,974
While loop not working!
using namespace std; void reverse(char a[],int slen, int elen) { int start,end,temp; for(start=slen,end=elen;start<end;start++,end--) { temp=a[start]; a[start]=a[end]; a[end]=temp; } } void reverseall(char b[]) { char a[15]; ...
Change it to for(i=13,j=0;i>=0,j<15;i--,j++) a[j]=b[i]; a[14] = '\0'; and it will work (codepad). What happened was that you reversed the input string, but it contains a \0 character at the end, so your arrays first character was \0 and the rest of the code did nothing anymore. So what we're doing now is to...
5,764,917
5,764,934
Using for loop to reverse Iterate over elements of a container/string without warnings in both 32-bit and 64-bit
I just want to reverse-iterate over a container or over a string. This sample code for (int i = strlen (str) - 1; i >= 0; i--) { ... } will raise a warning on 64-bit compilation: warning C4267: 'initializing' : conversion from 'size_t' to 'int', possible loss of data On the other hand, for (size_t i = strlen (str...
change to: for (size_t i = strlen (str); i--; ) { ... }
5,764,929
5,765,815
sending and receiving udp packets on same port
i need my client app to be able to sendto() and recvfrom() through the same port using UDP. I have discovered i can only bind one socket to the port and it's better to do it when using recvfrom(), otherwise things mess up. I want to be able to still send UDP packets through that port but binding it to a different socke...
This should work fine. One socket bound to a port where you use recvfrom() and sendto() on the same socket. See this example from MSDN that shows recvfrom() in isolation - right around the recvfrom() you should be able to sendto() using that same socket.
5,764,956
5,765,029
Which is faster : if (bool) or if(int)?
Which value is better to use? Boolean true or Integer 1? The above topic made me do some experiments with bool and int in if condition. So just out of curiosity I wrote this program: int f(int i) { if ( i ) return 99; //if(int) else return -99; } int g(bool b) { if ( b ) return 99; //if(bool) el...
Makes sense to me. Your compiler apparently defines a bool as an 8-bit value, and your system ABI requires it to "promote" small (< 32-bit) integer arguments to 32-bit when pushing them onto the call stack. So to compare a bool, the compiler generates code to isolate the least significant byte of the 32-bit argument th...
5,765,139
5,765,230
Entropy and parallel random number generator seeding
I have a loop where I am adding noise to some points; these are being later used as the basis for some statistical tests. The datasets involved are quite large, so I would like to parallelise it using openMP to speed things up. The issue comes up when I want to have multiple PRNGs. I have my own PRNG class based upon N...
I think it depends on the properties of your PRNG. Usual PRNGs weaknesses are lower entropy in the lower bits and lower entropy for the first n values. So I think you should check your PRNG for such weaknesses and change your code accordingly. Perhaps some of the diehard tests give useful information, but you can also ...
5,765,141
5,765,192
How to pass 2D array as read only to function by double pointer?
I need to pass double pointer, which points to the first element of 2D array, to function in way that prevents the function from modifying any element from 2D array. I thought I can do it with const reference - int** const &board, but it doesn't work like I expected. Moreover the 2D array cannot be declared as const, b...
I saw your code, and the interesting part is this: int move(int** const &board) { board[1][1] = 9; // should be illegal return 9; } If you want board[1][1] = 9 to be illegal, then you've to declare the parameter as: int move(int const** &board); //int move(int** const &board); doesn't do what you want There i...
5,765,309
5,765,484
Converting Orthogonal Camera to Perspective OpenGL
I'm having some troubles converting a orthogonal camera to a perspective one, using OpenGL. I currently have my orthogonal camera following a middle point of two objects, using: glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0,_winWidth,0,_winHeight,150,-150); glTranslated(-_middlePoint[0]+_winWidth/2, -_middle...
If you have code working using glOrtho already, you can normally switch to a perspective projection by simply changing that to glFrustum. If you're writing new code, gluPerspective and gluLookat may be easier, but for code that already works using an orthographic projection, it's easy to switch to perspective by just c...
5,765,320
5,765,333
Clean way to eliminate "unused parameter 'widget'" warning generated by QGraphicsItem::paint
QGraphicsItem::paint has the following signature: void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) When I create custom QGraphicsItems, I have to provide an implementation for this function. The thing is... I never need to use the option and widget parameters, but I can't just rem...
Don't provide parameter names to the unused parameters. For example (I'm not sure what your "event" refers to), to get rid of warning: unused parameter ‘option’, change your signature to: void paint(QPainter *painter, const QStyleOptionGraphicsItem * /* unused */, QWidget *widget) (The /* unused */ tag is unnecessary ...
5,765,735
5,766,016
c++: Accessing the Elements of a Map of Strings and Boost Circular Buffers
I'm writing a program that reads a text file of city names into a vector, then uses a stl::map to associate each city with a boost circular buffer. I also have a vector of temperature data, which I converted to double type after reading it as strings from another text file. I want to know how to feed this data into a c...
You can initialize a circular_buffer with a pair of iterators, like so: std::vector<double> v; ... ... // Fill v with data ... boost::circular_buffer<double> cb(v.begin(), v.end()); I'm not exactly sure how you want to apply this in your specific case. You only have one vector of doubles, but I don't know how many c...
5,765,780
5,765,787
Can anyone help me understand this error? "definition of implicitly-declared ‘classA::classA()’"
Heres the code: #include <cstdlib> #include <iostream> using namespace std; class classA { protected: void setX(int a); private: int p; }; classA:: classA() { //error here. p = 0; } void classA:: setX(int a) { p = a; } int main...
You forgot to declare the constructor in the class definition. Declare it in public section of the class (if you want clients to create instance using it): class classA { public: classA(); // you forgot this! protected: void setX(int a); private: ...
5,765,836
5,774,474
machine-learning, artificial-intelligence and computational-linguistics
I would love to talk to people who have experience in machine-learning, computational-linguistics or artificial-intelligence in general but by the following example: • Which existing software would you apply for a manageable attempt building something like google translate by statistic linguistic, machine learning? ...
The best techniques available for automated translation are based on statistical methods. In computer science this is known as "Machine Translation" or MT. The idea is to treat the signal (the text to be translated) as a noisy signal and to use error correction to "fix" the signal. For example, suppose you are translat...
5,765,842
5,766,339
How to write a console application that uses powershell instead of cmd
I have no idea if this is even a programming question, or something that is configured through my OS. But how would I get it so my console application uses Powershell instead of cmd? I know I can open Powershell and run the program from there, but even then, calls such as system("Get-Childitem") fail. I'm using Visua...
Look into the environment variable COMSPEC, which on Windows, and DOS 1.1 before that, controls which shell is utilized for launching programs that need a shell. SET COMSPEC=%path_to_powershell% You can do the same within your C++ program by calling the setenv C runtime call;
5,765,924
5,767,006
function template cannot hide class name?
This works in GCC and Comeau: struct X {}; void X() {} This breaks in Comeau: struct X {}; template< typename T > void X() {} This breaks both: template< typename T > struct X {}; template< typename T > void X() {} The rule is defined by §3.3.7/2. Is the discrepancy simply because a function template is not a fun...
That's because the spec says in 14.p5: A class template shall not have the same name as any other template, class, function, variable, enumeration, enumerator, namespace, or type in the same scope (3.3), except as specified in (14.5.5). Except that a function template can be overloaded either by (non-template) func...
5,765,986
5,766,931
How can I run an .exe with DLLs in separate directory?
I know that this was already discussed somewhere in here but I have not find question that I wanted, namely: I have a C++ application that uses a lot (more than 20 -30 ) DLLs. I have defined in my Visual Studio 2010 project that the .exe will be copied to the ProjectDir (so that everything is neat and clear) but when t...
first of all there is no need to copy your exe file to your project dir, whereever your .exe file is created when you are debuging your project the running dir would be your project dir. and after that when you are trying to import the dll if you look for it relatively windows first search for that dll in your running ...
5,766,006
5,766,015
Does catch (...) work on throw; with no object?
What does C++ standard say should happen for the following code when there is no pending exception being processed higher up the stack? try { throw; } catch (...) { cerr << "Caught exception." << endl; } Will the throw with no object be caught or not?
From the 2003 C++ Standard §15.1[except.throw]/8: If no exception is presently being handled, executing a throw-expression with no operand calls terminate(). So, in your example, since no exception is currently being handled, nothing is thrown and instead terminate() is called. Since terminate() does no...
5,766,044
5,766,078
Sleeping for less than a millisecond in C++
Possible Duplicate: Sleep Less Than One Millisecond Is there a way to "sleep" for less than a millisecond in C++, but without a busy loop?
No. Under Windows, even without sleeping you can't ensure that two consecutive instructions will be carried out with less than a millisecond between them.
5,766,385
5,766,397
Why do I get different results when I apply sizeof operator?
I have this program #include <stdio.h> int main() { char arr[100]; printf("%d", (int)sizeof(0,arr)); } This prints 4 when compiled as a C file and prints 100 as a C++ file. Why? I am using gcc.
In C the result of the right hand operand of the comma operator has a type and value. In C a comma operator does not yield an lvalue. So there is an lvalue to rvalue conversion resulting in decay of array type to pointer type. So in C what you get is the result of sizeof(char*). In C++ the result of a comma expression...