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
2,885,535
2,885,617
Custom URL protocol in Windows to serve HTML content
This question addresses how to register a custom URL protocol to launch an application in response to a link, but I want my handler to serve dynamic content. Essentially, I'm looking to create a web application that runs on the user's machine instead of a web server. I could set up a localhost, but I want to use a "fr...
I did something similar a few years back, we had a local application and wrote a custom url handler so that we could embed these special links on our web page that when clicked would launch our application and load the file. The technology is called Asynchronous Pluggable Protocols - http://msdn.microsoft.com/en-us/lib...
2,885,597
2,886,432
C++ template name pretty print
I have need to print indented template names for debugging purposes. For example, instead of single-line, I would like to indent name like this: boost::phoenix::actor< boost::phoenix::composite< boost::phoenix::less_eval, boost::fusion::vector< boost::phoenix::argument<0>, boost::phoenix...
Certainly not the most elegant piece, but this should get you going regarding the closing tags: std::string indent(std::string str, const std::string &indent = " ") { std::string indent_ = std::string("\n"); size_t token = 0; while ((token = str.find_first_of("<>,", token)) != std::string::npos) { ...
2,885,750
2,885,827
Difficulties getting GraphViz working as a library in C++
Am working on a program that will allow a graph of nodes to be displayed and then updated visually as the nodes themselves are updated. I am fairly new to Visual Studio 2010 and am following the GraphViz guide located at on the GraphViz website in order to get GraphViz working as a library. I have the following code wh...
You normally need to add the .lib file to the additional input in the first section of the linking area. Correction: properties->Linker->Input->Additional Dependencies.
2,885,809
2,885,913
Where is a good place for a code review?
A few colleagues and I created a simple packet capturing application based on libpcap, GTK+ and sqlite as a project for a Networks Engineering course at our university. While it (mostly) works, I am trying to improve my programming skills and would appreciate it if members of the community could look at what we've put ...
You might get some mileage by posting the code out in the public space (through github or some other open-posting forum), putting a link here on SO, and seeing what happens. You could also make it an open-source project, and see if people find it and use it. Probably your best bet is to talk to your prof/classmates, fi...
2,885,822
2,886,422
Which logging library to use for cross-language (Java, C++, Python) system
I have a system where a central Java controller launches analysis processes, which may be written in C++, Java, or Python (mostly they are C++). All these processes currently run on the same server. What are you suggestions to Create a central log to which all processes can write to What if in the future I push some p...
Apache has cross-platform logging libraries, which allow you to log from various programming languages using similar APIs. Unfortunately they don't have a Python API, though you should be able to whip one up with log4cpp and Boost.Python. A project I work on uses one of these libraries to log to a database, which allo...
2,885,991
2,886,095
Extracting bool from istream in a templated function
I'm converting my fields class read functions into one template function. I have field classes for int, unsigned int, long, and unsigned long. These all use the same method for extracting a value from an istringstream (only the types change): template <typename Value_Type> Value_Type Extract_Value(const std::string...
The strings for true and false are defined by std::numpunct::truename() and std::numpunct::falsename(). You can get the numpunct for a given stream with use_facet <numpunct <char> >(stream.getloc()), if I understand the documentation correctly. EDIT: You can toggle whether to use "1"/"0" or "true"/"false with std::nobo...
2,886,146
2,886,207
Real-time spectrum analyzer with API
I'm looking for a C or C++ API that will give me real-time spectrum analysis of a waveform on Windows. I'm not entirely sure how large a sample window it should need to determine frequency content, but the smaller the better. For example, if it can work with a 0.5 second long sample and determine frequency content to ...
I used FFTW a few years ago. It is supposedly fast (though I didn't use it for anything real-time myself) and was certainly pretty easy to use, even on Windows. Regarding the window size, see the Nyquist-Shannon sampling theorem. (I imagine there are other issues involved when using a window on the data, particularly f...
2,886,193
2,886,229
Visitor and templated virtual methods
In a typical implementation of the Visitor pattern, the class must account for all variations (descendants) of the base class. There are many instances where the same method content in the visitor is applied to the different methods. A templated virtual method would be ideal in this case, but for now, this is not all...
oh, I see what you're after. Try something like this: template < typename Impl > struct Funky_Visitor_Base : Visitor_Base { // err... virtual void operator()(Base_Int& b) { Impl::apply(b) } virtual void operator()(Base_Long& b) { Impl::apply(b) } virtual void operator()(Base_Short& b) { Impl::apply(b) } vi...
2,886,259
2,886,675
gcc 4.5 installation problem under ubuntu
I tried to install gcc 4.5 on ubuntu 10.04 but failed. Here is a compile error that I don't know how to solve. Is there anyone successfully install the latest gcc on ubuntu? Following is my steps and the error message, I'd like to know where is the problem.... Step1: download these files: gcc-core-4.5.0.tar.gz gcc-g++-...
It might not be a good idea to have a space in your path - it's kind of rare and can easily mess up shell scripts that aren't specially designed to deal with it (which is a bad combination!) Another potential problem is that you're running configure inside the gcc source directory - this isn't recommended (and didn't ...
2,886,306
2,886,319
C++ header files and variable scope
I want to organize my c++ variables and functions in the following way: function prototypes in a header file "stuff.h", function implementation in "stuff.cpp", then say #include "stuff.h" in main.cpp (so I can call functions implemented in stuff.cpp). So far so good. Now I want to declare some variables in stuff.cpp...
Declare them as extern. E.g., in stuff.h: extern int g_number; Then in stuff.cc: int g_number = 123; Then in main.cc just #include stuff.h.
2,886,393
2,886,779
Creating rapid function overloads in C++
template<typename Functor, typename Return, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8, typename Arg9, typename Arg10> class LambdaCall : public Instruction { public: LambdaCall(Functor func ...
Turns out I just suck at the boost preprocessing library. #define ternary(z, n, data) data BOOST_PP_COMMA_IF(BOOST_PP_NOT_EQUAL(n, BOOST_PP_SUB(WIDE_RECURSE_UPPER_LIMIT, WIDE_RECURSE))) #define argternary(z, n, data) data ## n BOOST_PP_COMMA_IF(BOOST_PP_LESS(n, BOOST_PP_SUB(WIDE_RECURSE, 1))) template<typen...
2,886,588
2,886,595
TrackMouseEvent not working
Basically, I call TrackMouseEvent in my WM_CREATE then I also called it again after a WM_MOUSELEAVE event, but this freezes up my program. Where should I be sticking it?
You need to call TrackMouseEvent when the mouse enters your control, and not when it leaves your control. You can call TrackMouseEvent on the WM_MOUSEMOVE message. You don't need to call TrackMouseEvent every time WM_MOUSEMOVE is fired, just once up until you get another WM_MOUSELEAVE. After you get a WM_MOUSELEAVE y...
2,886,601
2,886,755
initializing a vector of custom class in c++
Hey basically Im trying to store a "solution" and create a vector of these. The problem I'm having is with initialization. Heres my class for reference class Solution { private: // boost::thread m_Thread; int itt_found; int dim; pfn_fitness f; double value; std::vector<dou...
the example I gave as a comment uses copy constructor to create new objects. You can do the following: // override copy constructor Solution(const Solution &solution) { ... copy from another solution } however be careful, as you no longer going to have exact object copy/construct if you introduce random generation in ...
2,886,609
2,886,654
How to make multiple windows using Win32 API
I see plenty of tutorials and articles showing me how to make a simple windows program, which is great but none of them show me how to make multiple windows. Right now I have working code that creates and draws a layered window and I can blit stuff using GDI to draw anything I want on it, drag it around, even make it ...
You can hit CreateWindow() more than once if you want. The message loop in your WinMain will pass events to all the windows that WinMain creates. You can even create two overlapped windows and set the parent window of the 2nd one to be the handle of the 1st one if you want.
2,886,671
2,886,695
Should I use a global var or call the function every time? C++
Im using: bool GetOS(LPTSTR pszOS) { OSVERSIONINFOEX osve; BOOL bOsVersionInfoEx; ZeroMemory(&osve, sizeof(OSVERSIONINFOEX)); osve.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osve)) ) return false; TCHAR buf[80]; StringCchPrintf...
What's the best option from a performance point of view. Using a variable is much more efficient than a function call even if the function is empty. Just make sure that you initialize this variable when you have a single thread and then don't change it. Does it really matter though? From the info provided it's hard ...
2,886,800
2,886,818
C++ Why am I unable to use an enum declared globally outside of the class it was declared in?
Right now, my project has two classes and a main. Since the two classes inherit from each other, they are both using forward declarations. In the first object, right underneath the #include statement, I initialize two enums, before the class definition. I can use both enums just fine inside that class. However, if I tr...
I'm not sure what issue you are having without seeing your code, but this compiles: enum OutsideEnum { OE_1, OE_2, }; namespace ns { enum NSEnum { NE_1, NE_2, }; } class Base { public: enum BaseEnum { BE_1, BE_2, }; void BaseFunc(); }; class Derived ...
2,886,831
2,901,465
Win32 C/C++ Load Image from memory buffer
I want to load an image (.bmp) file on a Win32 application, but I do not want to use the standard LoadBitmap/LoadImage from Windows API: I want it to load from a buffer that is already in memory. I can easily load a bitmap directly from a file and print it on the screen, but this issue is making me stuck. What I'm look...
Nevermind, I found my solution! Here's the initializing code: std::ifstream is; is.open("Image.bmp", std::ios::binary); is.seekg (0, std::ios::end); length = is.tellg(); is.seekg (0, std::ios::beg); pBuffer = new char [length]; is.read (pBuffer,length); is.close(); tagBITMAPFILEHEADER bfh = *(tagBITMAPFILEHEADER*)pBuf...
2,886,922
2,887,102
Casting to derived type problem in C++
I am quite new to C++, but have worked with C# for years, however it is not helping me here! :) My problem: I have an Actor class which Ball and Peg both derive from on an objective-c iphone game I am working on. As I am testing for collision, I wish to set an instance of Ball and Peg appropriately depending on the a...
Since this is Objective-C code (not C++, as per the title), why not just call: [actorA hitByBall]; [actorB hitByBall]; Updated: If the object you are sending the message to is nil it will be ignored. If the object you send the message to does not implement hitByBall, you'll get an exception, "selector not recognized",...
2,886,984
2,887,031
inspect C++ template instantiation
Is there some utility which would allow me to inspect template instantiation? my compiler is g++ or Intel. Specific points I would like: Step by step instantiation. Instantiation backtrace (can hack this by crashing compiler. Better method?) Inspection of template parameters. @gf helpd me with simple type printing, ...
With templates we simply don't have clean output facilities and there are no compilers i know of that allow you to directly view template instantiations. The closest i found regarding metaprogram debugging was a paper on Templight. For now the best utilities seem to be: static asserts & concept checks (clearly assert ...
2,887,047
2,887,081
Is there a C++ graphing library?
Is there a C++ graphing library that can display visual graphs (such as hyperbolas and parabolas and linear equations) based on the equation it is given and that is cross platform? Or am I just asking for too much...
Let's take your question step by step. "based on the equation [that] it is given" This would require you to write an expression parser; C++ cannot interpret equations "on the fly" without you writing a procedure to do so. For this, I recommend you look at Bison (go straight to the example RPN calc to get the idea). Fo...
2,887,167
2,887,176
What could possibly cause this error when declaring an object inside a class?
I'm battling with this assignment :) I've got two classes: Ocean and Grid. When I declare an object of the Grid inside the Ocean: unsigned int sharkCount; Grid grid; The compiler/complainer says: error C2146: syntax error : missing ';' before identifier 'grid' Can you possibly predict what produces this error with t...
My first guess would be that the definition of Grid simply isn't visible at the point that you've tried to use it in Ocean. Typically this happens if you have each in its own file, and haven't used a header to allow each to be "seen" by the other.
2,887,205
2,887,226
C++: looking for thread based a parallel kd tree library
Are there some implementation for KD-Tree on shared memory machines? thanks Arman.
libkdtree++ or kdtree
2,887,302
2,887,445
Lambda Expressions and Memory Management
How do the Lambda Expressions / Closures in C++0x complicate the memory management in C++? Why do some people say that closures have no place in languages with manual memory management? Is their claim valid and if yes, what are the reasons behind it?
Lambdas can outlive the context they were created in. Binding free variables by reference can be an issue then, because when the lambda wants to access them later, they may not exist anymore. It's simply "Don't return local variables by reference" in disguise.
2,887,465
2,887,555
C++ header and implementation files: what to include?
There is a .h file and a .cpp file with the same name but different extension. If I want to use what's in the .cpp file, do I include the .h file or the .cpp file?
The simple answer is that you almost always want to include .h files, and compile .cpp files. CPP files are (usually) the true code, and H files are (usually) forward-declarations. The longer answer is that you may be able to include either, and it might work for you, but both will give slightly different results. What...
2,887,498
2,887,504
C++ man pages in Ubuntu
In Ubuntu linux I can't get any man pages for C++ keywords. Is there some kind of package I can install to fix this?
sudo apt-get install manpages-dev glibc-doc Look here too for STL.
2,887,507
2,887,517
What do I need to include in my header file for ostream
When I try to compile my program the compiler complains about this line in a .h file that I #included. ostream & Print (ostream & stream); How can this be fixed?
If you #include <ostream>, ostream will be defined in the std namespace: #include <ostream> // ... std::ostream & Print (std::ostream & stream);
2,887,583
2,887,595
Could a derived-class object treated as if it's the same type of a bases class? <noobieQ/>
Say I got: class X_ { public: void do() { } } class Y_ : public X_ { } And I have this function: void foo(X_ whatever) { whatever.do(); } Can I send a "Y_" object to the foo function, would this work? I just realized that I could have tested this myself :)
Yes, but it will get sliced - all the Y_ parts of the object will be chopped off, and it will become an X_. You normally need to pass by reference in this situation, as normally do() will be a virtual function: void foo(X_ & whatever) // ampersand means whatever is a reference { whatever.do(); } BTW, I don't know...
2,887,600
2,887,626
reverse a linked list?
Im trying to reverse the order of the following linked list, I've done so, But the reversed list does not seem to print out. Where have I gone wrong? //reverse the linked list #include <iostream> using namespace std; struct node{ int number; node *next; }; node *A; void add...
Well, the first thing I notice is that you are doing temp = new node and then, on every interaction: temp = temp->next but you are never assigning temp->next so when you finally override the list pointer you are surely giving back some funny value.
2,887,707
2,895,784
How to build Boost with C++0x support?
I don't know how to build Boost with C++0x compilers. Which option must be given to bjam? Should the user.config file be modified?Can someone help me? Best, Vicente
I have found the answer. I was waiting for a features something like 'std' and call it as follows: bjam std=0x but currently we need to use the low level variables cxxflags and add the specific compiler flags. For example for gcc we can do bjam toolset=gcc cxxflags=-std=gnu++0x Other compilers will need a different s...
2,887,713
2,890,419
C++ creating generic template function specialisations
I know how to specialise a template function, however what I want to do here is specialise a function for all types which have a given method, eg: template<typename T> void foo(){...} template<typename T, if_exists(T::bar)>void foo(){...}//always use this one if the method T::bar exists T::bar in my classes is static...
Sadly you are out of luck in this situation as descriped, the best thing you can do is to explicitly specialize the templates as @aaa says. As you can limit these specializations to a simple forwarding to one central function, the overhead for 20 classes should be bearable. E.g.: template<class T> my_foo() { /* do the ...
2,888,134
2,888,206
Rendering sub tools on vertical toolbar
I was wondering how ex Photoshop and Expression Design render sub tools. These show up when for example you hold your mouse down on the fill tool, a sub menu comes up to your right with the fill and gradient tools. I'm just not sure how to go about this because this sub menu would essentially have to be an extension of...
I'm pretty sure that they are created as bona fide transient windows much as the pop-up File menu and sub-menus are. I'd look at the source of GTK or similar to see how precisely that is done. Painting directly on the frame tends to make a window system unhappy.
2,888,501
2,888,514
Using a bitwise AND on more than two bits
I am pretty new to bitwise operators. Let's say I have 3 variables a, b and c, with these values in binary: a = 0001 b = 0011 c = 1011 Now, I want to perform a bitwise AND like this: a AND b AND c -------- d = 0001 d &= a &= b &= c doesn't work (as I expected), but how can I do this? Thanks
What's wrong with just this. d = a & b & c;
2,888,521
2,888,624
std::string manipulation: whitespace, "newline escapes '\'" and comments #
Kind of looking for affirmation here. I have some hand-written code, which I'm not shy to say I'm proud of, which reads a file, removes leading whitespace, processes newline escapes '\' and removes comments starting with #. It also removes all empty lines (also whitespace-only ones). Any thoughts/recommendations? I cou...
A few comments: As another answer (+1 from me) said - ditch the hungarian notation. It really doesn't do anything but add unimportant trash to every line. In addition, ifstream yielding an is_ prefix is ugly. is_ usually indicates a boolean. Naming a function with processXXX gives very very little information on wh...
2,888,749
2,888,787
Storing data with a stand-alone C++ application
I work with Apache, PHP, and MySQL for web development and local applications. For the past couple of years I have slowly been learning C++ and want to build an application this summer. Specifically, I want to make a "library" application in which I can store information about the books, CDs, and records that I own. I ...
Is it possible to create a stand-alone application that does not require a database for storing data? Yes, you could do some sort of custom file format for storing data. If the answer to #1 above is "yes", is it a good idea to do this for an application that could potentially need to manage a lot of data? It's not ...
2,888,805
2,888,808
static const C++ class member initialized gives a duplicate symbol error when linking
I have a class which has a static const array, it has to be initialized outside the class: class foo{ static const int array[3]; }; const int foo::array[3] = { 1, 2, 3 }; But then I get a duplicate symbol foo::array in foo.o and main.o foo.o hold the foo class, and main.o holds main() and uses instances of f...
Initialize it in your corresponding .cpp file not your .h file. When you #include it's a pre-processor directive that basically copies the file verbatim into the location of the #include. So you are initializing it twice by including it in 2 different compilation units. The linker sees 2 and doesn't know which one t...
2,888,843
2,888,849
syntax error : missing ';' before identifier
I am new to c++, trying to debug the following line of code class cGameError { string m_errorText; public: cGameError( char *errorText ) { DP1("***\n*** [ERROR] cGameError thrown! text: [%s]\n***\n", errorText ); m_errorText = string( errorText ); } ...
You need to include <string>, not "string.h". Or in addition to "string.h". string.h is the C header for the standard C string handling functions (strcpy() and friends.) <string> is the standard C++ header where 'string' is defined. You also need to specify the std namespace when using string: std::string m_errorText...
2,888,906
2,889,044
C++ bughunt - High-score insertion in a vector crashes the program
I have a game I'm working on. My players are stored in a vector, and, at the end of the game, the game crashes when trying to insert the high-scores in the correct positions. Here's what I have (please ignore the portuguese comments, the code is pretty straightforward :P): //TOTAL_HIGHSCORES is the max. number of hisco...
You don't say exactly where the code crashes or what the nature of the crash so I shall guess. This test is the wrong way around. it < hiScores.end() && !(stopIterating) In one common case your iterator it will be invalidated in the same clause that you set stopIterating to true. You could do this (!= is more idiomati...
2,889,074
2,889,093
Output spits two extra control characters, possibly a memory corruption bug?
I have the following program test.cc: #include <iostream> unsigned char bogus1[] = { // Changing # of periods (0x2e) changes output after periods. 0x2e, 0x2e, 0x2e, 0x2e }; unsigned int bogus2 = 1816; // Changing this value changes output. int main() { std::clog << bogus1; } I build it with: g++ -g -c -o test.o...
In C/C++, a string is usually stored as a null-terminated char array. Your unsigned char array isn't null-terminated. Usually it would look something like this: unsigned char bogus1[] = { 0x2e, 0x2e, 0x2e, 0x2e, 0x00 // terminating NUL byte }; If it isn't null-terminated, output will continue until a NUL byte is f...
2,889,182
2,889,495
writing structs and classes to disk
The following function writes a struct to a file. #define PAGESIZE sizeof(BTPAGE) #define HEADERSIZE 2L int btwrite(short rrn, BTPAGE *page_ptr) { long addr; addr = (long) rrn * (long) PAGESIZE + HEADERSIZE; lseek(btfd, addr, 0); return (write(btfd, page_ptr, PAGESIZE)); } ...
There's a lot you need to learn here. First of all, you're treating a structure as an array of bytes. This is strictly undefined behavior due to the strict aliasing rule. Anything can happen. So don't do it. Use proper serialization (for example via boost) instead. Yes, it's tedious. Yes, it's necessary. Even if you i...
2,889,186
2,889,191
Should I set global vars value on startup or the first time I use them? C++
I have a few global vars I need to set the value to, should I set it into the main/winmain function? or should I set it the first time I use each var?
Instead, how about not using global variables at all? Pass the variables as function parameters to the functions that need them, or store pointers or references to them as members of classes that use them.
2,889,202
2,889,226
Is there a way to introspect an array's size?
In C++ given an array like this: unsigned char bogus1[] = { 0x2e, 0x2e, 0x2e, 0x2e }; Is there a way to introspect bogus1 to find out is is four characters long?
Sure: #include <iostream> int main() { unsigned char bogus1[] = { 0x2e, 0x2e, 0x2e, 0x2e }; std::cout << sizeof(bogus1) << std::endl; return 0; } emits 4. More generally, sizeof(thearray)/sizeof(thearray[0]) is the number of items in the array. However, this is a compile-time operation and can only be...
2,889,232
2,889,241
How to make a struct of structs in C++
Can a struct contain other structs? I would like to make a struct that holds an array of four other structs. Is this possible? What would the code look like?
Yes, you can. For example, this struct S2 contains an array of four S1 objects: struct S1 { int a; }; struct S2 { S1 the_array[4]; };
2,889,273
2,889,500
How to build boost::asio example?
I'm trying to build an example of boost::asio http://www.boost.org/doc/libs/1_43_0/doc/html/boost_asio/example/echo/async_tcp_echo_server.cpp but without any luck. System: Windows Vista, Visual C++ 2008 Pro, Boost 1.43. I've added to the project, at VC, the include path and the additional lib path (see note #1), yet th...
Check out this, I needed to re-phrase in order to get an answer: fatal error LNK1104: cannot open file 'libboost_system-vc90-mt-gd-1_43.lib' Thank you all!
2,889,337
2,889,346
Why does this C++ char array seem to be able to hold more than its size?
#include <iostream> using namespace std; typedef struct { char streetName[5]; } RECORD; int main() { RECORD r; cin >> r.streetName; cout << r.streetName << endl; } When I run this program, if I enter in more than 5 characters, the output will show the whole string I entered. It does not truncate at...
You are overflowing the buffer. Put another char array after streetName and you will likely find that it gets the rest of the characters. Right now you are just corrupting some memory on your stack.
2,889,392
2,889,484
Adding C++ DLL's to a C# project
I'm trying to use the lame_enc.dll file from LAME in a C# project, but adding the thing seems impossible. I keep getting an error that says that a reference could not be added and to please check if the is accessible, a valid assembly or COM component. I have no C++ experience, though I would like to use the functional...
You have to use P/Invoke to call unmanaged APIs from managed code.
2,889,394
2,889,409
fatal error LNK1104: cannot open file 'libboost_system-vc90-mt-gd-1_43.lib'
Made a new project, added main.cpp and wrote the code at this URL: http://www.boost.org/doc/libs/1_43_0/doc/html/boost_asio/example/echo/async_tcp_echo_server.cpp Also, added the appropriate include path. What's next?!?!! It seems like a darn mystery to build a boost code! Been digging on it for more than 10 hours. Can...
You need to use bjam. It is responsible for creating the libraries that your application will use. Once you use bjam, you are going to need to instruct your project to include the lib file. You do this by going into the project's properties -> Configuration Properties -> Linker -> General. Add the directory which creat...
2,889,421
2,889,483
How to copy a string into a char array in C++ without going over the buffer
I want to copy a string into a char array, and not overrun the buffer. So if I have a char array of size 5, then I want to copy a maximum of 5 bytes from a string into it. what's the code to do that?
First of all, strncpy is almost certainly not what you want. strncpy was designed for a fairly specific purpose. It's in the standard library almost exclusively because it already exists, not because it's generally useful. Probably the simplest way to do what you want is with something like: sprintf(buffer, "%.4s", you...
2,889,771
2,889,794
How to extract comment out of header file using python, perl, or sed?
I have a header file like this: /* * APP 180-2 ALG-254/258/772 implementation * Last update: 03/01/2006 * Issue date: 08/22/2004 * * Copyright (C) 2006 Somebody's Name here * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that...
This should work for you: sed -n '/\*\//q; /^\/\*/d; s/^ \* \?//p' <file.h >comment.txt Here's an explanation: sed (as you may know) is a command that goes through a file applying a list of rules to each line. Each rule consists of a "selector" and commands that are applied to that line only if the selector matches. T...
2,889,964
2,889,990
creating thread on another core? (WinAPI)
I was wondering if there was a way to run a thread on a seperate core instead of just a thread on that core? Thanks
If you create a thread, you have by default no control on which core it will run. The operation system's scheduling algorithm takes care of that, and is pretty good at its job. However, you can use the SetThreadAffinity WinAPI to specify the logical cores a thread is allowed to run on. Don't do that unless you have ver...
2,890,001
2,890,008
Graph - strongly connected components
Is there any fast way to determine the size of the largest strongly connected component in a graph? I mean, like, the obvious approach would mean determining every SCC (could be done using two DFS calls, I suppose) and then looping through them and taking the maximum. I'm pretty sure there has to be some better approac...
Let me answer your question with another question - How can you determine which value in a set is the largest without examining all of the values?
2,890,320
2,890,355
can these templates be made unambiguous
I'm trying to create a set of overloaded templates for arrays/pointers where one template will be used when the compiler knows the size of the array and the other template will be used when it doesn't: template <typename T, size_t SZ> void moo(T (&arr)[SZ]) { ... } template <typename T> void moo(T *ptr) { ... } The p...
It is possible as it can be determined wether a template parameter is an array or not: template<class T> struct is_array { enum { value = false }; }; template<class T, size_t N> struct is_array<T[N]> { enum { value = true }; }; template<class T> void f(T const&) { std::cout << is_array<T>::value << std::e...
2,890,408
2,890,428
Is there a var type equivalent in C++?
So I know that C++ is strongly typed and was just wondering if there was any library (or any thing for that fact of the matter) that would allow you to make a variable that has no initial specific type like var in Python.
Take a look at boost::any and boost::variant.
2,890,525
2,890,537
Sorting odd in descending and even in ascending order
Given a array of random integers, sort the odd elements in descending order and even numbers in ascending order. Example input: (1,4,5,2,3,6,7) Output: (7,5,3,1,2,4,6) Optimize for time complexity.
Which language is it, C or C++ (I see both tags) In C++, you can use std::sort() with appropriate ordering function. In C, qsort() works similarly: #include <iostream> #include <algorithm> bool Order(int a, int b) { if (a%2 != b%2) return a%2; else return a%2 ? b<a : a<b; } int main() { int a[] ...
2,890,536
2,890,543
c++ passing unknown type to a function and any Class type definition
I am trying to create a generic class to write and read Objects to/from file. Called it ActiveRecord class only has one method, which saves the class itself: void ActiveRecord::saveRecord(){ string fileName = "data.dat"; ofstream stream(fileName.c_str(), ios::out); if (!stream) { cerr << "Error opening file: " <<...
stream.write(reinterpret_cast<const char *> (foo_instance), sizeof(FooClass)); This doesn't work. string allocates its data on the heap (IIRC, when it's larger than 16chars). Your reinterpret cast will not include that heap data. Don't reinvent the wheel, this is a non-trivial, but solved problem. Use Google Protoc...
2,890,588
2,890,596
Weird characters at the beginning of a LPTSTR? C++
I am using this code to get the windows version: #define BUFSIZE 256 bool config::GetOS(LPTSTR OSv) { OSVERSIONINFOEX osve; BOOL bOsVersionInfoEx; ZeroMemory(&osve, sizeof(OSVERSIONINFOEX)); osve.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &...
Your problem is that you should be using StringCchCopy and not StringCchCat. StringCchCat will search until it finds a 0 in the string, and then append the result there. Since you are not initializing your output string buffer to 0's, you cannot assume it will start with a 0.
2,890,589
2,890,599
C++ destructors causing crash's
ok, so i got a some what intricate program that simulates the uni systems of students, units, and students enrolling in units. Students are stored in a binary search tree, Units are stored in a standard list. Student has a list of Unit Pointers, to store which units he/she is enrolled in Unit has a list of Student poin...
If your UnitCollection is std::list<Unit> then you don't have to manually remove items - the list itself with destroy contained objects and deallocate the memory in its own destructor. Take a look at std::list documentation. I would also suggest that you post complete code - some of your description is contradictory.
2,890,635
2,898,013
Error with Phoenix placeholder _val in Boost.Spirit.Lex :(
I'm newbie in Boost.Spirit.Lex. Some strange error appears every time I try to use lex::_val in semantics actions in my simple lexer: #ifndef _TOKENS_H_ #define _TOKENS_H_ #include <iostream> #include <string> #include <boost/spirit/include/lex_lexertl.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include...
I believe this is a problem in the current Phoenix related to using iostreams. As a workaround I suggest to define a custom (Phoenix) function doing the actual output: struct output_operation_impl { template <typename TokenId, typename Val> struct result { typedef void type; }; template <typename TokenId, ...
2,890,722
2,890,728
Including huge string in our c++ programs?
I am trying to include huge string in my c++ programs, Its size is 20598617 characters , I am using #define to achieve it. I have a header file which contains this statement #define "<huge string containing 20598617 characterd>" When I try to compile the program I get error as fatal error C1060: compiler is out of he...
You can't, not reliably. Even if it will compile, it's liable to break the runtime library, or the OS assumptions, and so forth. If you tell us why you're trying to do it, we can offer lots of alternatives. Deciding how to handle arbitrarily large data is a major part of programming. Edited to add: Rather than guess, ...
2,890,811
2,890,816
handling large number
This is Problem 3 from Project Euler site I'm not out after the solution, but I probably guess you will know what my approach is. To my question now, how do I handle numbers exceeding unsigned int? Is there a mathematical approach for this, if so where can I read about it?
Have you tried unsigned long long or even more better/specifically uint64_t? If you want to work with numbers bigger than the range of uint64_t [264-1] [64 bit integer, unsigned], then you should look into bignum: http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic. 600,851,475,143 is the number given by the ...
2,890,860
2,890,867
C++ error: ‘string’ has not been declared
In my header file I'm getting the error: ‘string’ has not been declared error but at the top of the file I have #include <string>, so how can I be getting this error?
string resides in the std namespace, you have to use std::string or introduce it into the scope via using directives or using declarations.
2,891,166
2,894,290
Pages used by a DLL in the address space of a process
Is there a reliable way to learn that a memory page or a range of pages belongs to a specific DLL inside the address space of a process?
There are a method known as API hooking. Well known BugslayerUtil.DLL from John Robbins (see his book "Debugging Applications") war used originally as API hooking inside own process. I mean that all memory allocation can be allocated with respect of small number of well known functions like LocalAlloc, GlobalAlloc, Vir...
2,891,275
2,891,308
How to fill a section within c++ string?
Having a string of whitespaces: string *str = new string(); str->resize(width,' '); I'd like to fill length chars at a position. In C it would look like memset(&str[pos],'#', length ); How can i achieve this with c++ string, I tried string& assign( const string& str, size_type index, size_type len ); but this seem...
In addition to string::replace() you can use std::fill: std::fill(str->begin()+pos, str->begin()+pos+length, '#'); //or: std::fill_n(str->begin()+pos, length, '#'); If you try to fill past the end of the string though, it will be ignored.
2,891,344
2,891,453
Visual studio feature - commenting code Ctrl K - Ctrl C
I commented on this answer some time ago regarding how visual studio comments out code with // or /* */. I was thinking to revise the answer (to include my findings) but I had to test it first, which kind of confused me. My finding is that depending on what you comment when you press Ctrl - K, Ctrl - C you will get eit...
The approach one would expect is to use // for any selection that is made up entirely of complete lines, and /*...*/ for anything that starts/ends mid-way along a line. ...which is what it seems to actually do.
2,891,525
2,891,620
Finding the maximum weight subsequence of an array of positive integers?
I'm tring to find the maximum weight subsequence of an array of positive integers - the catch is that no adjacent members are allowed in the final subsequence. The exact same question was asked here, and a recursive solution was given by MarkusQ thus: function Max_route(A) if A's length = 1 A[0] else maximum...
I don't really understand that pseudocode, so post the C++ code if this isn't helpful and I'll try to improve it. I'm tring to find the maximum weight subsequence of an array of positive integers - the catch is that no adjacent members are allowed in the final subsequence. Let a be your array of positive ints. Let f...
2,891,596
2,930,981
MySQL Connector Linker Problem
Hey, I'm trying to compile a program with the MySQL C++ Connector but somehow I can't get the linking right. The errors I get are: mysql/lib/libmysqlcppconn.so: undefined reference to `std::ios_base::ios_base()@GLIBCPP_3.2'.... etc alt text http://img156.imageshack.us/img156/4022/linking.th.png locations: libmysqlcpp...
OK, it seems like the connector (binary) requires a certain libstdc++.so version (5) since I couldn't fix that I had to use the sources. Some errors I encountered while compiling them where that I had to include <stdio.h>. Now Everything is working!
2,891,690
2,891,732
Closure and nested lambdas in C++0x
Using C++0x, how do I capture a variable when I have a lambda within a lambda? For example: std::vector<int> c1; int v = 10; <--- I want to capture this variable std::for_each( c1.begin(), c1.end(), [v](int num) <--- This is fine... { std::vector<int> c2; std::for_each( c2...
std::for_each( c1.begin(), c1.end(), [&](int num) { std::vector<int> c2; int& v_ = v; std::for_each( c2.begin(), c2.end(), [&](int num) { v_ = num; } ...
2,891,865
2,891,875
bind() fails with windows socket error 10038
I'm trying to write a simple program that will receive a string of max 20 characters and print that string to the screen. The code compiles, but I get a bind() failed: 10038. After looking up the error number on msdn (socket operation on nonsocket), I changed some code from int sock; to SOCKET sock which shouldn't ...
The problem is with servSock=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)==INVALID_SOCKET which does not associate as you think it does. Why would you even want to write something like that, what's wrong with SOCKET servSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(servSock == INVALID_SOCKET) DieWithError("soc...
2,891,926
3,328,170
Create thread is not accepting the member function
I am trying to create a class for network programming. This will create a general purpose socket with thread. But when I tried to crete the thread using createthread(). The third argument is producing errors. And from the net I came to know that I can't use the member functions as an argument to the createthread(). Is ...
At lost I got it, the very fact is, in CreateThread if you pass the socket then there is no trouble. Because CreateThread is taking care of that socket. But if you pass as an object which is having that socket, then CreateThread is not taking care of the socket, and it is ends up in invalid socket in the new thread. Th...
2,891,966
2,892,158
What are the advantages of squashing assignment and error checking in one line?
This question is inspired by this question, which features the following code snippet. int s; if((s = foo()) == ERROR) print_error(); I find this style hard to read and prone to error (as the original question demonstrates -- it was prompted by missing parentheses around the assignment). I would instead write the ...
When you are writing a loop, it is sometimes desirable to use the first form, as in this famous example from K&R: int c; while ((c = getchar()) != EOF) { /* stuff */ } There is no elegant "second-form" way of writing this without a repetition: int c = getchar(); while (c != EOF) { /* stuff */ c = getchar...
2,892,087
2,892,133
If the address of a function can not be resolved during deduction, is it SFINAE or a compiler error?
In C++0x SFINAE rules have been simplified such that any invalid expression or type that occurs in the "immediate context" of deduction does not result in a compiler error but rather in deduction failure (SFINAE). My question is this: If I take the address of an overloaded function and it can not be resolved, is that...
template<class T> void f(T, typename size_map<sizeof(&U::foo)>::type* = 0); This doesn't work, because U does not participate in deduction. While U is a dependent type, during deduction for f it's treated like a fixed type spelled with a nondependent name. You need to add it to the parameter list of f /* fortuna...
2,892,096
2,894,132
Serial: write() throttling?
I'm working on a project sending serial data to control animation of LED lights, which need to stay in sync with an animation engine. There seems to be a large serial write buffer (OSX (POSIX) + FTDI chipset usb serial device), so without manually throttling calls to write(), the software can get several seconds ahead ...
If you want to slow your animation down to match the maximum speed that you can write to the LEDs, you can just use tcdrain(); something like this: while (1) { write(serial_fd, led_command); animate_frame(); tcdrain(serial_fd); }
2,892,189
2,892,378
Color space - RGB and YCbCr question
I am now trying to understand how JPEG encoding works and everything seems fine except the color transformation part. Before attempting to do a DCT in JPEG algorithm, the image is transformed into YCbCr color space. To me this essentially means that we just (comparing to initial RGB image) take a chunk of color informa...
To me this essentially means that we just (comparing to initial RGB image) take a chunk of color information and dispose it while applying the RGB -> YCbCr transformation. No information gets disposed by the transformation itself. The transformation is reversible in a mathematical sense. E.g. if you convert a...
2,892,294
2,892,317
Creating many polygons with OpenGL is slow?
I want to draw many polygons to the screen but i'm quickly noticing that it slows down quickly. As a test I did this: for(int i = 0; i < 50; ++i) { glBegin( GL_POLYGON); glColor3f( 0.0f, 1, 0.0f ); glVertex2f( 500.0 + frameGL.GetCameraX(), 0.0f + frameGL.GetCameraY()); glColor3f( 0.0f, 1.0f, 0.0...
as already mentioned don't do glBegin and glEnd in the loop but outside for even better performance use vertex arrays for optimal performance use vertex buffer objects The solutions are ordered in how much speed gain you will get, and inversly how wide supported they are. That said, any modern graphics card supports ...
2,892,303
2,892,364
how many color combinations in a 24 bit image
I am reading a book and I am not sure if its a mistake or I am misunderstanding the quote. It reads... Nowadays every PC you can buy has hardware that can render images with at least 16.7 million individual colors. Rather than have an array with thousands of color entries, the images instead contain explicit...
The combinations of 8 bits is not 82 (64) but 28 (256). This is because each of the 8 bits can have 2 distinct values. For 1 bit that would give you 2 (21) possibilities, for 2 bits 2*2 (22), for 3 bits 2*2*2 (23)... etc. 3 bytes = 24 bits => 224 = 16.7M possible combinations.
2,892,477
2,892,507
gcc optimization? bug? and its practial implication to project
My questions are divided into three parts Question 1 Consider the below code, #include <iostream> using namespace std; int main( int argc, char *argv[]) { const int v = 50; int i = 0X7FFFFFFF; cout<<(i + v)<<endl; if ( i + v < i ) { cout<<"Number is negative"<<endl; } else {...
It's a known problem, and I don't think it's considered a bug in the compiler. When I compile with gcc 4.5 with -Wall -O2 it warns warning: assuming signed overflow does not occur when assuming that (X + c) < X is always false Although your code does overflow. You can pass the -fno-strict-overflow flag to turn that p...
2,892,512
2,892,542
C++ Scoping and ambiguity in constructor overloads
I've tried the following code snippet in 3 different compilers (G++, clang++, CL.exe) and they all report to me that they cannot disambiguate the overloaded constructors. Now, I know how I could modify the call to the constructor to make it pick one or the other (either make explicit that the second argument is a unsi...
In C++, accessibility to class members doesn't influence the other language semantics. Instead, any invalid access causes a program to be ill-formed. In other words, there is accessibility and visibility. The Standard has it straight It should be noted that it is access to members and base classes that is controlled,...
2,892,649
2,892,727
terminate called after throwing an instance of 'std::length_error'
this is my first post here. As i am newbie, the problem might be stupid. I was writing a piece of code while the following error message shown, terminate called after throwing an instance of 'std::length_error' what(): basic_string::_S_create /home/gcj/finals /home/gcj/quals where Aborted the following is the offend...
You are adding items to the dirs and need vectors while iterating over them. This is not allowed: if adding an item requires a reallocation, it will invalidate all existing iterators, and can cause various errors when you next access them.
2,892,673
2,892,711
textures and vertex arrays with OpenGL?
Basically what I'd like to do is make textured NGONS. I also want to use a tesselator (GLU) to make concave and multicontour objects. I was wondering how the texture comes into play though. I think that the tesselator will return verticies so I will add these to my array, that's fine. But my vertex array will contain ...
If you're going to use glDrawArrays or glDrawElements, you'll have to draw your vertices in pieces, one piece per texture. The same texture is used for the entire call. (These calls are like a potentially more efficient version of submitting the same data by hand within glBegin and glEnd, and you can't change texture i...
2,892,690
2,913,601
Mesh triangulation and simplification C++ library
I am looking for a C++ library to triangulate and simplify 3D mesh. My 3D meshes are potentially huge (around 3 millions vertices). It should ideally be open source. Any idea?
Here are some libraries I found: 1) CGAL ++ Does a lot of things; -- Licensing issues; 2) GTS ++ Open source and quite easy to use; -- Does less that CGAL anymore ideas?
2,892,781
3,030,420
Objective-C++ visibility question
I have linked a library with my program. It works fine. The only problem is that there visibility errors/warnings (thousands of them). They are all of the form: newlib::method() has different visibility (default) in newlib.a and (hidden) in AppDelegate.o It is always with AppDelegate.o. I have tried to set the visibil...
The XCode system for dealing with errors is not very bright. I had a function called Error() and XCode treated every warning about this function as an error.
2,892,832
2,893,140
Boost Thread Synchronization
I don't see synchronized output when i comment the the line wait(1) in thread(). can I make them run at the same time (one after another) without having to use 'wait(1)'? #include <boost/thread.hpp> #include <iostream> void wait(int seconds) { boost::this_thread::sleep(boost::posix_time::seconds(seconds)); } bo...
"at the same time (one after another)" is contradictory. With a call to sleep() they run at the same time. Without a call to sleep(), they run one after another. With only 100 lines to output, thread t1 completes before t2 has a change to begin execution. On my computer, I had to set your loop counter to 10000 before t...
2,892,855
2,892,887
What library to choose to build a user interface for a C++ software that uses SDL
I have a simulation software (C++) that runs on the command line. It is platform independent (currently compiling and running on Windows, MacOS X and Linux). When the simulation ends, I visualize the result with SDL; it is a very basic 2d view, mainly color squares next to each other. I would like to have a user inter...
Probably using wxWidgets without SDL would be the easiest way to go. SDL is a media layer -- it's supposed to allow cross-platform media application development. As you only need graphical display, you only need wxWidgets -- and it will be a lot easier too! You would benefit from SDL if: you'd need very fast blitting ...
2,892,928
2,897,215
Get version of installed Flash ActiveX in Win32/C++
Is this even possible? I'm embedding Flash inside an IE frame in my application and would like to check if Flash and what version of it is installed. The application needs to run without admin privileges. Bonus question: Can I also check if ActiveX controls are enabled in the IE settings?
The solution is to search for the CLSID of Flash ("{D27CDB6E-AE6D-11cf-96B8-444553540000}") in the registry under HKEY_CLASSES_ROOT\CLSID. There you can read \InprocServer32 which gives you the OCX. Then get the version via GetFileVersionInfo. This should work for any COM control.
2,893,101
2,893,123
How to rotate a N x N matrix by 90 degrees?
How to rotate a N x N matrix by 90 degrees. I want it to be inplace?
for(int i=0; i<n/2; i++) for(int j=0; j<(n+1)/2; j++) cyclic_roll(m[i][j], m[n-1-j][i], m[n-1-i][n-1-j], m[j][n-1-i]); void cyclic_roll(int &a, int &b, int &c, int &d) { int temp = a; a = b; b = c; c = d; d = temp; } Note I haven't tested this, just compoosed now on the spot. Please test bef...
2,893,129
2,893,142
What does '**' mean in C?
What does it mean when an object has two asterisks at the beginning? **variable
It is pointer to pointer. For more details you can check: Pointer to pointer It can be good, for example, for dynamically allocating multidimensional arrays: Like: #include <stdlib.h> int **array; array = malloc(nrows * sizeof(int *)); if(array == NULL) { fprintf(stderr, "out of memory\n"); exit or return } f...
2,893,164
2,893,618
Texturing and Texture Mapping GLUTess Polygons?
How exactly does one provide texture coordinates and bind a texture for a GLUTess polygon? Thanks
I don't know If I understend you correctly. Texturing is described well in redbook. They use GLUT in the book, so you should find the answer in the examples. In short: call glTexCoord2f(u,v) before call to glVertex (if you do not use VBO), where u,v are texture coordinates. HTH EDIT: Sorry, now I understand the questio...
2,893,220
2,894,853
Organization of linking to external libraries in C++
In a cross-platform (Windows, FreeBSD) C++ project I'm working on, I am making use of two external libraries, Protocol Buffers and ZeroMQ. In both projects, I am tracking the latest development branch, so these libraries are recompiled / replaced often. For a development scenario, where is the best place to keep libpro...
I would suggest you don't copy files around in the source tree, and definitely not into the system folder, instead go for a defined target location - $BUILD_TARGET/bin - final binary destination (.exe/.so/.dll etc) $BUILD_TARGET/obj - object file destination (.obj etc) $BUILD_TARGET/lib - static library destination (....
2,893,365
2,893,375
Libraries for visualizing graphs in real-time using C++
Are there any good C++ libraries that can be used to visualize a graph of objects that have been instantiated and have random connections to each other? I would also need it to be able to be updated in real-time so that the graph was constantly updated.
If you use the Boost Graph Library then it supports the graphviz dot language. Otherwise it shouldn't be hard to write the code on your own.
2,893,713
2,893,798
Pthread Queue System
I'm working on my assignment on pthreads. I'm new and never touched on pthreads before. Is there any sample codes or resources out there that anyone of you have, that might aid me in my assignment? Here are my assignment details. A pthread program about queue system: Write a C/C++ Pthread program for a Dental clinic’s...
For generally starting out with pthreads, this is a good website with possibly more info than you need (but I like detail). It runs through a lot of the basics for pthreads and more. If you prefer a dead-tree tutorial, this book is pretty good and gives you a good grounding in most of the features of the Linux API, or ...
2,893,791
2,983,636
C++: Can virtual inheritance be detected at compile time?
I would like to determine at compile time if a pointer to Derived can be cast from a pointer to Base without dynamic_cast<>. Is this possible using templates and metaprogramming? This isn't exactly the same problem as determining if Base is a virtual base class of Derived, because Base could be the super class of a vir...
I had the same problem, once. Unfortunately, I'm not quite sure about the virtual-problem. But: Boost has a class named is_base_of (see here) which would enable you to do smth. like the following BOOST_STATIC_ASSERT((boost::is_base_of<Foo, Bar>::value)); Furthermore, there's a class is_virtual_base_of in Boost's type_...
2,894,006
2,894,011
How to assign a string value to a string variable in C++
Shouldn't this work? string s; s = "some string";
Yes! It's default constructing a string, then assigning it from a const char*. (Why did you post this question?... did you at least try it?)
2,894,083
2,894,102
Difference dynamic static 2d array c++
Im using opensource library called wxFreeChart to draw some XY charts. In example there is code which uses static array as a serie : double data1[][2] = { { 10, 20, }, { 13, 16, }, { 7, 30, }, { 15, 34, }, { 25, 4, }, }; dataset->A...
If You define an array like double myArr[5][2]; All cells occupy a continuous chunk of memory and I'm pretty sure dataset->AddSerie relies on that. You can't guarantee that if you allocate memory in chunks, using consecutive calls to new. My proposition is to write a simple class that allocates a continuous chunk of m...
2,894,191
2,895,106
How can I improve my real-time behavior in multi-threaded app using pthreads and condition variables?
I have a multi-threaded application that is using pthreads. I have a mutex() lock and condition variables(). There are two threads, one thread is producing data for the second thread, a worker, which is trying to process the produced data in a real time fashion such that one chuck is processed as close to the elapsin...
I could suggest the following pattern. Generally the same technique could be used, e.g. when prebuffering frames in some real-time renderers or something like that. First, it's obvious that approach that you describe in your message would only be effective if both of your threads are loaded equally (or almost equally) ...
2,894,229
2,894,236
Running a shellscript from a C++ application and check if it succeeds
I am creating an interpreter for my extension to HQ9+, which has the following extra command called V: V: Interpretes the code as Lua, Brainfuck, INTERCAL, Ruby, ShellScript, Perl, Python, PHP in that order, and if even one error has occoured, run the HQ9+-ABC code again most of them have libraries, BF and INTERCAL c...
From man system(3): RETURN VALUE The value returned is -1 on error (e.g. fork failed), and the return status of the command otherwise. This latter return status is in the format specified in wait(2). Thus, the exit code of the command will be WEXITSTATUS(status). In case /...
2,894,306
2,895,253
GLTessellator crashing
I'v followed a tutorial to get the GLU tesselator working. It works except the interpolation for colors of new points causes a crash after creating a random polygon(error reading from memory...) This is my callback where it crashes: void CALLBACK combineCallback(GLdouble coords[3], GLdouble *vertex_data[4], GL...
My guess is that vertex_data is wrong. It is the same pointer that you pass to gluTessVertex function. What does that pointer point to?
2,894,391
2,894,632
Best way to get individual digits from int for radix sort in C/C++
What is the best way to get individual digits from an int with n number of digits for use in a radix sort algorithm? I'm wondering if there is a particularly good way to do it in C/C++, if not what is the general best solution? edit: just to clarify, i was looking for a solution other than converting it to a string and...
Use digits of size 2^k. To extract the nth digit: #define BASE (2<<k) #define MASK (BASE-1) inline unsigned get_digit(unsigned word, int n) { return (word >> (n*k)) & MASK; } Using the shift and mask (enabled by base being a power of 2) avoids expensive integer-divide instructions. After that, choosing the best ...
2,894,429
2,894,450
Will a destructor destroy a static member?
Say I have: class A { A() {} ~A() {} }; class B { public: B() {} ~B() {} private: static A mA; }; B* pB = new B; delete pB; When I call delete pB, B's destructor will be called. Will this then call the destructor for static member A?
The keyword static means that the variable is independent of instances. That's why you can access static variables and methods without instantiating an object from the class in the first place. That's why destroying an instance will not affect any static variables.
2,894,595
2,898,140
Source-to-source compiler framework wanted
I used to use OpenC++ (http://opencxx.sourceforge.net/opencxx/html/overview.html) to perform code generation like: Source: class MyKeyword A { public: void myMethod(inarg double x, inarg const std::vector<int>& y, outarg double& z); }; Generated: class A { public: void myMethod(const string& x, double& y);...
I do not know of any ready-to-use solution, but you could build your own with a relatively little effort. One possible option is Elsa C++ parser, a bit out of date, but easy to use and quite extendible. Another option is to tamper with XML ASTs produced by Clang++. I used both approaches in different scenarios.
2,894,804
2,895,304
Handling lot of items in std::stack
Can C++ std::stack handle more than 10k int items? And how about its performance?
The performance depends on the underlying container used. As already mentioned, stack is an adapter, the underlying container can be deque (the default), or vector, or list (all in std namespace). Following is an example of performance comparison. As the type to be stored is not clearly mentioned in the question, I am...
2,895,313
2,895,330
What is the cost of a #define?
To define constants, what is the more common and correct way? What is the cost, in terms of compilation, linking, etc., of defining constants with #define? It is another way less expensive?
The best way to define any const is to write const int m = 7; const float pi = 3.1415926f; const char x = 'F'; Using #define is a bad c++ style. It is impossible to hide #define in namespace scope. Compare #define pi 3.1415926 with namespace myscope { const float pi = 3.1415926f; } Second way is obviously better.