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
7,270,533
7,270,565
Search a stack recursively, but leave the stack intact
I have been trying to write a recursive function that searches a stack, but leaves the stack in its original state. I may pus h and pop the stack, but not use a helper stack or any other data stucture. And yes, this is homework, so I do not expect a complete coded answer :). A little help about how to approach the stac...
you should store the pop()ed value, and the recursive call result, and push() the pop()ed value back, before returning. your else should look something like that: [other than it, it looks fine] else temp = s.pop(); retVal = getNth(s, n); s.push(temp); return retVal; (*)forgive me for not declaring tem...
7,270,617
7,270,663
QFileDialog painting problem while multithreading
I have two threads, the main one for GUI and the other for intense processing. A signal/slot connection 'connects' the threads so that when the proc thread emits the signal, a new QWidget is added on the GUI by the main thread's slot. The problem is that I want to diplay a QFileDialog::getOpenFileName when the user cli...
In the handler you could use a list where you push the new items to be drawn on while you display the QFileDialog. When you are done with the QFileDialog you process all the items that are in this list.
7,270,639
7,270,699
Why does intel compiler produce output that requires libiomp5mt.dll, even though I ask for static linking?
I'm compiling an openmp project with the /MT switch (or equivalently in visual studio settings, "C++: Code Generation: Runtime Library: Multi Threaded". Visual Studio still, however, reports that my output requires libiomp5mt.dll (multi threading dll) when I thought the above setting was asking for static linking. Is t...
The Intel website says: You are strongly encouraged to dynamically link in the compatibility OpenMP* run-time library libiomp (i.e libiomp5md.lib and libiomp5md.dll , located in the [Compiler Dir]\lib directory), even if other libraries are linked statically. Linking to static OpenMP* run-time library (i.e libiomp5mt....
7,270,742
7,271,996
C++ fwrite doesn't write to text file, have no idea why?
I have this code that basically reads from file and creates new file and write the content from the source to the destination file. It reads the buffer and creates the file, but fwrite doesn't write the content to the newly created file, I have no idea why. here is the code. (I have to use only this with _sopen, its pa...
Change your code to the following and then report your results: int main () { std::string szSource = "H:\\cpp\\test1.txt"; int iFileId = _sopen(szSource.c_str(),_O_RDONLY, _SH_DENYNO, _S_IREAD); if (iFileId >= 0) { FILE* pfFile; if ((pfFile = fdopen(iFileId, "r")) != (FILE *)NULL) { //read fi...
7,270,774
7,270,832
Copy constructor converts from const to non-const?
Consider the following : class A { public: int xx; A(const A& other) { cout << "A cctor" << endl; /* do some stuff */ } A(int x) : xx(x) {} /* conversion constructor */ }; int main() { A a = 1; A other = a; return 0; } Is it right to say that CCtor converts...
No idea what you mean. A(const A&) is a typical copy-ctor, which has a "read-only" access to its only argument. If you pass anything const, everything is fine. If you pass anything non-const, for ctor it becomes const. A a = 1 is a conversion ctor, as you said. A other = a is a copy ctor. What's the question? Regarding...
7,271,154
7,271,217
How to get pid from pthread
in RH Linux, every pthread is mapping to a pid, which can be monitored in tools such as htop. but how can i get the pid of a thread? getpid() just return the pid of the main thread.
pthread_self(); Can be called to return the ID of the calling thread. Also PID is process Id, A thread has thread Id not PID. All threads running in the same process will have the same PID.
7,271,307
7,271,321
Interacting with a simple database in c++?
I'm making a game in c++ that will need to store and retrieve information about players (name, email, high score) etc. I thought of trying to just do it myself with XML but I think a real database (maybe SQL?) would do a better job since over time there may be thousands of users. Are there libraries to do simple intera...
Yes, SQLite will do exactly this. It stores the database as a local file, so if you want an online database server then this is perhaps not the best option.
7,271,792
7,271,888
PHP Warning: PHP Startup: Unable to load dynamic library: /home/lib.so so: undefined symbol: __gxx_personality_v0 in Unknown on line 0
i've managed to succesfully create an .php extension. I would like to move further. Insted of using the .cc that i want my .php to link with i would like to add the library.so. When compiling i have this error. how to solve it? thx. appreciate EDIT: I succed to compile it. now i have this error: undefined symbol: _ZN3...
I guess you need to link with libstdc++. Or compile with g++ instead of gcc, then libstdc++ will be linked by default.
7,271,854
7,271,920
C++ Boost Read CSV data and add double quotes to certain columns then re-write back to file
I have CSV data file contained follow info: -0.2500000000,15,15;15;15;15;15;15;15;15;15;15;15;15;15;15;15;15;15;0;0;0;0;0;15;0;0,0,0 I only want to add double quotes around those data with semi-colon between them. And I know a specific data that needs to add double quotes. After add double quotes it should be like th...
If you format is as simple as you describe, I'd use boost::split given the string and the delimeter of ','. Then just put quotes around any string that contains a ;. Similar to this: // warning: pseudo code... std::string line_from_file; std::vector<std::string> split_line_to_file; boost::split(split_line_to_file, ...
7,272,093
7,272,147
What happens when an exception goes unhandled in a multithreaded C++11 program?
If I have a C++11 program running two threads, and one of them throws an unhandled exception, what happens? Will the entire program die a fiery death? Will the thread where the exception is thrown die alone (and if so, can I obtain the exception in this case)? Something else entirely?
Nothing has really changed. The wording in n3290 is: If no matching handler is found, the function std::terminate() is called The behavior of terminate can be customized with set_terminate, but: Required behavior: A terminate_handler shall terminate execution of the program without returning to the caller. So the...
7,272,169
7,272,229
Command-line arguments in C++
Many of my programs take in command-line arguments, one example is as follows: a.out [file-name] [col#] [seed] Then if I want to use the arguments, I have nice, easy-to-use functions such as: atof(argv[..]) and atoi(argv[..]) I was wondering if such easy/simple functions exist for C++. I tried to simply do this: cin ...
Solution 1: You can use lexical_cast in place of atoi int x = boost::lexical_cast<int>("12345"); Use boost::lexical_cast in try-catch block though. It throws boost::bad_lexical_cast when the cast is invalid. Solution 2: If you are not using Boost and need a standard C++ solution you can use streams. std::string hel...
7,272,561
7,275,560
How do I get Xcode 4.1 code completion to work automatically?
I just bought a MBP and trying out Xcode. I know code completion works fine when pressing 'Escape', but how can it work automatically with Xcode 4.1? For example, pressing down '.' in C++? I read several posts on this. Some suggest going to preferences and turning it on, but I didn't see any option. Can you please prov...
In the preferences > Text editing > Editing > Code completion > Suggest completion as I type.
7,272,991
7,273,031
Assignment operator on only one of two parents
Child has two parents: Foo and Bar. Foo does not allow copying. Bar does. How can Child use Bar's assignment operator to copy into Bar's subset of Child (while leaving Foo's subset intact)? To be more concrete: in the code below, how can Child refer to just Bar inside replace_bar()? (How would you modify line (X) to ma...
void replace_bar(const Bar& bar2) { Bar::operator=(bar2); } In other news, you're missing a return *this; in Bar::operator= and if all you want to do is prevent copy of Foo you shouldn't define the copy constructor and assignment operator, only declare them. That way even if you try to use them from within the cl...
7,273,040
7,273,088
C++ Size of classes and subclasses
If a class instance uses 20 bytes, and its subclass uses 24 bytes since it as more members, how is it possible to store an instance of the subclass in a variable of the parent class? Like: Subclass s; ParentClass p ; p = s;
You don't "store" instances "in" pointers. Pointers merely point at the start of the instance in memory. The pointer object itself contains a memory address, and the space that this takes up is always the same no matter what — or how much — data may be found at that address. Edit (since the question has changed almost...
7,273,085
7,273,155
C++ Access Violation
I'm working on an existing data parsing program that overlays a struct onto a buffer in order to extract values. Recently a new data format has been added to the buffer and requires a new struct. I abstracted functions into a common base class and defined a new struct like this: struct Header { Header () { } pub...
You seem to be using the memory in buffer without constructing an object there. Since Header is polymorphic it contains a virtual table pointer and you can't initialize its data directly (legally you can't even if it's a POD but you would probably get away with it). You should be using placement new in order to constru...
7,273,326
7,273,372
Getting the nth line of a text file in C++
I need to read the nth line of a text file (e.g. textfile.findline(0) would find the first line of the text file loaded with ifstream textfile). Is this possible? I don't need to put the contents of the file in an array/vector, I need to just assign a specific line of the text file to a varible (specifically a int). P...
How about this? std::string ReadNthLine(const std::string& filename, int N) { std::ifstream in(filename.c_str()); std::string s; //for performance s.reserve(some_reasonable_max_line_length); //skip N lines for(int i = 0; i < N; ++i) std::getline(in, s); std::getline(in,s); return s...
7,273,340
7,273,381
Array contents equality in C++
Is there a way to get the equality operators to work for comparing arrays of the same type? For example: int x[4] = {1,2,3,4}; int y[4] = {1,2,3,4}; int z[4] = {1,2,3,5}; if (x == y) cout << "It worked!" I'm aware that as is, it's just comparing pointer values - but I was hoping there's some kind of typedef trick or s...
You can use standard equal algorithm if (std::equal(x,x+4,y)) cout << "It worked!";
7,273,444
7,273,508
Can a hit and trial matrix take place in a recursive function without creating multiple copies?
I have a matrix which needs to be changed by hit and trial method, evaluated and the values need to be re-assigned if it does not meet the requirements. I am doing this in a recursive function for chained assumption. Can this be done without creating multiple copies? Can I restore the matrix while backtracking?
You ask: "Can I restore the matrix while backtracking?" I ask the same question - can you? If the modifications are easily reversible, then sure you can. void f() { foreach (possibilty) modify (); f(); unmodify(); } If unmodify is not trivial, then you'd be better off with void f(matrix m...
7,273,688
7,279,556
Expressing Church Numerals with Boost.Bind
Church numerals can be expressed in C++0x (C++11?) using the new lambda parts of the language using something like this: typedef function<int(int)> F; static const F id = [=](int x) { return x; }; function<F(F)> church(unsigned int i) { if(i == 0) { return [=] (F f) { return id; }; } return [=] (F f) { ...
Ok, I don't know anything about church numerals, and I haven't actually tested this code, but something like this should work :) HTH! // forward boost::function<F (F)> church(unsigned int i); typedef boost::function<int (int)> F; int idFunc(int x) { return x; } static const F id = boost::bind(&idFunc, _1); F Chur...
7,273,731
7,273,782
c++ weird problem converting a char to int
I'm a total newbie to C++ and I was trying to do one of the problems from Project Euler when I had a very weird problem. I reduced the error to the following. Consider the following simple code: #include <iostream> using namespace std; int main() { int numdigits; cout << "digits: "; cin >> numdigits; ...
The problem is here: char tmpchar; cin >> tmpchar; cout << atoi(&tmpchar) << endl; atoi expects a NUL-terminated string, which isn't what you're giving it (there's no NUL character except that you may be sometimes getting one by chance). A possible (ugly) fix is: char tmpchar[2] = {0}; cin >> tmpchar[0]; cout << atoi(...
7,274,028
7,278,460
Using HTML Tidy in Visual C++ 2010 Windows Forms project
I am using VC++ 2010 Express and I am attempting to include HTML Tidy to perform cleanup on HTML code strings. What I want to do is process the HTML as a string (NOT from a file) and save the processed cleaned HTML to a string (NOT to a file). The project is a C++ Windows forms project, the compiler is /CLR. I have att...
It's been almost 48 hours struggling with this problem. Solution discovered! Here it is... Using the very simple .NET wrapper from here http://www.codeproject.com/KB/cs/ZetaHtmlTidy.aspx converted the VC project to VC++ 2010 ok and compiled as a DLL ok. Below is the code I used to call it: System::String^ TidyMyHTML...
7,274,268
7,274,637
which is faster? "vector of structs" or "a number of vectors"?
Solution 1: If i have a class like, class car{ public: int a; string b; bool c;}; i can build a vector of 200 cars: std::vector<car> allcas; allcars.resize(200) at runtime, i just do: this_car=allcars[102]; then .... Solution 2: i have std::vector<int> a; a.resize(200); std::vector<string>b; b.resize(200); s...
A "struct of vectors" has a couple of advantages over a "vector of structs": If your inner loop doesn't use every element of the struct, then struct-of-vectors can save on memory bandwidth, as unused element vectors will not be loaded into cache. It is easier to vectorize. A struct-of-vectors may enable you to use th...
7,274,367
7,274,504
How to access a specific value in a text file using C++
my text file has this structure and this values 15.32 15.00 14.58 14.36 17.85 01.95 15.36 14.58 21.63 25.00 47.11 48.95 45.63 12.00 74.58 52.66 45.55 47.65 15.55 00.23 78.69 each column is a different type of data, the first column is weigh , second is size and so on. the user requests for instance the weight, which...
An even easier way is to make a function with two parameters: the starting item and the "stride", or the number of items per row. You can then skip items until the starting item and then skip the stride between successive items: void printcolumn(int start, int stride, ifstream &in) { string nextToken; // skip unti...
7,274,393
7,276,118
Decrypt Firefox password database
I want to write a simple utility that extracts passwords from a Firefox password database (the corresponding file is called signons.sqlite in the profile folder). What I've done so far: Opened database using sqlite, retrieved encrypted username, encrypted password and address of website (all stored as std::string). So,...
It could be that the call to PK11_Authenticate() isn't optional, even if no master password is set (yes, NSS is pretty messed up). So you might need to do the following first: PK11SlotInfo *slot = PK11_GetInternalKeySlot(); if (!slot) cout << "Error getting internal slot" << endl; SECStatus tmp = PK11_Authenticate(slo...
7,274,493
7,274,975
C++ Child classes - reusing overloaded operators?
I've got kind of an issue here with c++ - I've got two classes: class vec and class vecD : public vec class vec overloads pretty much any operator - some of them (as +=) return an object of the class itself for obvious reasons. Now my questions is: is it possible to reuse the overloaded functions of vec for vecD but re...
Judging by the comments, this might also interest you: //this is used as a common base, so that you don't have to write the gory //details twice. Only once. template<typename TYPE> class vec_base{ protected: TYPE *val; int dimension; vec(); /*protected so only vec can use vec_base, nobody else*/ ~vec(...
7,274,692
7,274,768
Can/do compilers simplify logical expressions involving functions?
Some functions which calculate booleans: bool a() { return trueorfalse; } bool b() { //... } bool c() { //... } This condition //somewhere else if((a()&&b()&&c()) || (a()&&b()&&!c()) ) { doSomething(); } can also be written as if(a()&&b()) { doSomething(); } Will compilers usually optimize this awa...
Since the functions may have side effects, the conditional cannot be "optimized" in any way, since all the functions will have to be called (conditionally) in a well-defined manner. If you do want optimization, you can assign the result to variables first: const bool ba = a(), bb = b(), bc = c(); if (ba && bb && bc ||...
7,274,723
7,275,448
Virtual method causes compilation error in Derived class
Consider the next code : #include <iostream> using namespace std; class A { public: virtual int f() {cout <<"A:: f()\n"; return 1;} virtual void f(int) {cout <<"A:: f(int)\n";} virtual void g() {cout <<"A::g()\n";} }; class B3 : public A { public: void f() {cout <<"B3::f ()\n";} }; int main() { ...
Don't confuse overriding with hiding. You override virtuals. Your class definition is equivalent to: class B3 : public A { public: virtual void f() {cout <<"B3::f ()\n";} }; Once a function declared virtual, it will remain virtual for all classes deriving from your base class, regardless of whether you explicitly ...
7,274,846
7,275,814
Template specialization with nested unspecialized type
I'm having trouble working out the syntax for a nested partial template specialization. I think that's the right way of putting it anyway. What I want is an as() function which returns a casted value. In most cases static_cast will work fine so I have a generic version which does that, but in some cases I want to get s...
Since a function can't be partially specialize, we partially specialize a functionoid-thingy instead, and make the function simply use the specialized class. //generic version template<typename ClassType, typename CastType> class As { public: CastType operator()(const ClassType& b) {return static_cast<CastType>(b)...
7,274,956
7,275,020
Preprocessor directive to create file names
I have to open files one by one for reading in C/C++. The name of the files are in0, in1, in2, in3..... I tried to use preprocessor directive to create file names. i want something like. for(int i=0;i<n;i++) { string inp_file="/path/"+"in"+APPEND(i); //to generate /path/in1 etc open(inp_file); } where APPEND ...
Addendum to Vlad's answer -- if for some reason you're not able/willing to use Boost, you can accomplish what you want using standard C++ with the stringstream class: #include <sstream> void Foo() { for (int i = 0; i < n; ++i) { std::stringstream converter; converter << "/path/in" << i; ope...
7,275,109
7,275,284
Passing data from Django to C++ application and back
We are creating a trading application, where the backend is totally in C++ (using QuickFix engine). We would like to build a web application in Django on top of this backend, where the user can place his orders. Both the Django (python) and the C++ application will be running in their own processes and address space. W...
Well you have to use some IPC method. One that you don't mention here is having the C++ process listen to a socket. That would add in flexibility (with slight speed cost) that the processes don't even need to be on the same machine. I've been doing a sort of similar thing, coming from C++ but wanting to write UX in py...
7,275,331
7,276,076
how to write makefile to take care of changes in the header file
Actually i have a library 'cryptopp' and what i want is that when i make any change to a file and issue the make command it should take care of the changes made in any file in the source directory. well, the GNUMakefile of cryptoopp takes care of the changes 'if' made in the '.cpp' files but not for the changes made in...
If you are building with g++ you can let g++ generate dependancy makefiles. You can include these in your main makefile. Use the -M and -M* arguments to use this feature. (see http://gcc.gnu.org/onlinedocs/gcc-4.6.1/gcc/Preprocessor-Options.html#Preprocessor-Options)
7,275,668
7,275,690
What is the default calling convention of static member functions in visual studio?
What is the default calling convention of static member functions for Microsoft's compiler? Can I change it by placing WINAPI in front of it?
The default calling convention is cdecl. Yes, you can override this and specify the calling convention. In this regard there is nothing special about static member functions.
7,275,867
7,277,213
Background compile in VS2010 and C/C++
I use Visual Studio 2010 and Intel icc compiler for C development. I use C99 but editor is still showing C99 constructs as errors (compiling is fine). How to get rid of it? Second question, is it possible to use Eclipse (CDT) with Intel compiler on Windows?
As mentioned in the responses to your post, the problem you're seeing is with your intellisense only. You can turn off intellisense error reporting in VS2010: Tools > Options > Text Editor > C/C++ > Advanced. Under IntelliSense, choose "Disable Error Reporting" and set it to "True".
7,276,164
7,276,399
how to access a text file while debugging with eclipse CDT
I am writing this code to access a file in eclipse CDT ifstream inFile; ofstream outFile; string next; inFile.open("input.txt"); if (inFile.fail()) { cout << "\nCould not open input.txt"; exit(1); } the problem is when I try to debug my app or run my app from inside eclipse it cannot find the input.txt file....
It could be an issue with relative paths. Is input.txt in the root directory of your project? Eclipse makes the top-level directory of the project the working directory. If you replace "input.txt" in your code with the fully qualified file name, that should also work.
7,276,345
7,276,406
"glibc free(): invalid next size(fast)" on vector.push_back?
When I run my program it will occasionally crash and give me this error: "glibc detected /pathtoexecutable: free(): invalid next size (fast)" The backtrace leads to a member function that just calls a vector's push_back function - void Path::add(Position p) {path.push_back(p);} I have tried googling the error and the...
You're probably doing an invalid write somewhere and trashing the control information kept by glibc for bookkeeping. Thus, when it tries to free things it detects abnormal conditions (unreasonable sizes to free). What's worst about this kind of thing is that the problem doesn't manifest itself at the point where you ma...
7,276,389
7,276,429
Confused over DLL entry points (entry point not found exception)
I'm trying to learn how to use DLL's in C#. I have a very simple DLL just to test the basics. // MainForm.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Runtime.In...
use extern "C" __declspec(dllexport) int __stdcall Add(int a, int b) { ... } and [DllImport("TestDLL.dll", CallingConvention = CallingConvention.Stdcall)] public static extern int Add(int a, int b); extern "C" will prevent name mangling with params and return type such as ?Add@@YGHHH@Z. __stdcall will prepend an _ ...
7,276,398
7,279,394
invalid memory when using classes from a dll
this is the first time I've tried to export a class from a dll. what I've done is: - crated an interface (only pure virtual methods) - implemented this interface in the dll with a class that wont be exported - the class has a release method that calls delete on its this pointer - created a Factory class wi...
Thanks for your answers, and I'm sorry I started this for nothing! The problem was very simple but hidden behind the interfaces , factory , and some other stuff. I was returning a pointer to an object that was declared as static because it has to be a singleton. Then I was trying to release this object. BANG heap corru...
7,276,805
7,276,875
referencing problem in void * pointer?
This code: int p = 10; void *q; *q = 10; Does not compile: '=' : cannot convert from 'int' to 'void *' However, this code compiles fine: int p = 10; void *q; q = &p; What is the reason behind it?
A void * points to data of an unknown type (if it is initialized, which yours is not). You can only assign to variables of a known type, or via pointers of a known type. int p = 10; void *q = &p; *(int *)q = 20; if (p != 20) ...something has gone horribly wrong... This converts the void * into an int * and then ...
7,276,826
7,276,879
Format number with commas in C++
I want to write a method that will take an integer and return a std::string of that integer formatted with commas. Example declaration: std::string FormatWithCommas(long value); Example usage: std::string result1 = FormatWithCommas(7800); std::string result2 = FormatWithCommas(5100100); std::string result3 = FormatWit...
Use std::locale with std::stringstream #include <iomanip> #include <locale> template<class T> std::string FormatWithCommas(T value) { std::stringstream ss; ss.imbue(std::locale("")); ss << std::fixed << value; return ss.str(); } Disclaimer: Portability might be an issue and you should probably look at...
7,276,961
7,327,666
Eclipse CDT + ICC compiler
Is it possible to use Intel C++ compiler (icc) in Eclipse (CDT) on Windows? How?
For what I could read in this forum "no such integration is currently supplied in the Windows environment for the Intel C++ compiler". Alternatively, there is MinGW, a free tool for developing Microsoft applications and it gives access to the functionality of the Microsoft C runtime. See here how to set it up with Ecli...
7,277,030
7,277,049
why does fclose not set file pointer to NULL?
I was writing a RAII wrapper for FILE *. I noticed that when the FILE * is deleted after close in the destructor it leads to undefined behavior (seg. fault or errors somewhere else). I assumed that the fclose will set the FILE * to NULL, which it did not. class smartFP { smartFP (const std::string& name) : fp (f...
Of course delete fp is causing a crash. It wasn't allocated with new. Only call delete on something you got with new or with something else that the documentation told you to use it on. The documentation for fopen never tells you to use delete. All cleanup for files is performed by fclose; there's nothing additional yo...
7,277,086
7,277,371
Incorrect watch values in Visual Studio 2010 Professional
I'm having a really bizarre problem wherein the watch window values for some variables don't seem to match their "real world" values. The debugger just appears to be off in space. Here's the tiniest code snippet that shows it: printf("%d", pNodes[nNode].nColumn); // watch shows "4" printf("%d", nColumn); // watch shows...
So I think I've cracked the case: The culprit was Struct Member Alignment. I had a bunch of projects mixed together and some of them had varying values for this field inside the projects. I removed the settings on all of them to just let VS pick the defaults and the problem has disappeared. The applicable value was bet...
7,277,366
7,292,674
Why does EnumWindows return more windows than I expected?
In VC++, I use EnumWindows(...), GetWindow(...), and GetWindowLong(), to get the list of windows and check whether the window is top window (no other window as owner), and whether the window is visible (WS_VISIBLE). However, although my desktop is showing only 5 windows, this EnumWindows is giving me 50 windows, how fu...
The way to list out only windows in taskbar (or similarly in Alt-Tab box) is described by Raymond in this article on MSDN blog: Which windows appear in the Alt+Tab list? And this is the super function to check whether a window is shown in alt-tab: BOOL IsAltTabWindow(HWND hwnd) { TITLEBARINFO ti; HWND hwndTry, ...
7,277,387
7,277,827
Using Perlin noise to create lightning?
Actually I am having several questions related to the subject given in the topic title. I am already using Perlin functions to create lightning in my application, but I am not totally happy about my implementation. The following questions are based on the initial and the improved Perlin noise implementations. To simpli...
That depends on how you implement it and sample from it. Using multiple octaves helps counter integers quite a bit. The octaves and additional interpolation/sampling done for each provides much of the noise in perlin noise. In theory, you should not need to use different integer positions; you should be able to sampl...
7,277,394
7,277,489
prefix operator overloading
I'm overloading the ++ prefix operator using a member function. Here's the prototype: Test &operator++(); But my doubt comes when I use it for my object like below: Test t; ++t; As far I have learned that for any operator overloaded by a member function there should be a object of that same class on left side of tha...
As far I have learned that for any operator overloaded by a member function there should be a object of that same class on left side of that operator. That would hold for any binary operator. Pre- and post-incrementations, as well as the dereference operator (*obj) are unary operators. They have a single argument (ei...
7,277,477
7,277,513
How is dynamically allocated space freed when a program is interrupted using Ctrl-C?
Given the following code: #include <stdio.h> int main() { int *p; p = (int *)malloc(10 * sizeof(int)); while(1); return 0; } When the above code is compiled and run, and is interrupted while in execution by pressing Ctrl+C, how is the memory allocated to p freed? What is the role of the Operating Sys...
When a process terminates, the operating system reclaims all the memory that the process was using. The reason why people make a big deal out of memory leaks even when the OS reclaims the memory your app was using when it terminates is that usually non-trivial applications will run for a long time slowly gobbling up al...
7,277,490
7,277,697
C++ class that can hold one of a set of classes that all inherit from a common class
What are the ways in C++ to handle a class that has ownership of an instance of another class, where that instance could potentially be of a number of classes all of which inherit from a common class? Example: class Item { //the common ancestor, which is never used directly public: int size; } class ItemWidget: publ...
A correct solution looks like: class Container { public: /* ctor, accessors */ private: std::unique_ptr<Item> item; }; If you have an old compiler, you can use std::auto_ptr instead. The smart pointer ensures strict ownership of the item by the container. (You could as well make it a plain pointer and roll up ...
7,277,497
7,277,552
Reading from text files C++
I have a text file containing three columns of numbers; one column each for the x,y,z coordinates of a bunch of points. All numbers are between 0 and 1. I have created the following structure: typedef struct { double xcd, ycd, zcd; } point; I want to create a size-N array of structures of type point. Then I want...
Simply do it like has been shown five million billion kajillion times before, using ifstream, vector and various other accouterments. ifstream infile("myfile.txt"); // check if file opened successfully if (!infile) { cerr << "failure, can't open file" << endl; cin.get(); return EXIT_FAILURE; } // the cont...
7,277,637
7,277,756
New (std::nothrow) vs. New within a try/catch block
I did some research after learning new, unlike malloc() which I am used to, does not return NULL for failed allocations, and found there are two distinct ways of checking whether new had succeeded or not. Those two ways are: try { ptr = new int[1024]; } catch(std::bad_alloc& exc) { assert(); }; and ptr = new ...
Consider what you are doing. You're allocating memory. And if for some reason memory allocation cannot work, you assert. Which is more or less exactly what will happen if you just let the std::bad_alloc propagate back to main. In a release build, where assert is a no-op, your program will crash when it tries to access ...
7,277,846
7,277,855
c++ code: class or structure: difficult to understand
Possible Duplicate: What are the differences between struct and class in C++ I am looking at somebody header file for a structure, but it looks like functions are a part of this structure... so then this is a class but how to abstantiate? or use? struct Recording { FLAG mode; unsigned short intervals; ...
In C++ class and structare identical, except that the default access specifier for the former is private, while for the latter it is public. class Base { /* .. */ }; class Foo : Base { int i; }; struct Bar : Base { int i; }; In the above code, Foo inherits privately from Base while Bar does so publicly. Similarl...
7,278,347
7,278,359
C++ - pointer array to Vector?
double * values; // instead of this, std::vector<double> values; // I want this. An API I'm using provides a result as double* pointer. I want to wrap this with the std::vector<double> type.
You can't wrap an array in a vector in place and expect the vector to operate on that array. The best you can do is give the vector the double* and the number of values, which will have the vector make a copy of every element and put it in itself: int arrlen = 0; // pretending my_api takes arrlen by reference and sets...
7,278,555
7,434,183
DNS customization development on Windows?
I want to implement my own policy for DNS look up on Windows platform (Server 2008), in more details, the customization I mean is when there is a request to look up IP for a host name comes for DNS server, my own customization logics (inside DNS) will be called (e.g. find a low working load machine) and return the IP a...
Don't know if it will exactly solve your problem, but have you investigated using Windows NLB? http://en.wikipedia.org/wiki/Network_Load_Balancing_Services It possibly supports custom load balancing logic
7,278,894
7,311,793
Monotouch: Adding .a resource , gcc error
Using this project: https://github.com/dalexsoto/Monotouch-AdMob-Bindings I am adding the AdMob .a to my MonoTouch app. I'm not sure that these compile errors mean, though I guess the bindings in the MonoTouch dll are not correct?: Compile Flags: -v -v -v -gcc_flags "-framework AudioToolbox -L${ProjectDir} -lGoogleA...
Adding --cxx if often enough but, since it does not work, you might want to try being more specific and also add -lgcc_s - this time inside the gcc_flags, so using something like: -v -v -v -cxx -gcc_flags="-lgcc_s ..." in your 'extra mtouch arguments'.
7,278,966
7,278,975
inner_product of map
can inner_product not be applied to a map. I have the following code: std::map<class A, class B> s; std::map<class A, class B>::const_iterator vit=s.begin(); long double x = std::inner_product(vit->first,vit->second,vit->first,0.0); but I get a no-matching function to inner_product error.
It certainly can be applied to maps, given creatively chosen functors, but inner_product expects iterators, while vit->first is a const A and vit->second is a B. For example, std::map<int, double> m = {{1, 0.1}, {2, 0.2}}; typedef std::map<int, double>::value_type val_t; double x = std::inner_product(m.begin(), m.end()...
7,279,100
7,279,148
C++ ifstream on XCode: Where is the default directory?
Ok, so this is the first time I've coded C++ in Xcode (I'm used to ObjC)and I've now started a programming course at my college. I'm trying to open a file (either hard coded or from user input in the console) and no matter what I try, it says the file won't open (through error checking) I'm assuming it's because the te...
The default directory should be relative the application's working directory, which is usually the same place the application is located (debuggers can mess with that, sometimes). For simple testing, just specify an absolute path in the command line (or code). To get the current directory (to see), the getcwd() C funct...
7,279,193
7,291,271
Windows.h macros not defined
I'm making a simple GUI library, and I've gotten to the first test. The weird thing is, none of the windows macros seem to be defined. I'm getting errors like "'NULL' was not declared in scope" and "'HANDLE' was not declared in scope." I'm thinking it might be the way I organized the code because the stuff in the entry...
This should be a comment on IronMensan's answer because it's entirely correct but I can't fit in there... The windows's API has functions that take parameters of type "HANDLE" in the global namespace, in other words "::HANDLE". The windows libraries are already compiled to do this and the compiled code exists in such ...
7,279,393
7,279,406
Quickest way to change endianness
What is the quickest way to reverse the endianness of a 16 bit and 32 bit integer. I usually do something like (this coding was done in Visual Studio in C++): union bytes4 { __int32 value; char ch[4]; }; union bytes2 { __int16 value; char ch[2]; }; __int16 changeEndianness16(__int16 val) { bytes2 ...
Why aren't you using the built-in swab function, which is likely optimized better than your code? Beyond that, the usual bit-shift operations should be fast to begin with, and are so widely used they may be recognized by the optimizer and replaced by even better code. Because other answers have serious bugs, I'll post...
7,279,400
7,280,147
Is object created without new operator deleted in a specific case in C++
If we have the following code snippet: MyObject my_object = MyObject(0); my_object = MyObject(1); What happens to MyObject(0)? Is it deleted? Looking at what I have read about it it should only be deleted when we leave the scope of creation, so the anwser is probably no. If this is the case is there any way to explici...
The term delete has a special meaning in C++, so the use of deleted is unfortunate. MyObject my_object = MyObject(0); This line declares that an object of type MyObject created with automatic storage duration (ie, on the stack). This object will be destructed (ie, its destructor will be executed) when the scope ends. ...
7,279,416
7,279,535
Checking whether a non-hardwired member function exists with SFINAE
I want to create proxies for member functions and operators. They must have the same return type and parameters, and must be good for several classes, which are given as template parameters. Even if the class does not have the particular member function or operator, I want it to compile instead of failing with an error...
I suspect that template<typename... Args> decltype( std::declval<T&>().f(std::declval<Args>()...) ) f(Args&&... args) { return x.f(std::forward<Args>(args)...); } should trigger SFINAE and discard any instantiation of f for which the return type is ill-formed (e.g. ambiguous or non-existant overload) instead of a ...
7,279,475
7,279,530
call of overloaded ‘max(char&, char&)’ is ambiguous
#include <iostream> using namespace std; int max (int a, int b) { return a<b?b:a; } template <typename T> T max (T a, T b) { return a<b?b:a; } template <typename T> T max (T a, T b, T c) { return max (max(a,b), c); } int main() { // The call with two chars work, flawlessly. :: max ('c',...
Thing is, there is already a max in std, and you are saying using namespace std;: template <class T> const T& max ( const T& a, const T& b ); So your max ('c', 'b', 'a') is called fine; the problem is inside it. template <typename T> T max (T a, T b, T c) { return max (max(a,b), c); /* Doesn't know which max to p...
7,279,669
7,279,809
Standard Position of a Quaternion?
In 2D, the standard position of a vector is down the positive X axis. Is there an equivalent position for quaternions?
There is no "standard position of a vector." In 2D or 3D. There is of course a general mathematical convention that the X,Y direction of an angle is (cos(angle), sin(angle)). Which means that if the angle is 0, then the vector points down the positive X axis. But that's far from a "standard position of a vector." While...
7,279,825
7,279,840
Segmentation fault and run time error
Possible Duplicate: Modifying value of char pointer in c produces segfault This is a piece of code ... void main() { char *p="Hello"; *p= 'h'; // Segmentation fault . } I understand the fact that there is a segmentation fault and it gives me a run time error also .But I wonder , why is ...
String literals are really of type char const*. However, for compatibility with older C code that's not const-correct, C++ allows them to be assigned to a char*. That does not mean you are really allowed to modify them.
7,280,021
7,280,125
Integer |= Char; operation ignoring high order byte in Integer
Just a quick and specific question, this has stumped me for half an hour almost. char * bytes = {0x01, 0xD8}; int value = 0; value = bytes[0]; // result is 1 (0x0001) value <<= 8; // result is 256 (0x0100) value |= bytes[1]; // result is -40? (0xFFD8) How is this even happening? The last operation is the one o...
In your case the type char is equivalent to signed char, which means that when you save the value 0xD8 in a char, it will come out as a negative number. The usual arithmetic conversions that happen during the |= operation are value-preserving, so the negative number is preserved. To solve the problem, you can either ma...
7,280,108
7,280,172
add two shared libraries in php extension. WHO?
I have a sharedlib.cc and a sharedlib.h code that contains classes and methods. I wrap this up and created a shared library called MySharedLibrary.so. I would like to work with my .so library inside a php code. So I've created a config.m4 file , a php_code.cc file and a php_code.h file in order to make the extension f...
I believe the PHP_ADD_LIBRARY() macro in config.m4 will achieve this. You can find some examples here: http://devzone.zend.com/article/4486 edit: you may need PHP_ADD_LIBRARY_WITH_PATH() if your shared lib isn't somewhere that the linker will find it. edit 2: looks like this was covered before; the answer provides good...
7,280,184
7,280,536
Fast uniformly distributed random points on the surface of a unit hemisphere
I am trying to generate uniform random points on the surface of a unit sphere for a Monte Carlo ray tracing program. When I say uniform I mean the points are uniformly distributed with respect to surface area. My current methodology is to calculate uniform random points on a hemisphere pointing in the positive z axis a...
The simplest way to generate a uniform distribution on the unit sphere (whatever its dimension is) is to draw independent normal distributions and normalize the resulting vector. Indeed, for example in dimension 3, e^(-x^2/2) e^(-y^2/2) e^(-z^2/2) = e^(-(x^2 + y^2 + z^2)/2) so the joint distribution is invariant by rot...
7,280,571
7,280,684
precompiled header files usage for library builders
According to this answer boost and STL headers belong into the precompiled header file (stdafx.h in the MSVC world). So I changed the headers of my dynamic link library project and moved all STL/Boost headers into the stdafx.h of my project. Before #include <boost/smart_ptr.hpp> namespace XXX { class CLASS_DECL_BK C...
You should get nearly the same speed increase when you leave the header-includes in place in the library headers and just additionally put them into stdafx.h. Alternatively, you could add an additional define (a bulk external include guard) // stdafx.h #define MY_LIB_STD_HEADERS_ALREADY_INCLUDED // library_file.h #ifn...
7,280,673
7,289,280
What are lookup rules when calling function from lambda?
The following example demonstrates the problem I encountered in VC++ 2010: class Foo { template<class T> static T foo(T t) { return t; } public: void test() { auto lambda = []() { return foo(1); }; // call to Foo::foo<int> lambda(); } }; VC++ produces: error C3861: 'foo': identifie...
Microsoft has been seeing this problem reported in a number of cases. See: Scope Resolution with lambdas interferes with namespace and type resolution Template resolution in lambdas As you've found out, explicit resolution allows it to find the name. There is an additional warning about this which is also a compiler ...
7,280,680
7,281,927
Best place to learn C++ for a C# programmer
I have been developing using c# now since the first release of .NET. I have never really spent time on C or C++ and thought it would be a good idea to get a little more awareness. Does anyone have any recommendations for sites that would provide a good learning/tutorial for someone that has c# experience to venture int...
Warning: C++ is not C and the following is related only with C++. If you are already a c# developer I think you should work in three different directions: 1) copy semantic, memory management and const keyword, these are the main differences between c# and c++. Make yourself familiar with copy constructor, destructor a...
7,280,706
7,280,790
Problem loading object data from text file
Why doesn't this code want to load all the values from a text file? It only loads the first object's items correctly but after that it starts going weird. Here is the code: #include <iostream> #include <fstream> #include <cstdlib> using namespace std; class Location { public: Location() { locName = "No...
Your first problem is that this line doesn't extract the newline character: ins >> inLoc.locID; This means that the getline in for the second Location is extracting the rest of the line after 1 - i.e. an empty string - for the name. This means that you are quickly getting out of sync with the lines that you want to re...
7,280,791
7,280,866
Boost CRC problem: different results with the same parameters
I am using CRC for the first time (boost::crc_32_type), and I noticed that calling the process_bytes() method twice with the same parameters I get different results. Is it normal? #include <boost/crc.hpp> #include <ios> // for std::ios_base, etc. #include <iostream> #include <string> using namespace std; ...
According to the manual, checksum() returns "the CRC checksum of the data passed in so far". So, the second checksum is the checksum of the concatenation of data1 with itself and thus naturally different from the checksum of data1.
7,280,986
7,286,271
wxWidgets Crash on closing application
This is probably a stupid question as this crash is probably related to some invalid pointer or already destroyed object, but looking at the code on all ways I couldn't find out where is the problem. When I close the software I got a SIGSEVerror with the following message: #0 00000000 0x003f01c5 in ??() (??:??) #1 004D...
In general: Do a debug build Run the application You may well get extra windows popping up with extra information about dodgy code. If so, track down the problems that the debug build has noticed and fix them Does this fix the problem? If not, run the app under the debugger. When the crash occurs, look at the call s...
7,280,992
7,281,078
How to find where a library call returns?
I am analyzing an external FORTRAN library which is quite huge. Anyways, the whole point of the library is to fit parameters values for a function I supply. The entry point is one method call with godzillion parameters. The problem is, sometimes the call returns quite quickly, and the parameters values it spits out may...
Run gdb, type help next or help nexti and you can see the description of the next command which basically steps forward in your program. What you can do is, set a breakpoint in the beginning of the function, and then from there, run the program step by step (using next) and see where it goes out of the function. If the...
7,281,072
7,281,109
Accessing public members of base class fails
might be a bit of a coward-ish question: I've got two classes, and declared all variables public. Why can't I access the variables from derived class?? g++ tells me: vec3d.h:76:3: error: ‘val’ was not declared in this scope template<typename TYPE> class vec{ public: TYPE *val; int dimension; public: ...
This is purely a lookup issue and nothing to do with access control. Because vec3d is a template and its base class depends on the template parameter, the members of the base class are not automatically visible in the derived class in expression that are non-dependent. The simplest fix is to use a dependent expression ...
7,281,237
7,434,258
Low performance of Incremental linking in Visual Studio C++
I have a large binary which is built of many static libs and standalone cpp files. It is configured to use incremental linking, all optimizations are disabled by /Od - it is debug build. I noticed that if I change any standalone cpp file then incremental linking runs fast - 1 min. But if I change any cpp in any static...
Set "Use Library Dependency Inputs" in the Linker General property page for your project. That will link the individual .obj files from the dependency .lib instead of the .lib, which may have some different side effects.
7,281,325
7,328,007
In JNI Cannot using GetIntField get the value in the java class Android
I try to get the value in the Native class field mInt. This class is created by SimpleJNI. In this sample I set the mInt value to 9. JNI function add try to get the mInt value by using GetIntField. It should return 9 in add function. But it seems GetIntfield cannot find the field in this jobject. How do I get the mInt...
I already found the root cause of why JNI add function cannot get value from GetIntField. Because the native function declare cannot be static. It should be public native int add(int a, int b);
7,281,362
7,281,424
const_string lib issue
I'm trying const_string lib that looks not bad, but it crashes at runtime with access violation(atomic_count, operator++()). The test code: #include <boost/const_string/const_string.hpp> #include <boost/const_string/concatenation.hpp> typedef boost::const_string<wchar_t> wcstring; class Test { private: const wcst...
Your instance of Test has initialized its reference data members as references to temporaries created from the literals L"". Oops. The temporaries no longer exist by the time you try to use one of them in the copy constructor of wcstring at the line that crashes, so your references don't refer to anything. I think boos...
7,281,441
7,281,477
Elegantly call C++ from C
We develop some project in plain C (C99). But, we have one library as source codes (math library) in C++. We need this library so I would like to ask, what is the most elegant way to integrate this source codes? Ratio between sizes of C and C++ is 20:1 so moving to C++ is not the option. Should we use static library? D...
EDIT: Based on discussion in the comment, I should point out that separating things into a C-compatible struct duck and a derived class Duck is probably unnecessary. You can probably safely shovel the implementation into struct duck and eliminate class Duck, thus obviating real(…). But I don't know C++ well enough (in ...
7,282,079
7,282,159
Address Windowing Extension
I have an 32bit application with very large memory requirements. I noticed that there is something called Address Windowing Extension. However I haven't found much information in regards to how to use it and also what disadvantages and problems one might run into while using this?
It shouldn't work on versions of Windows at 64bits (read here http://msdn.microsoft.com/en-us/library/aa366778.aspx Intel and AMD's specification of PAE does support the x86-64 architecture but the software layer of Microsoft's PAE (the API), called AWE, is not supported on 64 bit editions of Windows, so Windows Vista...
7,282,127
7,282,303
EOF before EOF in Visual Studio
I had this snippet in a program (in Visual Studio 2005): if(_eof(fp->_file)) { break; } It broke the enclosing loop when eof was reached. But the program was not able to parse the last few thousand chars in file. So, in order to find out what was happening, I did this: if(_eof(fp->_file)) { cout<<ftell(fp)<<en...
You can't reliably use _eof() on a file descriptor obtained from a FILE*, because FILE* streams are buffered. It means that fp has sucked fp->_file dry and stores the remaining byte in its internal buffer. Eventually fp->_file is at eof position, while fp still has bytes for you to read. Use feof() after a read operati...
7,282,243
7,282,331
GCC - Linking bass.lib on Ubuntu
I wrote an application on Windows using CPP and BASS, and now I have to get it running on Linux (UBUNTU). I am using gcc version 4.5.2. I have bass.lib in my directory from which I try to compile prog.cpp using the following command arguments: gcc prog.cpp -L. -lbass.lib But I get the following error: /usr/bin/ld: ca...
bass.lib sounds like the windows library. You cannot use libraries generated on windows, (likely generated with the MSVC compiler), on linux. The linux version of the library seems to be named libbass.so , in which case you'd use -lbass as the linker argument , and possibly other compiler/linker flags as well depending...
7,282,350
7,282,570
How to unit test deliberate compilation errors of template code
Please note that this is NOT a duplicate of How write a unit test for verifying compiling error? as I'm not concerned about testing the correctness of external libraries or the compiler itself. It is typical in C++, particularly when dealing with templates, to employ techniques that prevent some particular piece of cod...
Do it in the similar way compiler tests are written. You will have a bit of testing code in some scripting language (shell, perl, tcl etc.) that will run compiler on given snippets of code and check whether the right ones compiled and the right ones did not. gcc uses DejaGnu, which is built on top of expect, which is ...
7,282,568
7,282,886
check if a pointer has some string c++
I am not good with c++ and I cannot find this anywhere, please apologize me if it is a bad question. I have a pointer and I want to know if some names store in this pointer begins with some specific string. As in python something like (maybe it is a bad example): if 'Pre' in pointer_name: This is what I have: double...
The equivalent of Python 'Pre' in string_name is: string_name.find("Pre") != std::string::npos // if using string std::strstr(pointer_name, "Pre") // if using char* The equivalent of Python string_name.startswith('Pre') ("begins with some specific string") is: string_name.size() >= 3 && std::equal(string_name.begin()...
7,282,645
7,283,002
How to build boost iostreams with gzip and bzip2 support on Windows
How do I build boost's iostreams library with gzip and bzip2 support?
I am no expert, but this worked for me. Option 1 (straight from source) Download source files for zlib and for bzip2. Extract the downloads to directories, move directories to somewhere you like. I had to avoid C:\Program Files (x86)\ as I couldn't get it to work with spaces in the directory name, so I created C:\Sys\...
7,282,820
7,283,007
Function call to return string inside ListView_SetItemText macro
A question on ListView_SetItemText macro for setting text of items in ListView Windows control. Why does the following code works (in a sense that the text is displayed in the ListView) std::string strNumber = NumberToString(number); ListView_SetItemText( hListView, iItemIndex, iSubitemIndex, (LPSTR)strNumber.c_str() )...
Here's the macro definition (in commctrl.h): #define ListView_SetItemText(w,i,iS,s) \ { \ LV_ITEM _lvi;\ _lvi.iSubItem=iS;\ _lvi.pszText=s;\ SNDMSG((w),LVM_SETITEMTEXT,i,(LPARAM)(LV_ITEM*)&_lvi);\ } This expands to: ... _lvi.pszText=(LPSTR)NumberToString(number).c_str(); SNDMSG((hListView),...
7,282,853
17,470,650
What does #pragma hdrstop without parameter do when used in multiple files?
What is the practical value ("what does it do") of putting #pragma hdrstop (no filename parameter) in a couple of source (cpp) files? Note that the MSDN docs are (once again) as clear as mud to me. Edit/Note: I'm asking this, because this answer and the article it links to seem to recommend that. But I do not understan...
The answer to the original question is that the purpose of having #pragma hdrstop in a file with neither /Yc or /Yu set is that it's ignored and so you can set up a build configuration which builds without precompiled headers and other build configurations that build WITH precompiled headers and you don't need to chang...
7,282,876
7,283,092
boost::ref and boost::asio completion handlers, pass-by-reference
m_io_service.post(boost::ref(i)); I have this call in a section of code, the underlying type i is definetly a callable (because removing the boost::ref leads to pass by value, which works fine), however clang tells me that : /opt/dev_64_swat/proto-rpc2/dependencies/boost/include/boost/asio/handler_invoke_hook.hpp:64:3...
boost::ref doesn't provide an overload of operator(). Hence, the return cannot be used directly as a callback. There are 2 options: C++03: Use boost::bind to wrap the ref, and it will do what you want m_io_service.post(boost::bind<ReturnType>(boost::ref(i))) Note that you have to specify the return type unless the...
7,282,882
7,282,915
Why operator[] not allowed for maps but are allowed for int arrays?
I have a class with the following private members: private: int *vals_; size_type *cidx_; std::map< size_type, std::pair<size_t, unsigned int> > ridx_; Now I am trying to access these variables in operator<< overload: (Note that m is const) std::ostream& operator<<(std::ostream &os, const SMatrix &m) { os ...
std::map::operator[] inserts an element if it doesn't exist, so it cannot be used with const objects. Arrays are not class types in C++, for them a[idx] is equivalent to *(a + idx) and never mutates the array by itself.
7,282,971
7,283,108
Syntax of C++ Template Template Parameters
I'm having difficulty understanding the syntax of C++ Template Template parameters. I understand why they are useful, as per the excellent description here, I just find their syntax hard to get to understand. Two examples taken from the above website (there are others): template <typename T, template <typename> class C...
There's nothing so arcane about it. Just take out your template template parameters from the original template: template <typename> class Cont Any class template with a single type argument fits, such as template <typename T> class A { public: A(T t) : t_(t) {} T get() { return t_; } private: T t_; }; And you w...
7,283,077
7,283,211
Counting columns of a space separated file
My question concerns the use of std::count (or another appropriate function) to count the columns of a space separated file. I currently use something like this: std::ifstream inFile("file"); int lines = std::count(std::istreambuf_iterator<char>(inFile), std::istreambuf_iterator<char>(), '\n'); to c...
No, you'll count spaces, not columns. You need to tokenize your line, e.g. by boost::tokenizer
7,283,102
7,283,765
QFileSystemModel - Incremental update/pre-emptive update
From the Qt documentation: QFileSystemModel will not fetch any files or directories until setRootPath() is called. This will prevent any unnecessary querying on the file system until that point such as listing the drives on Windows. Unlike QDirModel(obsolete), QFileSystemModel uses a separate thread to populate itself...
QFileSystemModel emits directoryLoaded(const QString &path) signal, when gather thread finished loading directory.
7,283,128
7,283,204
edge_index zero for all edges?
Defining my boost::graph like the following, I get edge indices zero for all edges. Why? What am I doing wrong? #include <iostream> #include <boost/graph/adjacency_list.hpp> int main() { typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property, boost::property<boost::edge_index_...
An adjacency_list doesn't have an edge index associated with it, only a vertex index. Which is quite logical once you think about how the graph is stored. To have an edge index, you need to manually add it to the graph description, and then manually handle it.
7,283,214
7,283,384
In which cases does compiler create a new temporary local value while comparing two types?
template <typename T> inline T const& max (T const& a, T const& b) { return a < b ? b : a; } inline char const* max (char const* a, char const* b) { return std::strcmp(a,b) < 0 ? b : a; } template <typename T> inline T const& max (T const& a, T const& b, T const& c) { return max (max(a,b), c); } i...
Let's do it slowly: ::max(s1, s2, s3); invokes T const& max (T const& a, T const& b, T const& c) with T being char const*. Within this method we have: max(a,b) which invokes char const* max (char const* a, char const* b) max(max(a,b), c); thus invokes char const* max (char const* a, char const* b) as well And thus t...
7,283,412
7,538,015
Where can I find script that convert VC++ inline assembler to intrinsics?
I am porting inline assembler that use SSE commands to intrinsics. It takes much work to find appropriate intrinsic for assembler instruction. Somewhere on the Internet I saw a Python script that simplifies the job, but cannot find it now.
I created my own script to convert inline assembler to intrinsics. He does a lot of rough work. https://github.com/KindDragon/Asm2Intrinsics
7,283,489
7,283,572
How to debug kernel written in c++?
I am developing my kernel in C++. So can any one please explain me step by step How to debug a kernel? I am using Linux OS and GCC and NASM for building my kernel. Ans for testing kernel i am using genisoimage and virtualbox 4.x Help Me. Thank you.
I would recommend bochs as an emulator, it comes with some debugging capabilities.
7,283,670
7,292,122
Decode funny ISO encoding of e-mail message
I have an e-mail body (char[] buffer, retrieved via POP3), it apparently uses some markup for ISO code pages, e.g. a subject like Daß ißt ään schlümmer Test is encoded as =?iso-8859-1?Q?Da=DF_i=DFt_=E4=E4n_schl=FCmmer_TDest Is there anything pre-made I can use to turn that into a (readable) CStringW? (Environment: Wi...
This format is called an encoded-word and is defined by RFC 2047. The form is =?<charset>?<Q or B>?<encoded data>?=, where the data is encoded as either base-64 (B) or something that looks like quoted-printable (Q) but isn't quite (because _ means a space). Some example C++ decoders will get you to a byte string. You'd...
7,283,735
7,315,071
How to get pixel bit count using PixelFormat in libav
Is there any way to get pixel's bit count from codecContext.pix_fmt of type PixelFormat? I do it manually using switch: switch (OUT_IMAGE_FORMAT) { case PIX_FMT_RGB24: pVideoInfo->bmiHeader.biBitCount = 24; do_something(); break; //etc } but this requires manual updates every time liba...
Try using #include "libavutil/pixdesc.h" pVideoInfo->bmiHeader.biBitCount = av_get_bits_per_pixel(&av_pix_fmt_descriptors[OUT_IMAGE_FORMAT]); http://ffmpeg.org/doxygen/trunk/pixfmt_8h.html
7,283,805
7,284,929
Inertia must be positive definite
I'm writing a game in C++ using Open Dynamics Engine. When I run it, i get these errors: ODE Message 2: inertia must be positive definite in dMassCheck() File ../../../../../ode/src/mass.cpp Line 53 ODE Message 2: inertia must be positive definite in dMassCheck() File ../../../../../ode/src/mass.cpp Line 53 ODE INTER...
The massPtr structure contains an inertia tensor. This tensor (just a matrix, in this context) has to be positive definite. That's all we can say until you tell us where you got your massPtr from.
7,283,820
7,283,894
DLLImport with char * arguments. Only one character being passed
I have written a C++ DLL with the following function exported extern "C" BOOL WINAPI SetUserPassword(const char* u, const char* p) When calling this from C# I am using the following code [DllImport("mydll.dll")] private static extern int SetUserPassword(String user, String password); Now when SetUserPassword is calle...
The only thing that makes sense is that your C# code is actually: [DllImport("mydll.dll", CharSet = Unicode)] private static extern int SetUserPassword(String user, String password); When you do this you pass a wide character based string to your C++ code and since it expects single byte characters it interprets the 0...
7,283,993
7,284,800
OLEDragDrop Event working with compiled exe but not when debugging
We're using OLEDragDrop Event in one of our bigger products and have stumbled upon a strange issue. On my machine, if I build the application and run the exe-file, the application sees a drag-drop-event and I can drag a file from the desktop to the program and it saves it and does what it should do. However, when I go ...
You won't be able to drag onto the application if Visual Studio is running as an administrator.
7,284,344
7,284,726
std::string operator+() memory leak?
I'm quite worry because I wrote a little application and it seems that there is a memory leak if I believe valgrind (What I actually do): ==9321== 251 bytes in 7 blocks are definitely lost in loss record 1 of 1 ==9321== at 0x402569A: operator new(unsigned int) (vg_replace_malloc.c:255) ==9321== by 0x40D3D05: std:...
To quote Valgrind FAQ With GCC 2.91, 2.95, 3.0 and 3.1, compile all source using the STL with -D__USE_MALLOC. Beware! This was removed from GCC starting with version 3.3. With GCC 3.2.2 and later, you should export the environment variable GLIBCPP_FORCE_NEW before running your program. With GCC 3.4 and later, that var...