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,682,509
5,683,475
how to parse POST body / GET arguments?
So I need to parse such string login=julius&password=zgadnij&otherArg=Value with N args and each arg will have a value. You can find such ti GET arguments and in POST requests. So how to create a parser for such strings using Boost?
In this question's case, as Tomalak mentioned, regular expression may be a little overkill. If your real input is more complex and regular expression is needed, does the following code illustrate the usage? int main() { using namespace std; using namespace boost; string s = "login=julius&password=zgadnij&otherArg...
5,682,658
5,682,670
C++ -- In which case the compiler can deduce the type
vector<Widget*> vwp; // populate vwp; // Do need to specify the TYPE 'Widget' for_each(vwp.begin(), vwp.end(), DeleteObject<Widget>()); // case I template<typename T> struct DeleteObject: public unary_function<const T*, void> { void operator() (const T* ptr) const { delete ptr; } }; //////////////...
The first case features a class template. The second case features a function template. That is the one distinction.
5,682,891
5,688,190
C++ show an icon оverlay over all empty folders
I am searching for the C++ solution to show icon overlay over the folder. but I have noticed that it's really bad idea to code overlays in .NET\Java +Shell because interpreter is called all the time you are using explorer. So I have example how to do add icon over files which contains some text: http://www.codeproject...
You need to create a COM object that implements IShellIconOverlayIdentifier like that codeproject article. Your IsMemberOf method would look something like this: STDMETHODIMP YourClassThatImplementsIShellIconOverlayIdentifier::IsMemberOf(PCWSTR pwszPath,DWORD Attr) { if (!(Attr&FILE_ATTRIBUTE_DIRECTORY)) return S_F...
5,682,971
5,683,090
Performance issues when using iterators?
I have a function which takes in a list of characters and generates the next lexicographic permutation. For fun, I tried generalizing the code to use iterators, as well as being able to generate permutations of more different types. template<typename ITER> bool nextPermutation(ITER start, ITER end, std::random_access_i...
Without optimizations, due to heavy iterator debugging (_ITERATOR_DEBUG_LEVEL is defaulted to 2 in debug mode, aka full debugging), the code is also slow on my machine. With /02 however, the iterator debugging is disabled completely and the code executes in full before the console window even shows up. Here you got a n...
5,683,026
5,683,030
Logical AND, OR: Is left-to-right evaluation guaranteed?
Is left-to-right evaluation of logical operators (&& ||) guaranteed? Let's say I have this: SDL_Event event; if (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { // do stuff } } Is this guaranteed to be the same as this? SDL_Event event; if (SDL_PollEvent(&event) && event.type == SDL_QUIT) ...
Yes, it's guaranteed, otherwise such operators would lose much of their usefulness. Important notice: this is valid only for the builtin && and ||; if some criminal overloads them, they are treated as "regular" overloaded binary operators, so in this case both operands are always evaluated, and in unspecified order as ...
5,683,197
5,686,030
Helper classes - Private nested class vs. class declared & defined only in implementation file
I'm writing a basic SQLite wrapper. While doing this I noticed I'm frequently manually opening and closing SQLite databases, creating and destroying SQLite compiled statement structs using SQLite's API. Manually creating/destroying these resources. Which I'm learning gets kind of messy when a function has to return pre...
No, that's perfectly fine. If some classes or functions are only used in one .cpp file, it makes sense to define them in that file. On the other hand, if they are of significant size (whatever that means), or could be used elsewhere, you would be better of putting them in a separate source file. But that can also be...
5,683,257
5,683,281
Why is typename _not_ needed here in Visual Studio 2008/2010?
In this question, the asker has the following function: template<typename ITER> bool nextPermutation(ITER start, ITER end) { return nextPermutation(start, end, std::iterator_traits<ITER>::iterator_category()); } Why isn't a typename needed before the std::iterator_traits? I thought it was needed for nested types o...
Doesn't MSVC implement the late-parsing scheme? In such a scheme, the compiler isn't dependent on typename. It just stores all the token in between the template definition's braces, and when the template is instantiated, it parses those tokens. Since it then knows what is and what is not a type, it will work without ty...
5,683,355
5,829,867
#define in precompiled header not recognized in .mm files
Why would a #define statement in a .pch not be recognized by .mm files? Results in "use of undeclared identifier" and "not declared in this scope" when attempting to reference the macro. Pch looks like this: #import <Availability.h> #ifndef __IPHONE_3_0 #warning "This project uses features only available in iPhone SDK...
I had the same problem, cleaning was not solving it. After closing and restarting Xcode 4 everything was fine. If that can help someone...
5,683,543
5,684,394
Lisp and Android NDK
Is there a lisp ported to android with the NDK? I've been thinking of writing one in C++, for a project I have going, but I don't want to reinvent the wheel. Has anyone seen such a beast? I have seen this project, but it's not quite what I'm looking for...
There is an effort underway to run ECL on Android with the NDK. Embeddable Common Lisp (ECL) is an implementation of Common Lisp that compiles to C. According to a recent post from the developer about the status of ECL on Android, "it's now at a point where it's reasonably complete." The developer is currently working...
5,683,553
5,684,003
C++ Get File Name and Line Number of "Segmentation Fault" Linux x64
Without running GDB, but only the program itself. edit: i've already seen such program but i can't figure how to do that myself :(
Tommie deserves credit for solving this. I've detached his answer from GDB by using the somewhat standard backtrace utility from <execinfo.h>. static void dumpstack(void){ static void *backbuf[ 50 ]; int levels; levels = backtrace( backbuf, 50 ); backtrace_symbols_fd( backbuf, levels, STDERR_FILENO ); ...
5,683,604
5,683,644
Correct way to copy _bstr_t to wchar_t*
There is a class A that derives from _bstr_t. It needs to have a method that takes a wchar_t* and copies the bstr into it. Is this the safest way to do it if wcsncpy_s understands bstrs? class A: public _bstr_t { ---- ---- void CopyTo(wchar_t* buf, size_t destinationsize) { wcsncpy_s(buf, des...
I think you want this: void CopyTo(wchar_t* buf, size_t destinationsize) const { wcsncpy_s(buf, destinationsize, static_cast<wchar_t const *>(this), _TRUNCATE); } If you don't use _TRUNCATE, then the invalid parameter handler will be invoked when the buffer is too small to contain the entire string (plus null): h...
5,683,660
5,683,683
How can you make exception handling fall through multiple catch blocks in a single case?
Let's say you have the following hierarchy. You have a base class Animal, with a bunch of sub classes like Cat, Mouse, Dog, etc. Now, we have the following scenario: void ftn() { throw Dog(); } int main() { try { ftn(); } catch(Dog &d) { //some dog specific code } catch(Cat &c) {...
Another alternative (aside from the try-within-a-try) is to isolate your generic Animal-handling code in a function that is called from whatever catch blocks you want: void handle(Animal const & a) { // ... } int main() { try { ftn(); } catch(Dog &d) { // some dog-specific code hand...
5,683,710
5,683,740
wstring -> LPCWSTR in ShellExecute give me error LNK2028 & LNK2019
Hello I'm programming in Visual C++ 2010 (spanish) with UNICODE and /clr. I have a header file called "fileFuncs.h": #include <iostream> #include <fstream> #include <string> #include <stdlib.h> #include <string> using namespace std; std::wstring s2ws(const std::string& s) { int len; int slength = (int)s.lengt...
Right-click your project in the Solution Explorer, Properties, Linker, Input. Add shell32.lib to the Additional Dependencies setting. Beware that there's little point in compiling this code with the /clr option, you didn't write any managed code. The equivalent of ShellExecute() function is Process::Start().
5,683,794
5,683,819
Bad practice to declare names in the standard namespace?
I was looking through the Google C++ style guide, and came across this: "Do not declare anything in namespace std, not even forward declarations of standard library classes. Declaring entities in namespace std is undefined behavior, i.e., not portable. To declare entities from the standard library, include the appropri...
Could someone explain what this means and why this is undefined behavior using example code? The following program yields undefined behavior: namespace std { void foo(int) { } } #include <iostream> int main() { std::cout << "Hello World!" << std::endl; } Why? It declares a function named foo in namespace ...
5,684,071
5,684,136
Conditional Member Functions
What's the recommendation regarding conditionally defining member functions in a C++ class? (The question is centered around limiting the external exposure of some classes in a DLL - specifically when those classes are passed in as a parameter). Obviously this isn't something you want to do to data members, but functio...
Generally if you wont want to expose parts of an exported class, then you should consider the option of not exposing the class, but instead providing an abstract interface that your class inherits from. eg. class AbstractExportedInterface { public: virtual void do_stuff() = 0; }; class HasStuffIDontWantToExport : ...
5,684,086
5,684,108
What happens to dynamically allocate objects inside of an object that is deleted?
When I use the delete keyword on an object is that objects destructor executed? What if the objected I deleted contains other pointers and I don't delete them, is that a memory leak? I get a confused a bit sometimes over when to use delete. The problem is worst for me when I pass things around. I don't know when it'...
When I use the delete keyword on an object is that objects destructor executed? Yes. That's what the destructor is for. What if the objected I deleted contains other pointers and I don't delete them, is that a memory leak? Yes. This is one of the most common sources of memory leaks. I don't know when it's safe to ...
5,684,096
5,684,164
Instantiating Derived objects from the Base class
Trying to create a Driver type class where, below, Base is the Driver that is passed a type at instantiation. The type, the 2 in this case, is used to construct the correct derived object. My compiler is throwing a Declaration syntax error on the "Class Base" line. My end goal is to be able to do this: Base *B; ...
It looks like you're trying to do a class factory. I'd recommend that you have a static method in Base that returns either Derived1 or Derived2. class Base { public: static Base* Create(int); virtual void DoStuff() = 0; } class Derived1 : public Base { Derived1() { printf("\nDerived1 Initialize...
5,684,165
5,684,222
Making an array of pointers to structs or objects in C++
So I'm basically just trying to take in some file input, and then take that data and put it into several structs. The only issue I'm having is with the naming of the pointers to the structs. The struct's themselves are supposed to represent students and I wanted to set each pointer as one of their names rather than a...
Ok, let's start from the top. Your code was (before I reformatted it) a mess. Messy code is harder to read and more likely to have bugs. You have 3 arrays, each containing 20 strings. Why do you need so many? One of them is named temp; having to use that as a variable name is a good indicator that you're mishandling d...
5,684,253
5,684,273
Are user-defined-literals resolved at compile-time or runtime?
I wonder, because predefined literals like ULL, f, etc. are obviously resolved at compile time. The standard (2.14.8 [lex.ext]) doesn't seem to define this, but it seems to tend towards runtime: [2.14.8 / 2] A user-defined-literal is treated as a call to a literal operator or literal operator template (13.5.8). To ...
Yes, you get a function call. But function calls can be compile time constant expressions because of constexpr literal operator functions. For an example, see this one. As another example to show the advanced form of constexpr computations allowed by the FDIS, to have compile time base-26 literals you can do typedef u...
5,684,302
5,684,514
C++ Recursively find shortest path in horizontal cylinder.(Problem with recursion)
This program should return the weight of the shortest path from left to right(it also can go over the top and over the bottom, so it's like a horizontal cylinder) in two-dimentional array.(here is a full question_link) I'm trying to check recursively by first going up,then right and finally down in the array. By runnin...
Here you go. This will just return the cost of the path, finding the actual path is just a simple modification of this. int rec_path(int matrix[5][6],int r,int c,int cost) { if(c==6) return cost; int ans=2e9; static const int dr[]={-1,0,1}; for(int i=0;i<3;i++) ans=min(ans,rec_path(matrix,(5+(r+...
5,684,312
5,684,622
circular linked list problem in c++
Why doesn't my linked list code work? It has no problem with 4 notes, but when I get to 5 the sorted linked list seems to hang. Does it not know where to append and place the new node? I mean,for example the first data is a name starts with letter A, and the second start with D and the 3rd start with C.. but when i e...
Take a look at this section: if(name.compare("N") < 0){ while(temp->getNext()->getNext()!=NULL && name.compare(temp->getNext()->getUserData()->getName())>0){ temp = temp ->getNext(); } } else{ temp = end; while(name.compare(temp->getUserData()->getName())<0){ temp = temp ->getPrev(); } } Yoiu have s...
5,684,479
5,686,844
Help with automated renaming in C++
Here is my issue: I have a large library of code where all of the class names begin with Agui. For example: class AguiWidget { }; class AguiBitmap { }; also, all the hpp and cpp files are named like this also: AguiWidget.hpp etc. The library also does not use a namespace. all of the enums begin and use Agui: ex: e...
You need to use a global find and replace tool. If you have Visual Studio 2008, then it is already built-in. Once you rename all the classes and namespaces, then use another tool to rename the files or build a script to do it for you.
5,684,537
5,684,564
Read a file twice in C++ because of eof?
I read numbers from a file, apply 3 functions and print out to another file: int main(int argc, char** argv) { std::ifstream fin; fin.open("input.txt"); std::ofstream fout; fout.open("output.txt", std::ios::app); char arr[50]; int a,b; int N;//number to factor while (!fin.eof()){ ...
while (!whatever.eof()) is essentially always wrong, and will never detect the end of the file correctly. In your case, it's easiest to coalesce the reads together, and then do all the processing, something like this: while (fin >> arr >> a >> b >> N) { PrintBackwards(arr); fout << "\n"; fout << gcd(a, b) ...
5,684,594
5,684,631
Matrix Libraries vs For Loops in C++
Could you tell me if using a matrix library results in a faster run-time than regular for-loops? Currently, I have some methods that use for-loops that iterate through multidimensional vectors to calculate matrix products and element-wise products, where the matrix size is roughly 1000 columns by 400 rows. This method ...
Yes -- a fair number of C++ matrix libraries (E.g., MTL, uBLAS, Blitz++) use template metaprogramming to optimize their behavior. Absent a reason to do otherwise, I'd start with Boost uBlas. You might also want to look at the OO numerics libraries list for other possibilities.
5,684,737
5,684,867
Why GetProcAddress doesn't work?
First, I create a simple dll called SimpleDll.dll, its head file: // SimpleDll.h #ifdef MYLIBAPI #else #define MYLIBAPI __declspec(dllimport) #endif MYLIBAPI int Add(int a. int b); its source code: // SimpleDll.c #include <windows.h> #define MYLIBAPI __declspec(dllexport) #include "SimpleDll.h" int Add(int ...
You should use a .def file if you want to export the name for GetProcAddress. Otherwise you will have to deal with c++ name mangling and with symbol decorations. You can avoid mangling by declaring your function as extern "C", but the only way to avoid decorations is to use a .DEF file. One more thing - in Dependenc...
5,684,794
5,684,839
Pass a overloaded function as a template
I have this template set __Self &set(const char *name, lua_CFunction func) { return rawSet(name, FuncCall::create(func)); } .... that i use like: .set("child_value", &pugi::xml_node::child_value) But child_value is overloaded with const char_t* xml_node::child_value(const char_t* name) const const c...
Define typedefs as: typedef const char_t* (pugi::xml_node::*fn_pchar)(const char_t* name) const; typedef const char_t* (pugi::xml_node::*fn_void)() const; And then write: //if you want to select first member function that takes parameter (char*) set("child_value", (fn_pchar)&pugi::xml_node::child_value); ...
5,684,846
5,686,312
C++ Application crashes once it memory usage reaches 1.5 GB
We have a C++ application running on Windows 32 bit system. It crashes once the memory usage reaches 1.5 GB. What we are unable to understand is why it's crashing at 1.5 GB limit and not at 2 GB limit (the virtual address space and windows 32 bit architecture limit)? Other details:- Total memory available : 4GB Operat...
This is perfectly normal under 32bit Windows. Unless you have the /3gb switch activated, you have a total address space of 2GB. However, that's minus the mapped executable and at least half a dozen DLL and NLS files (for "hello world" -- a real application would probably have more like a dozen or two dozen of them). Si...
5,684,967
5,685,044
How can I copy a CHAR Variable to WCHAR Variable in C++
I want to convert a CHAR file to UNICODE file. I read a file character by character in CHAR file type and then save this character in a CHAR Variable and then I want to copy this CHAR Variable to a WCHAR Variable and then I Write the the WCHAR Variable in to a UNICODE file. here is the code : #include<Windows.h> #inclu...
I have always found these string basics and conversions very useful when dealing with Unicode in C++.
5,685,028
5,685,299
GetModuleFileNameA returns weird results
I'm trying to get the name of a module loaded in another process with GetModuleFileNameA. I've loaded a symbol using dbgHelp and got its module base address but 2 weird thing happen: 1. Sometimes GetModuleFileNameA returns system error codes 5: Access denied. 2. It returns the wrong module name. for a function I know t...
Please read the docs. Right on the page for GetModuleFileName it says To locate the file for a module that was loaded by another process, use the GetModuleFileNameEx function. GetModuleFileName only makes sense for modules in your process. Even if both processes have loaded the module, it may be at a different base a...
5,685,090
5,685,490
ReadFile() says it failed, but the error code is ERROR_SUCCESS
I'm using ReadFile() on Windows to read data from a serial port. This code was working fine at one point in time, but it's now failing and I'm trying to track down the source of the problem, so I doubt it's a problem with the serial configuration or timeouts, since none of that has changed. ReadFile() returns false, in...
I think the key to your observations is the phrase in your source that says "Yet in here, GetLastError() returns ERROR_SUCCESS (0)" The call to GetLastError has to be the very next Win32 call made after the (presumably) failing call. As an experiment, try putting an explicit call to GetLastError() within your failure ...
5,685,093
6,903,159
How to stop thrift TNonblockingServer in C++?
I start a TNonblockingServer from one thread: void *start_server(void *) { server->serve(); return NULL; } pthread_create(&daemon_thread, NULL, start_server, NULL); , and call server->stop() from the main thread, then try to use pthread_join to wait the background thread exiting gracefully. However the main t...
Sorry for the late response You would just need to stop the underlying libevent For example, a slightly delayed stop: tv.tv_usec = 500000; tv.tv_sec = 0; event_base_loopexit(myTNonBlockSvr->getEventBase(), &tv);
5,685,097
5,685,649
How to de-GUI a complex tanglewad C++/Qt4 app?
We have a large messy app written in C++ and Qt4, many library dependencies, hundreds of classes and no coherent structure. It normally runs as a GUI app manipulated interactively, but sometimes it's launched in a hands-off way from another program that feeds it command line options and communicates with it by dbus. ...
The long and hard way is finding out what and how the logic is executed, extract the logic to some QObject based classes (with signals and slots) and make it a QtCore app. I know this doesn't help, but that's the correct way. If setting all GUI elements to hidden (or perhaps only the QMainWindow?) is not an option, thi...
5,685,242
5,685,381
Unable to take input from a file containing string variables
I decided to make a phonebook in c++ and decided to take input of names, address and number from a file. So I made a class called contact and declared the public variables name, address and number. Using a constructor I initialized these to name="noname"(string), number=0(int), address="no address"(string) Now my body...
Hey guys I figured out the problem.... the problem is that i1 should be set to 0 after the second loop and that the file taking input numbers should be f2.open("numbers") and not names....silly mistake!!
5,685,471
5,685,578
Error: Jump to case label in switch statement
I wrote a program which involves use of switch statements, however on compilation it shows: Error: Jump to case label. Why does it do that? #include <iostream> int main() { int choice; std::cin >> choice; switch(choice) { case 1: int i=0; break; case 2: // error here ...
The problem is that variables declared in one case are still visible in the subsequent cases unless an explicit { } block is used, but they will not be initialized because the initialization code belongs to another case. In the following code, if foo equals 1, everything is ok, but if it equals 2, we'll accidentally us...
5,685,500
5,685,602
Detecting integer truncation
Possible Duplicate: Best way to detect integer overflow in C/C++ What is the best way to detect if integer truncation occurred? Edit This should cause truncation being signalled but it doesn't #include <iostream> using std::cout; typedef signed int int32_t; typedef unsigned int uint32_t; typedef signed short int16_...
You can check that the value is the same after the assignment. smallInt = largeInt; if (smallInt != largeInt) { // Truncation } Or, you could check with a mask before: if (my32bitInt & 0xFFFF0000) { // Can't be assigned to a 16 bit value. }
5,685,514
5,685,579
Virtual function breaking private access
I recently came across this article on IBM site. Below is the sample code #include "iostream" class B { public: virtual void f() { std::cout<<"\n In class B"; } }; class D : public B { private: int i; void f() { std::cout<<"\n In class D i = "<<i; } public: D(int i_num):i(i_num) {} }...
Access-specifiers are compile-time construct, and so, the compiler detects any violation of access-rules at compile-time (obviously) based on the static type of the object (or pointer). Such violation cannot be detected at runtime. So bptr->f() works, because the compiler sees that the static type of bptr is B which h...
5,685,560
5,685,582
How can I define a function pointer that takes the same arguments and return value as a given function?
For example, I have a function foo: int foo(int a, int b) { return a + b; } I can define a function pointer: int (*pfoo)(int, int); But how can I do this dynamically in program? I want a function that takes a function as a parameter, and return a function pointer that takes the same arguments and return value...
You cannot do this at run-time (i.e. dynamically); remember that all types (and function pointers are types) are statically determined at compile-time. Imagine if you could do this, and you somehow obtained a function-pointer whose type was variable (i.e. it could point to a float (*)(int,int) or a char (*)(float)). H...
5,685,617
5,687,860
Missing symbols from static library in linked executable
I have a problem with static library symbols missed in linked executable. Here is the description of my problem: I have static library built from several object files. These object files provides sevaral groups of symbols, associated with: A set of C functions and structs (several object files). Let's call correspondi...
Use -rdynamic -Wl,-whole-archive <all your libs> -Wl,-no-whole-archive <boost, pthread and so on> - one of your libs aren't within --whole-archive
5,685,765
5,685,912
Computing FFT and IFFT with FFTW library C++
I am trying to compute the FFT and then the IFFT just to try out if I can get the same signal back but I am not really sure how to accomplish it. This is how I do the FFT: plan = fftw_plan_r2r_1d(blockSize, datas, out, FFTW_R2HC, FFTW_ESTIMATE); fftw_execute(plan);
Have you at least tried to read the more than decent documentation? They have a whole tutorial thought out for you to get to know FFTW: http://fftw.org/fftw3_doc/Tutorial.html#Tutorial UPDATE: I assume you know how to work with C-arrays, as that's what's used as input and output. This page has the info you need for FFT...
5,685,987
5,686,661
How to create `.u3d` files?
I'm working on a project for school and I've got some 3D vector data as well as surface plots. These are saved in .dat files outputted from a c++ program. I'm able to plot these files in gnuplot as wanted, but I'd really like to make .u3d files so I can include them in a TeX document (using the movie15package). How do...
You may use MeshLab, as it can import common 3D file formats, and exports U3D files. From the main page: imports: PLY, STL, OFF, OBJ, 3DS, COLLADA, PTX, V3D, PTS, APTS, XYZ, GTS, TRI, ASC, X3D, X3DV, VRML, ALN. exports: PLY, STL, OFF, OBJ, 3DS, COLLADA, VRML, DXF, GTS, U3D, IDTF, X3D Since that software can be used f...
5,686,134
5,686,157
return reference to dynamically generated 2D array
//header file CGPoint **positions; //Implementation file int rows = 10; int columns = 6; positions = malloc(rows * sizeof(CGPoint)); for(int i=0; i<rows; i++){ positions[i] = malloc(columns * sizeof(CGPoint)); } positions[0][0] = CGPointMake(682, 0); positions[0][1] = CGPointMake(682, 336); positions[0][2] = C...
You should allocate pointer size rather than structure size. CGPointMake(x, y) create the structure in stack rather than heap. Thanks @Bavarious for pointing out that that this is not true. See comment below. :) The code to do what you want: unsigned int row = 10; unsigned int column = 10; CGPoint **points = malloc(r...
5,686,199
5,686,393
How to organize Windows and Android builds of my C++ game?
I would like to develop a Windows build of my Android game for testing and demo purposes. Most of my code is C++, using OpenGL to render, with a thin Android/Java layer that forwards touch events and loads resources. My first thought was to make a Visual Studio project for my Windows version, as I'm familiar with it an...
CDT is a perfectly good Windows development environment. Just make sure that you have installed the Windows SDK. If the concern is that Visual Studio puts a lot of the Windows-specific code in place for you, you might consider starting a new project in it. I'd avoid MFC. Just create a new Win32 project. Then, you...
5,686,459
5,686,527
What is the maximum memory available to a C++ application on 32-bit Windows?
Just wondering if there is a restriction on the max memory that a C++ application uses I understand that this is 2GB - Is that correct? If a C++ app tries to request more then 2GB memory does this cause a memory crash? Final question - If the machine the C++ app is running on is already low on memory and a C++ app asks...
It will cause a dynamic memory allocation failure, which usually will make the resultant application crash, but technically, an application could be written to withstand this event. 2GB is indeed the user address space size for an individual process- an application may use multiple processes (easiest example: Chrome). ...
5,686,487
5,686,536
C++ Project Compiles and Links w/ Missing Library
I'm building an open source C++ library called ITPP in Visual Studio 2010. It builds successfully and so I try to build the test program that comes with it in order to try it. I get linking errors in the test program saying that the first library I built has some linking errors in that it can't find some functions. I ...
Has the test app setup the dependency on the lib correctly? Have you added the directory your new lib is in to Visual Studios search path? (Tools->Options->Projects and Solutions->VC++ Directories). Does the test app list the lib under the linker "additional dependencies" option (check project properties->linker->inpu...
5,686,615
5,686,632
Quick formatted strings in C++
Is there a quick, easy way of getting sprintf-like formatting when constructing a std::string? Something like... std::string foo("A number (%d) and a character (%c).\n", 18, 'a');
Not built into the string's constructor, but you might want to check out boost format. Its a more typesafe sprintf style string formatting. With it you can at least do this: std::string foo = boost::str(boost::format("A number (%d) and a character (%c)\n") % 18 % 'a');
5,686,643
5,687,079
parameter of system() in linux C++,Qt
when I call system() with a long string(and it contains some Chinese characters), system() seems not to deal my parameter correctly. e.g. what system() recieved was not the same with what I sent //it based on Qt void work(QString order) { system((const char*)order.toLocal8Bit()); // in terminal, it shows a wrong...
If you are using Qt, then its better to use QProcess rather than system, see here
5,686,682
5,686,711
Building a Volume Shadow Service app for release
How should an application that uses the Volume Shadow Copy service be built for release? I've been building and testing in Windows 7 and everything looks good so I built the app to test in Windows XP and I get an error on startup: The procedure entry point VssFreeSnapshotPropertiesInternal could not be located in the d...
Take a look at HoboCopy source code. This should answer every question you could have. It's free (for personal use) and C++ src code covers all Windows versions from XP to 2008. Src has moved, anyway start from here.
5,686,814
5,686,843
DevIL and OpenGL in C++
I am writing a C++ OpenGL project using DevIL and I am getting compile-time errors while trying to work out how to load an image to use as a texture. So far I have this //Declarations const char* filename = "back.bmp"; ILboolean ilLoadImage(const char *filename); ILuint image; ilGenImages(1, &image); ilBindImage(image...
Fix the compile error by ensuring you add C++ strings not C strings throw runtime_error(std::string("Unable to load image") +filename); Fix the link error by putting a space in between the libs in Additional Dependencies. Also, if you have to use const_cast, odds are you're doing it wrong. ILboolean ilLoadImage(const ...
5,686,943
5,688,143
Cross compilation tutorials
Possible Duplicate: Cross platform programming I've written some code using wxwidgets in c++. But I am not able to compile the same code for both windows and linux. Actually I'm a bit scared by the preprocessor directives generated by code-blocks ide. I wonder if anyone could point out some nice tutorials for learni...
You could have a look at Cross Compiling wxWidgets Applications on Linux (Code::Blocks wiki) and Cross-Compiling Under Linux (wxWiki). There is also a section on cross compiling Windows applications in Brent W. Woodruff C++ Introduction to wxWidgets.
5,686,976
5,687,051
QRegExpValidator parameters
If I write the following: QValidator *validator = new QRegExpValidator(regExp, this); What does this mean here? What is it referring to? If I don't use it what effect will occur?
this is a pointer to the current class where validator is declared in. its there to let QRegExpValidator know who is the parent of validator so whenever the parent is deleted, so as validator. this way you dont need to delete it manually. More about the this pointer, see here
5,686,977
5,687,108
Using QT Creator how can I set the execution level as requireAdministrator
Basically I need to be able to edit files that require administrator privileges to edit. I know that in Visual Studio a manifest file is used for this - but I understand QT does not have these.
You can use a manifest with Qt applications, but you'll have to do it semi-manually. This blog post Embedding Application Manifest and Version Information using QtCreator shows one way of doing it (adapt the manifest to suit your needs).
5,687,021
5,687,043
sleep command in threaded application
The Sleep(ms) command in windows is causing threads to release their timeslices. Is there an equivalent Sleep(ms) command that halts the thread but does not release the timeslice?
You don't want your thread to sleep (aka suspend), you want to stall it. Do that with a simple loop: #include <time.h> void stall(unsigned ms){ clock_t goal = clock()+ms; while(goal>clock()); } // or maybe higher resolution with some performance profiling functions...
5,687,055
5,687,543
Correct use of `= delete` for methods in classes
Is the following snipplet correct for un-defining all otherwise generated methods and constructors for a class? struct Picture { // 'explicit': no accidental cast from string to Picture explicit Picture(const string &filename) { /* load image from file */ } // no accidental construction, i.e. temporaries and th...
In addition to Xeo's answer: Yes, everything is correct. If you wanted you could eliminate all of the deleted members but the deleted copy constructor and deleted copy assignment and have the same effect: struct Picture { // Also ok // 'explicit': no accidental cast from string to Picture explicit Picture(const ...
5,687,174
5,687,189
Could I create a function based on another function at runtime?
I'm playing with Microsoft's Detours to hook api, for example, I can change what happens when MessageBoxA is called in this way: int (WINAPI* pMessageBoxA)(HWND, LPCTSTR, LPCTSTR, UINT) = MessageBoxA; int WINAPI MyMessageBoxA(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType) { printf("A function is...
In C++, functions aren't first-class object, that means they cannot be created at runtime. However, you can use an array of function-pointers, each pointer pointing to an already defined function, and choosing the appropriate function-pointer at runtime based on some conditions, and call it. And it looks like you're al...
5,687,205
5,688,028
Positioning objects in a 3D Scene and then figuring out what the user clicked on
I'm building a cross-platform game in C++, using OpenGL ES 2.0. The target is iPhone at the moment. I'm a newbie to coding games, but not a newbie to coding. I'm confused about how to architect the game. But specifically, I'm asking about how to setup the objects needed to position models in the scene. I have an obj...
You can either : 1 . compute a line intersection with your model, it depends how complex your model is. 2 . render a label image in an off screen pixmap : instead of drawing with light and textures you use flat colors which are object labels. pick the pointed pixel, the value gives the object. You have to assign labels...
5,687,263
5,687,441
Copying a bitmap from another HBITMAP
I'm trying to write a class to wrap bitmap functionality in my program. One useful feature would be to copy a bitmap from another bitmap handle. I'm a bit stuck: void operator=( MyBitmapType & bmp ) { HDC dcMem; HDC dcSource; if( m_hBitmap != bmp.Handle() ) { if( m_...
You can't -- the source bitmap may not be selected into a DC at all, and even if it is you have no way to find out what DC. To do your copy, you probably want to use something like: dcSrc = CreateCompatibleDC(NULL); SelectObject(dcSrc, bmp); Then you can blit from the source to destination DC.
5,687,269
5,687,284
Confused how to convert from a string to double using strtod() in C++
If someone could explain how to use the function, that would be great. I don't understand the parameters. Thanks
First parameter is a pointer to the chars. c_str() gives you that pointer from a string object. Second parameter is optional. It would contain a pointer to the next char after the numerical value in the string. See http://www.cplusplus.com/reference/clibrary/cstdlib/strtod/ for more infos. string s; double d; d = strt...
5,687,302
5,687,321
How do I make GCC instantiate a class instance with non-trivial const/dest?
I am implementing a profiler. I want to use the Constructor/Destructor idiom to keep track of when I enter/exit a function. A rough outline of my code is as follows: class Profile { Profile(void); //Start timing ~Profile(void); //Stop timer and log }; //... Game::Game(void) : m_Quit(false) { Profile p(); I...
Profile p(); What you've done here is declared a function, called p, that returns an object of type Profile. What you want is this: Profile p;
5,687,312
5,687,344
How can I capture data which will be sent to stdout in c++?
how can I capture data which will be sent to the stdout in c++? I found here: // This can be an ofstream as well or any other ostream std::stringstream buffer; // Save cout's buffer here std::streambuf *sbuf = std::cout.rdbuf(); // Redirect cout to our stringstream buffer or any other ostream std::c...
Write: std::cout << buffer.str(); //not buffer.get(); Now its working : http://ideone.com/W8mW8 By the way, std::stringstream::get() returns std::istream. See this : http://www.cplusplus.com/reference/iostream/istream/get/ Recall that std::stringstream derives from std::istream. So don't get confused. :-)
5,687,386
5,687,476
When a `key/value` is inserted into a `std::map`, does it make its own copy of the objects?
This is inspired by an Item in Effective C# first edition, warning about overriding GetHashCode() naively. Sorry, I do not have supporting code. By the way, this is not a homework, I am just not that familiar with C++/STL, and could not find information regarding implementation. Suppose I create my own class named pers...
When you use std containers all data is copied into the container. For maps this is no different. One restriction that map places on the data is that the key is non mutable. Once it is inserted it is fixed to change the key you must find/erase and re-insert to change the value of the key. struct Person { std::string...
5,687,392
5,687,407
Can I password protect an application?
I have an application which I don't want people to access unless given explicit permission (via a password). More specifically, this application needs to be "locked" during certain hours of the day unless the user enters a password. The ability to check the time is simple. The ability to lock the application is what I...
How about you embed the app in an encrypted disk image bundle? As long as the only user that uses it never copies it from there and properly unmounts the bundle afterwards, i think it would accomplish what you want: Create a new encrypted disk image (DMG) using Disk Utility (this allows you to enter a password), store...
5,687,494
5,687,608
Putting non-copyable objects into std-containers
Is this class design the standard C++0x way to prevent copy and assign, to protect client code against accidental double-deletion of data? struct DataHolder { int *data; // dangerous resource DataHolder(const char* fn); // load from file or so DataHolder(const char* fn, size_t len); // *from answers: added* ~...
Your example code looks mostly correct. const DataHolder &&other (in two places). if(&other!=this) in your move assignment operator looks unnecessary but harmless. The initializer list vector constructor won't work. This will try to copy your DataHolder and you should get a compile time error. The push_back and empl...
5,687,540
5,687,553
Non-type template parameters
I understand that non-type template parameters should be a constant integral expression. Can someone shed light why this is so? template <std::string temp> void foo() { // ... } error C2993: 'std::string' : illegal type for non-type template parameter 'temp'. I understand what a constant integral expression is...
The reason you can't do this is because non-constant expressions can't be parsed and substituted during compile-time. They could change during runtime, which would require the generation of a new template during runtime, which isn't possible because templates are a compile-time concept. Here's what the standard allows ...
5,687,653
5,687,673
Where is the QDialog result value stored?
If I have the QDialog result value as QDialog::Accepted, where is such value stored? And, what is the benefit of knowing such value? Thanks.
You can get it by calling QDialog's result() method. And it allows you to know if the user clicked "OK" or "Cancel" (or any similar option) on the dialog.
5,687,706
5,687,999
Understanding VerQueryValue
On MSDN I noticed the following for the VerQueryValue function: lplpBuffer [out] LPVOID When this method returns, contains the address of a pointer to the requested version information in the buffer pointed to by pBlock. The memory pointed to by lplpBuffer is freed when the associated pBlock memory is freed._ How...
VerQueryValue returns a pointer to somewhere inside the initial block of memory that you allocate (GetFileVersionInfoSize returns the size of a block that is large enough to contain the whole version resource + any space required for ansi to unicode conversion etc)
5,687,714
5,687,738
How do I rewrite this line of code in Qt?
In the C++ GUI Programming with Qt 4 book, in gotocelldialog.cpp, it has the following line of code: okButton->setEnabled(lineEdit->hasAcceptableInput()); Can this line be rewritten as follows? if (lineEdit->hasAcceptableInput()) okButton->setEnabled();
No, setEnabled requires a boolean parameter. See the documentation for QWidget.
5,687,928
5,687,939
execv() quirks concerning arguments
I'm trying to output the results of 'ps' for an assignment, but I've ran into some slight quirks that I'd like to figure out. This works correctly, and displays ps's output in the shell: //Create "ps -u laser" int pid_ps = fork(); char *argv[1] = {"-u laser"}; if (pid_ps == 0) { execv("/bin/ps", argv); } Now, this ...
Use char *argv[] = {"/bin/ps", "-u", "laser", 0}; - the first argument is the executable name. EDIT: Sample. int pid_ps = fork(); if (pid_ps == 0) { char *argv[] = {"/bin/ps", "-u", "laser", 0}; execv("/bin/ps", argv); } The above snippet is tested and working.
5,687,964
5,688,614
QListView item background color
I'm trying to change the background color of the item which currently has the mouse hover. What I've done so far is: I subclassed QListView and in the ctor: connect(this,SIGNAL(entered(QModelIndex)),this,SLOT(enteredSlot(QModelIndex))); The job basically needs to be done in the slot enteredSlot(QModelIndex) but I have...
You can achieve what you are trying to do a bit easier by setting a style sheet for your QListView. If you haven't worked with style sheets before you may want to back track in the documentation a bit but most common activities related to customizing the appearance of widgets can be done using them. Do not confuse them...
5,688,127
5,688,168
Can I use the insert function to add elements into a vector of vectors?
I would like to know, can I use insert keyword to add elements into vector of vector? For example, I have a vector vector<int> temp1; for this vector, elements add within the inner for loop. at the end of out for loop, I need to add the elements to temp1; vector<vector<int> >temp1; for (int a;a<size(),a++){//... vec...
Question: temp1[a].insert(temp1[a].end(),temp2.begin(),temp2.end()); Reinstated prior answer: To append a range of values to an existing vector: std::copy(temp2.begin(),temp2.end(), std::back_inserter(temp1)); To append the range as a new vector to an existing vector_of_vectors: vector<vector<int> > vecvec; vector<i...
5,688,161
5,688,192
porting C# to android
i'm trying to code an app that creates a spherize filter on a jpeg. i've been struggling for a while with java code that does the distortion due to bufferedimage not being supported on android. i've been given this link that give a fisheye distortion written in C#. i'm considering porting this code to android using the...
What you may want to do is port it using opengl es (http://www.khronos.org/opengles/) first, and your development machine. Once you get there then getting it to the android will be easier. Did you write this in C# using the DirectX library originally? You may want to just use OpenGL ES from Java also (http://developer....
5,688,197
5,688,250
boost::filesystem How having a correct path to file read it into stringstream?
So I have a path p and I can call for example is_regular_file(p) and file_size(p) on it but how to read that file into stringstream? (btw I need only to read it)
I assume you want to copy the entire file into the stringstream. std::stringstream ss; ss << std::ifstream( p.string().c_str() ).rdbuf(); Here is a kind of inside-out demo: Shadow:code dkrauss$ ./ssclone ssclone.cpp #include <sstream> #include <fstream> #include <iostream> int main(int, char *argv[] ) { std::strings...
5,688,203
5,688,227
How do you create pseudo random numbers sequentially in c/c++?
srand(time(NULL)); for (it=hand.begin(); it < hand.end(); it++) (*it) = rand() % 13 + 1; This code does not work to create many random numbers at a time. Is there a way to do it that isn't as complex as Mersennes and isn't operating system dependent?
PRNGs don't create many PRNs at once. Each output is dependent on the previous output, PRNGs are highly stateful. Try: srand(time(NULL)); // once at the start of the program for( int i = 0; i < N; ++i ) r[i] = rand(); Even APIs that return an entire block of output in a single function call, have just moved that...
5,688,294
5,688,322
Pure virtual function call
I'm using boost.python to make python-modules written in c++. I have some base class with pure virtual functions which I have exported like this: class Base { virtual int getPosition() = 0; }; boost::python::class_<Base>("Base") .def("GetPosition", boost::python::pure_virtual(&Base::getPosition)); in Python I ...
This error happens when a constructor or a destructor directly or indirectly calls a pure virtual member. (Remember that during constructor and destructor execution, the dynamic type is the constructed/destructed type and so virtual members are resolved for that type).
5,688,355
5,688,412
Partial specialisation of member function with non-type parameter
I have a template class with both a type and a non-type template parameter. I want to specialize a member function, what I finding is, as in the example below, I can do a full specialization fine. template<typename T, int R> struct foo { foo(const T& v) : value_(v) {} void bar() { std::...
You can wrap the function inside a class. Only classes, not functions, may be partially specialized. template<typename T, int R> struct foo { foo(const T& v) : value_(v) {} void bar() { return bar_impl< T, R >::bar( * this ); } friend struct bar_impl< T, R >; T value_; }; ...
5,688,417
5,688,433
How to initialize unsigned char pointer
I want to initialize an unsigned char * buffer of length 1500 so that I can store values in it from some other sources.
If you want it on the heap, unsigned char* buffer = new unsigned char[1500]; if you want it on the stack, unsigned char buffer[1500];
5,688,704
5,688,750
Regular Expression For Assembly Instructions
I'm currently writing my own parser for a fictional Assembly language. The instructions are very similar to any normal assembly instruction: [INSTRUCTION] [OP]* where op can be 0-3 operands. I want to be able to use an expression that matches this. This is being written in C++ with boost::regex. I myself am a regexp n...
A string like: ADDI 8, 8, 10 can be matched by a regex like this: [a-zA-Z]+[ \t]+-?[0-9]+([ \t]*,[ \t]*-?[0-9]+)* A (short) explanation: [a-zA-Z]+ # match an instruction [ \t]+ # match one or more spaces or tabs -?[0-9]+ # match an integer value with an option minus sign in front of it ( # open gr...
5,688,710
5,770,124
Templates and runtime component loading in a component-based game engine
Suppose I have an component based game engine, and in that engine I have an object that stores a repository of properties in a form of a stl map and can be accessed through the object access() method, which is a templated call so you can access and store any type of data into the repository, eg: class component { p...
Besides of the wrong signature of access in your code, it all boils down to how your platform deals with instantiating global objects from shared libraries. As I see it, you will end up with different instances of std::map<std::string, Whatever> per library loaded into process...
5,688,719
5,688,737
New, delete, and subclasses in C++
TextItem is a subclass of XObject. I am trying to figure out why the following works: TextItem *textItem = new TextItem(); XObject *xItem = textItem; delete textItem; But this does not: TextItem *textItem = new TextItem(); XObject *xItem = textItem; delete xItem; The second example fails on delete, with a...
XObject *xItem = textItem; delete xItem; This would work only if XObject has virtual destructor. Otherwise, the delete statement invokes undefined behavior. class XObject { public: virtual ~XObject(); //^^^^^^ this makes virtual destructor };
5,688,781
5,689,158
Why C++ can't see my lua script file?
I have a simple problem with integrating Lua with c++. I have my project in Visual Studio : http://i.stack.imgur.com/nNw6H.png and I run my lua_init() function : bool lua_init(std::string &luaScriptName){ // Create the Lua state. Explanation from Lua 5.1 Ref. Manual: globalL = luaL_newstate(); // 5.1 OK - Lua 5.0 or...
Your code will exectue where the binary is, or in the target directory in Debugging Mode. So check that your lua file is accessible to your binary when you execute it. If it's with your source files, sure, it's not accessible.
5,688,811
5,689,044
Yet another C++ list question
Im quite stuck here and I have tried my best but I could not solve it. I would like to do this: list<Enemy> *_myEnemies; Enemy* _myEnemiesPushBack; _myEnemiesPushBack = new Enemy; _myEnemiesPushBack->load("earth.png"); _myEnemiesPushBack->setPos(150, 150); _myEnemies->push_back(_myEnemiesPushBack); //error here The e...
You don't need pointers, at all. std::list<Enemy> myList; Enemy en; en.load("earth.png"); en.setPos(150,150); myList.push_back(en); typedef std::list<Enemy>::iterator iterator; for (iterator it = list.begin(), end = list.end(); it != end; ++it) { it->move(); } I would also encourage you to fetch a book about C++ s...
5,688,902
5,689,077
Is PhysicsFS platform-independent?
I'm thinking about using PhysicsFS in my game engine project, but I'd like to first make sure it's entirely platform-independent. That's because I'd like to port my engine to some rather obscure platforms after I'm done with the Windows code (Wii Homebrew, for example).
In accordance with the official specs the developers provide on their site it: Compiles/runs on GNU/Linux (x86, PPC, MIPS, Sparc, Alpha, Itanium, and x86-64 tested; gcc). Compiles/runs on Windows, Win95 and later (x86 tested; Visual C++, Visual Studio, Cygwin, and MinGW). Compiles/runs on Mac OS X (x86 and PPC tes...
5,689,122
5,689,219
How to initialize a zero array in c++
int M=7; int N=6; int i=0; int x=N*M; int val3[x] = {}; for(int i=0;i<x;i++) { //some calculations if (my condition) { //if this condition ok, change value of val[i] } cout << i << " " << val[i] << endl; } I want to initialize a zero array(val), I used above codes, but I got...
Alternatively to the std::vector suggested above, you could also do: int M=7; int N=6; int x=N*M; int* val3 = new int[x]; memset(val3, 0, x * sizeof (int)); for (int i = 0; i < x; i++) { // ... } // ... delete [] val3;
5,689,366
5,689,384
Is it possible for a non-member function to return a const value?
If so, how? Does this question even make sense? In my case it would make no sense to have the returned object modified by the caller, so I want to mark it as non-modifiable.
const MyClass foo(); is valid, but returning a const value doesn't make sense - it's copied anyway. You can return e.g. a const reference: const MyClass & foo(); is also perfectly valid. This doesn't prevent the user from making a copy though. If you're thinking about const MyClass * foo(); then the const is more mean...
5,689,421
5,697,577
Boost ptime: how to format data in a way browsers send inside headers of http requests?
I need to format my ptime in such way Wed, 21 Jan 2004 19:51:30 GMT How to do such thing with boost? (so it would look like data format of HTTP servers Expires and Last-Modified and Date response headers )
#include <locale> #include <string> #include <iostream> #include <sstream> #include <boost/date_time/posix_time/posix_time.hpp> std::string current_time_formatted() { namespace bpt = boost::posix_time; static char const* const fmt = "%a, %d %b %Y %H:%M:%S GMT"; std::ostringstream ss; // assumes std::c...
5,689,432
5,689,792
linked list C++ , question selflearning
#include <iostream> using namespace std; struct Node { int item; // storage for the node's item Node* next; // pointer to the next node }; Node* addNode(Node*& head, int data , int& count) { Node * q; // new node q = new Node; // allocate memory for the n...
Since I'm not sure every answer completely answers it, here's a linked list implementation (written without testig: // your (correct) structure struct Node { float item; // storage for the node's item Node* next; // pointer to the next node }; Now we need two pointers somewhere to look after the list: /* ...
5,689,437
5,689,529
Compile a .cpp file to an EXE inside of a program (EXE file)
I want to make a program (EXE file) that will take the user defined settings and make a custom (EXE) file for the user inside of the previously mentioned program (EXE). Is there like a portable GCC or something? Please be as detailed as possible. I am not really sure where to start with this one.
The compiler itself is just another program which reads some input (source code) and writes some output (object code, or executable if it runs the linker too). You can use something like the system() call to execute a compiler, for example with gcc: system("g++ -o test test.cpp"); That will run the compiler (g++), tel...
5,689,504
5,689,609
Regular Expression library in C/C++
I want to write regular expression library in C/C++. What is the good starting point , any books or articles. I know there are may libraries are available , but I want to write my own version.
A good starting point is to use existing implementations and criticize them. Pay attention to data structures and design decisions you don't like. Avoid them when you write your version.
5,689,542
5,689,571
How do I initialize an array when an object is created?
I'm not sure how to use array variables with objects. How do you initialize an array when an object is created. An array that is a data member of an object. I'm hoping to use an initialization list.
An array member variable can only be default-initialized, you cannot provide explicit initialization values. struct Foo { Foo() : bar() {} // Default-initialize bar, for int this means initialize with 0 int bar[10]; }; If you want anything else, you'll have to assign in the constructor body. struct Foo { Foo() ...
5,689,845
5,689,887
Doubly Linked List InsertBack Method problem
Alright so for some reason this code is not quite working for my insertBack function for the doubly linked list template class Dlist. template <typename T> void Dlist<T>::insertBack(T *o) { node *findLast; node* newNode = new node; newNode->next = NULL; newNode->prev = NULL; newNode->o = o; if ...
If it's a doubly-linked list and you're keeping track of the last node... why are you iterating all the way through it to append to the end? All you have to do is: node* newNode = new node; newNode->o = o; newNode->previous = last; last->next = newNode; last = newNode;
5,689,860
5,690,585
Display a hyperlink in Visual Studio Output window using OutputDebugString()
I find it very useful to be able to include hyperlinks in the debug output of my test suite like this: OutputDebugStringA("file://c:/path/index.html") The above command prints the quoted URL to the output window as a hyperlink. It can be CTRL-clicked and the specified HTML file will open in a new IDE tab. In itself, ...
You're basically at the mercy of however the output window is implemented; I'm guessing it's just hotting up things that look like URLs and probably doesn't support HTML. Maybe you can develop a Visual Studio add-in that behaves similar to the output window that supports HTML.
5,689,908
5,689,928
Check if string.at(i) is a whitespace C++
I want to check if a char (string.at(i)) is whitespace in C++. How can I do this easily? I got this code example, and I was thinking to change the _____ with something, but don't know what. I've tried with ' ', but that didn't work. for(int i = 0; i < string.length(); i++) { if(string.at(i) == _________) { ...
#include <cctype> if (isspace(string.at(i)))
5,690,002
5,690,042
What book would cover theory for 3D game development mathematics?
I have had absolutely no trouble learning C++ and object oriented programming through books. However, I really want to head into 3D game development but I feel my math skills are pretty underdeveloped for this. I want to understand dot products, cross products, normals, vectors etc. I also hear calculus is very importa...
Any of the books by Dave Eberly ( http://www.geometrictools.com/ ) like "3D Game Engine Design" or "3D Game Engine Architecture" would be decent places to find this information, directly related to 3D game development. His website contains a wealth of information as well. Another one that comes to mind is the Realtime...
5,690,186
5,690,203
Is it faster to port data from a C++ program to a Java program's input via sockets than via a raw json or xml file on the server?
What's the best way to go about things in terms of speed/performance? Where do things like "Apache Thrift" come in and what are the benefits? Please add some good resources I can use to learn about any recommendations! Thanks all
Presuming you mean both processes are already running, then it's going to be via sockets. Writing a file to the disk from one process then reading it from the other is going to incur the performance hit of the disk write and read (and of course whatever method you employ to keep the reader from accessing the file until...
5,690,349
5,690,414
std::bind not working
I can't get std::bind to work the same way boost::bind works. Either I'm not using it correctly, or my compiler (GCC 4.4.5) doesn't implement it correctly yet. I have two functions: void f(int x, int y) { cout << x << " | " << y << endl; } template <class UnaryFunction> void g(UnaryFunction func) { func(100...
It looks like it's just your version of compiler, gcc 4.5.1 (via ideone.com) and 4.6.0 compile it correctly.
5,690,443
5,694,563
my program is leaking with resource owned by boost::shared_ptr
I can't see why my program is leaking, maybe you can spot it. typedef boost::shared_ptr < std::string > StringPtr; typedef std::pair < HWND, StringPtr > WMapPair; typedef std::map < HWND, StringPtr > WindowMap; // this callback populates the WindowMap (m_Windows) by adding a WMapPair each time BOOL CAL...
Not going to answer your question (as I can;t see any problems) but a couple of points: typedef std::map < HWND, std::string > WindowMap; typedef WindowMap::value_type WMapPair; // In the future it may not be a pair. // Or you may change the...
5,690,484
5,690,485
Parse tree doesn't work
I want to build simple parse tree/but it's not working. I think that strlen is returning the wrong result. #include <stdio.h> #include <string.h> #include <stdlib.h> #include <conio.h> int min(int a ,int b){ return (a>b)?b:a;} class Node { Node* left; Node* right; char operation; public: float res; ...
It seems like you are doing C with class more than C++. Try using std::string insted of char *. This way you won't have any trouble with strlen (if strlen is really the problem) because string has a size() function and it is garantied to work very well. Most of all you'll be able to use many features that you are tryin...
5,690,571
5,690,586
Is it necessary to lock around STL containers in order to read their data?
I am writing a multi-threaded server, which contains 5 or 6 global data structures (maps, vectors, etc.) and am trying to figure out if I need to hold mutexes for certain data in order to read values from maps or vectors, or if it is only necessary to hold a mutex when I am going to alter the data/add new items.
You need to synchronize access to the container if multiple threads are accessing the container and at least one of those threads is modifying the contents of the container. If none of the threads ever modify the contents of the container, you do not need to synchronize access to it. [Note that the C++ Language Standa...
5,690,901
5,690,923
C++ Extract std::string from a variable-length argument list
Hey everyone! I'm trying to make a simple copy of sprintf that returns the formatted string, but I am coming into a small snag... Apparently, using a variable-length argument list you cannot pass a std::string instance. I already have the parser working properly with int, double, float, char, const char*, char*... I h...
No -- as the compiler said, you're only allowed to pass objects of POD type to a variadic function. What you normally want to do is eliminate using a variadic function in the first place, such as by using an iostream instead of something like printf (or a stringstream instead of sprintf).
5,691,050
5,691,837
What is a good way to store the locations of models in a 3D scene?
I'm wondering what the best way is to store the positions of objects in a 3D scene. In my case, the scenes are actually levels of a game. Each Scene has: It's own projection matrix. A list of models to render Each Model has: The vertex list A GLSL program to render itself A texture A "model" matrix I'm using GLES ...
In general, you want as few matrix calculations as possible per frame, as those are pretty expensive. So in your entity classes, store their position, rotation, scaling absolut values in seperate 3D vectors (the rotation maybe even in a quaternion), and only during rendering connect those to a matrix.
5,691,099
5,691,125
char to uppercase assignment segmentation fault
In an effort to learn more about the inner workings of c++ I decided to write my own string class. However I am stuck on the .toUpper() and .toLower() functions. Here is my code. Text& toUpper(){ char* c = this->str; while(*c != 0, c++){ if((*c >= 'a') && (*c <= 'z')){ *c =...
Change your while loop to this: while(*c != 0){ if((*c >= 'a') && (*c <= 'z')){ *c = *c - 32; std::cout << *c << std::endl; } c++; // Should be here } See these: Your code Edited Code. From Wiki: In the C and C++ progra...