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 |
|---|---|---|---|---|
4,043,930 | 4,043,963 | Is using namespace..like bad? |
Possible Duplicate:
Why is 'using namespace std;' considered a bad practice in C++?
Every time I use using namespace std I always get that "thats a terrible programming habit".
Now I'm graduating this December with my B.S. in C.S. but I don't claim to know everything, but no one has ever explained why this is so bad... | found this useful post elsewhere:
Namespaces separate and organize functionality. You can have a xander333::sort() function and it won't conflict with std::sort() or boost::sort() or any other sort(). Without namespaces there can be only one sort().
Now let's say you've put "using namespace std;" in all your source fil... |
4,043,987 | 4,045,327 | Is there a solution for Floating point Arithmetic problems in C++? | I am doing some floating point arithmetic and having precision problems. The resulting value is different on two machines for the same input. I read the post @ Why can't I multiply a float? and also read other material on the web & understood that it is got to do with binary representation of floating point and on mach... | A short must be at least 16 bits, and in a whole lot of implementations that's exactly what it is. An unsigned 16-bit short will hold values from 0 to 65535. That means that a short will not hold a full five digits of precision, and certainly not six. If you want six digits, you need 20 bits.
Therefore, any loss of ... |
4,044,078 | 4,044,082 | Extract a struct member from an array of structs | I have an array of structures that contain multiple variables:
struct test_case {
const int input1;
//...
const int output;
};
test_case tc[] = {
{0, /**/ 1},
// ...
{99, /**/ 17}
};
int tc_size = sizeof(tc) / sizeof(*tc);
and I want to extract a vector of the outputs so I can compare them... | Yes, adding boost::bind is the answer:
std::transform(test_cases,
test_cases + tc_size,
back_inserter(output_vector),
boost::bind(&test_case::output, _1));
This works because std::transform passes in a test_case parameter into the functor generated by bind(). The functo... |
4,044,188 | 4,044,228 | Translate C++ Constructor into Java | I'm working on translating a small package from C++ to Java. I've never really used C++, so some of the syntax is a bit of a mystery. In particular, I'm having difficulty working out what the Java equivalent to this would be:
file: SomeClass.cpp
SomeClass::SomeClass( BitStream* data, const char* const filename ) :
... | Everything after ":" is called the member initialization list, in C++ this is one way of initialising the members of this class. For example from your code, "data" is a member of SomeClass, so the equivalent in Java would be a simple assignment in the body of the constructor.
this.data = data;
etc. for all the other m... |
4,044,204 | 4,044,343 | How can I initialise a static member of a class after certain other initialisation has taken place? | I want to be able to initialise the static member scalingfactor in the following class:
class ScalingRect: public Rect
{
public:
static float scalingfactor;
...
};
I thought I'd initialise it using a static member function of another class like this in the .cpp
float ScalingRect::Rect = Engine::GetScaleFactor... | instead of having the static as a class member, make it a static inside a static method, and return a reference to it:
class ScalingRect: public Rect
{
public:
static float& scalingfactor()
{
if (!Engine::initilized()) throw ("initilize Engine first!");
static float value = Engine::GetScaleFactor();... |
4,044,255 | 4,044,271 | passing a string literal to a function that takes a std::string& | I have the following function
void AddNodeValue(XMLNode& node, std::string& value);
I want to use it like this:
document.AddNodeValue(modvalue,"modvalue");
and the compiler complains:
error C2664: 'void XML::XMLDocument::AddNodeValue(XML::XMLNode &,std::string &)' : cannot convert parameter 2 from 'const char [9]'... | Your function needs to take const std::string& for you to use it like that.
C++ has a rule that an rvalue (in your case, a temporary std::string which is created from the string literal) can be bound with a const reference, but not a non-const reference.
As far as I know, this restriction isn't due to any fundamental i... |
4,044,275 | 4,044,347 | How Many default methods does a class have? | Sorry, this might seem simple, but somebody asked me this, and I don't know for certain.
An empty C++ class comes with what functions?
Constructor,
Copy Constructor,
Assignment,
Destructor?
Is that it? Or are there more?
| In C++03 there are 4:
Default constructor: Declared only if
no user-defined constructor is
declared. Defined when used
Copy constructor - declared only if the user hasn't declared one. Defined if used
Copy-assignment operator same as above
Destructor same as above
In C++11 there are two more:
Move constructor
Mo... |
4,044,466 | 4,044,572 | Is `x-- > 0 && array[x]` well-defined behavior in C++? | Can I use x on both sides of a boolean expression when I post-increment it on the left side?
The line in question is:
if(x-- > 0 && array[x]) { /* … use x … */ }
Is that defined through the standard? Will array[x] use the new value of x or the old one?
| It depends.
If && is the usual short-circuiting logical operator, then it's fine because there's a sequence point. array[x] will use the new value.
If && is a user (or library) defined overloaded operator, then there is no short-circuit, and also no guarantee of a sequence point between the evaluation of x-- and the ev... |
4,044,500 | 4,044,532 | C++ - Undefined reference issues when working with classes | I am working on a small project where I use multiple classes. One of those classes is Menu, which has a showContainer method. Here's the class declaration:
class Menu {
//snip
Menu();
Menu(std::string, std::string, int, int);
virtual ~Menu();
//snip
/**
* Visualiza e providencia navegacao p... | You definition of the Menu::showContainer function template must be visible to the code calling it, unless it's been explicitly instantiated for the type used in the call.
Chances are you've defined down in some implementation file.
If so, move it into the header.
Cheers & hth.,
|
4,044,590 | 4,044,613 | Can I check in C(++) if an array is all 0 (or false)? | Can I check in C(++) if an array is all 0 (or false) without iterating/looping over every single value and without allocating a new array of the same size (to use memcmp)?
I'm abusing an array of bools to have arbitrary large bitsets at runtime and do some bitflipping on it
| You can use the following condition:
(myvector.end() == std::find(myvector.begin(), myvector.end(), true))
Obviously, internally, this loops over all values.
The alternative (which really should avoid looping) is to override all write-access functions, and keep track of whether true has ever been written to your vecto... |
4,044,815 | 4,074,303 | How to interpret a custom language | I have an app in C++ which actually processes a binary file. The binary file is a collection of events say A/B/C, and on detecting event A in the file, the app handles the event in "handler A".
Now i need to write another script in a custom language, which gets executed orthogonally to the binary file processing. The s... | An easy way to build an interpreter:
Define a parser for the language from its syntax
Build an abstract syntax tree AST
Apply a visitor function is traverse the AST in preorder and "execute" actions suggested by the AST nodes.
Some AST nodes will be "definitional", e.g., will declare the existence of some named enti... |
4,045,216 | 4,045,272 | Am I missing anything here in my statement about c++? | You can't have code outside of functions except for declarations, definitions and preprocessor directives.
Is that statement accurate, or is there something I'm missing? I'm teaching my nephew to program, and he was trying to put a while loop before main. He's pretty young, I want to give him a hard simple rule that ... | Not quite -- you can also put expressions in global variable declarations:
int myGlobalVar = 3 + SomeFunction(4) - anotherGlobalVar;
But you can only put expressions here, which have to evaluate to the value you're initializing the global with. You cannot put full statements (no blocks of code, no if statements, no l... |
4,045,228 | 4,045,317 | c++ for_each() and object functions | I have an assignment that is the following:
For a given integer array, find the sum of its elements and print out the final
result, but to get the sum, you need to execute the function for_each() in STL
only once (without a loop).
As of now this is my code:
void myFunction (int i) {
cout << " " << i << " " << endl;
} ... | why not just:
for_each( array, array+10, myFunction);
I'm quite sure that int* can be used as iterator
EDIT: just checked this, it can indeed
|
4,045,643 | 4,045,657 | C++ Copy Objects from a file to a Array | Hi need to copy the written objects in a file to copy to a array But following code gives me a Error
T Obj
T arr[20];
while(file.read((char*)&Obj,sizeof(Obj))){
int i=0;
i++
arr[i]==Obj;
}
Error C2678: binary '==' : no operator found which takes a left-hand oper... | Well, firstly, the operator == is used for comparison, not assignment. For assignment, you want a single =. Secondly, your code is not portable, and possibly broken, because the way your object is stored on disk as a sequence of bytes is not necessarily the same way that it is stored in memory as a T object. This is... |
4,045,669 | 4,045,703 | C++ for_each() and the function pointer | I am try to make the myFunction give me a sum of the values in the array, but I know I can not use a return value, and when I run my program with the code as so all I get is a print out of the values and no sum why is that?
void myFunction (int i) {
int total = 0;
total += i;
cout << total;
}
int main() {
int array[]... | You really need a functor to store state between iterations:
struct Sum
{
Sum(int& v): value(v) {}
void operator()(int data) const { value += data;}
int& value;
};
int main()
{
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int total = 0;
std::for_each( array, array+10, Sum(total));
s... |
4,045,745 | 4,046,044 | detect obsolete and incorrect function prototypes with autoconf | I maintain an open source program that builds with autoconf.
Right now I'm having a problem with some of my users. They are using a pre-distributed VM from an organization that has an incorrect prototype for strchr in it. Their prototype is:
char *strchr(char *,int c);
when of course we know it should be:
char *strch... | You should be able to set up a configure test that attempts to call the const char* version (NOT using a literal since there's an implicit conversion to char*). Configure will tell you if it compiled or not so you can #define something based on that and use it to make a decision in your code (preferably in some sort of... |
4,045,947 | 4,501,781 | Class Members Over Exports | When Using DLLs or Code-injecting to be Specific
this is an example class only intended for explaining
class test
{
int newint1;
char newchararray[512];
void (*newfunction1)( int newarg1 );
int newfunction2( bool newarg1, char newarg2 )
{
return newint1;
}
} mynewclass1;
that covers m... | I suppose that you forget to add a public: (:)
mynewclass1 is a statically initialized to zero at load time (unless you are working on very old version of windows).
if you add a constructor to your class behavior will become unpredictable because it is quite difficult to know when the static is effectively initialized ... |
4,046,004 | 4,046,034 | How to fullscreen a QGLWidget? | I am new to OpenGL and Qt, and I am learning both simultaneously(3 days already:). I couple of years ago I did some exmerimenting with DirectX and I clearly remember that it was possible to make a full-screen window there. By full-screen I mean really full-screen, even without the top part where you have the close full... | showFullScreen()
Although I don't want to just say RTM - the Qt online documentation really is excellent.
|
4,046,093 | 4,046,124 | Deleting C++ pointers to an object | I thought that the delete command would free up memory I allocated. Can someone explain why it seems I still have the memory in use after delete?
class Test
{
public:
int time;
};
int main()
{
Test *e;
e = new Test;
e->time = 1;
cout << e->time << endl;
delete e;
e->time = 2;
cout <... | When you "delete" memory, you are basically returning the allocated memory back to the heap. This just means that the data structure used to organize heap memory is updated to indicate that the memory is now available to use. It is not cleared out or anything like that. You are accessing memory that still exists, but b... |
4,046,244 | 4,046,275 | Moving compressed strings between C++ and PHP with zlib | I'm working on a project where a Windows web server running PHP is communicating over a very slow connection with a back end Linux server running an application written in C++. Because the connection between the two machines is so slow, I'd like to compress the traffic moving between them.
I've gotten to where I can c... | Zlib's default compression level is 6 - you could try passing that as the second param on gzcompress for PHP.
string gzcompress ( string $data [, int $level = -1 ] )
From the ZLIB manual:
The compression level must be
Z_DEFAULT_COMPRESSION, or between 0
and 9: 1 gives best speed, 9 gives
best compression, 0 giv... |
4,046,265 | 4,046,277 | std::map with typedef type in it? | Is it a good idea to do the following in C++:
typedef std::map<std::string, boost::any> MyVals;
// Is the following typedef'd type inside a map a good idea?
typedef std::map<std::string, MyVals> TagValues;
These maps will be used a lot for sequential insertion and removal.
| There is nothing bad in typedefing a type commonly used in the code.
Typedefs exist only on syntactical level, they won't make any changes in the produced code. Moreover, a well chosen name will make readability better.
Just compare
std::map<std::string, std::map<std::string, boost::any>::const_iterator it =
t... |
4,046,312 | 4,046,472 | Float increments precision problems with UI | Here is my problem, I have several parameters that I need to increment by 0.1.
But my UI only renders x.x , x.xx, x.xxx for floats so since 0.1f is not really 0.1 but something like 0.10000000149011612 on the long run my ui will render -0.00 and that doesn't make much sense. How to prevent that for all the possible ca... | If you know that your floating point value will always be a multiple of 0.1, you can round it after every increment to make sure it maintains a sensible value. It still won't be exact (because it physically can't be), but at least the errors won't accumulate and it will display properly.
Instead of:
x += delta;
Do:
x ... |
4,046,404 | 4,061,018 | Getting started with client-server networking | I'm a good programmer, but I have zero network experience.
Basically, I'd like to get into client-server networking. For example, I'd like to try getting a server process going which allows clients to connect over the internet and send pings to all of the other connected clients. Then maybe I'll try developing a simple... | I prefer Java. I'm going to explain TCP:
The basic concept is that you have to run a "Server" on a machine. That server accepts clients waiting for a connection. Each connection goes over a port (you know, I hope...).
Always use ports above 1024 because ports lower than 1025 are most of the time reserved for standard p... |
4,047,001 | 4,047,023 | Passing HRESULT as a string on command line | I have a need to pass in an HRESULT value to a program as a command line argument. I had intended to do so by passing the hex value, e.g.:
>receiver.exe 0x80048836
I'm trying to convert this string representation back into an HRESULT using wcstol, eg:
HRESULT hr = wcstol(argv[2], NULL, 16);
However, the value of the ... | Check out wcstoul. http://msdn.microsoft.com/en-us/library/5k9xb7x1(v=VS.80).aspx
The HRESULT does fit in 32 bits, but with the example you gave it uses the most significant bit, which is considered to act like a sign bit for signed integers. Using wcstoul will fit it into an unsigned long.
LONG_MAX is 0x7FFFFFFF, the ... |
4,047,161 | 4,047,180 | Call a non-const member function from a const member function | I would like to know if its possible to call a non-const member function from a const member function. In the example below First gives a compiler error. I understand why it gives an error, I would like to know if there is a way to work around it.
class Foo
{
const int& First() const
{
return Second();
... | return (const_cast<Foo*>(this))->Second();
Then cry, quietly.
|
4,047,229 | 4,047,274 | C++ program snippet: what is this doing? | I'm trying to figure out how to output hOCR using Tesseract. Documentation is limited, so I am looking into the code. I found this in the main() function:
bool output_hocr = tessedit_create_hocr;
outfile = argv[2];
outfile += output_hocr ? ".html" : tessedit_create_boxfile ? ".box" : ".txt";
A typical command for Tess... | It's generating the output filename.
bool output_hocr = tessedit_create_hocr;
Saves the tessedit_create_hocr flag in a locally scoped variable.
outfile = argv[2];
Initializes the outfile variable with the base filename from the command line. Something like "Scann0000.tif".
outfile += output_hocr ? ".html" : tessedit_... |
4,047,251 | 4,048,218 | What should I use in Android when porting C++ code written with libsndfile? | I'm porting a small (<10 classes) C++ project to Java. The project manipulates sound files, and in C++ does this using libsndfile. The code includes stuff like:
const int channels = audioFileInfo.channels;
...
sf_readf_double( audioFile, inputBuffer, MAX_ECHO );
...
sf_writef_double( outputAudioFile, ¤tAudioBuffe... | libsndfile can be compiled for Android using the Native Development Kit. Once you have the library compiled for Android, you should be able to use JNI to access it from Java.
|
4,047,295 | 4,047,458 | Pointers to objects in a set or in a vector - does it matter? | just came a across a situation where I needs to store heap-allocated pointers (to a class B) in an STL container. The class that owns the privately held container (class A) also creates the instances of B. Class A will be able to return a const pointers to B instances for clients of A.
Now, does it matter if these poi... | There's nothing wrong with storing pointers in a standard container - be it a vector, set, map, or whatever. You just have to be aware of who owns that memory and make sure that it's released appropriately. When choosing a container, choose the container that makes the most sense for your needs. vector is great for ran... |
4,047,418 | 4,051,363 | Interfere Win32 message loop with injected DLL code (SetWindowsHookEx) | Hello everybody!
After hours of penetrating Google I ended up here. I'll come straight to the point: I'm about to "refresh" my C/C++ skills and gain experience with the unmanaged world again. As a "basic" task I developed a little key logger (which are just a few lines with the Windows API) but now I want to extend it ... | Okay, first off, you're doing way too much in your dll entry point function. For one thing - and this is straight from MSDN - "There are serious limits on what you can do in a DLL entry point". Also, while in the dll entry point the loader lock is held so no other libraries can be loaded/unloaded. So seeing as you're ... |
4,047,487 | 4,048,198 | Assembly code mixed in with my C++ code. How to port to 64 bit | I am porting 32 bit C++ code into 64 bit in VS2008. The old code has mixed code written in assembly.
Example:
__asm
{
mov esi, pbSrc
mov edi, pbDest
...
}
I have read somewhere that I need to remove all assembly code and put them all in a separate project and somehow link to it. Can somebody give me the ste... | If you can't use intrinsic functions to perform your tasks, or cannot write the equivalent in C/c++, you're going to have to dive into x64 assembly language. From a high level:
1) Assuming that you're starting with x86 assembly language routines, you'll need to port them to x64.
2) Use ML64 (Microsoft x64 assembler)... |
4,047,652 | 4,049,966 | Gdiplusshutdown results in exit code 1 | when my app is exited i see the following in the debugger console.
The thread '_threadstartex' (0xd48) has exited with code 0 (0x0).
The thread '_threadstartex' (0xf80) has exited with code 0 (0x0).
The thread '_threadstartex' (0x190) has exited with code 0 (0x0).
The thread '_threadstartex' (0xaa0) has exited with co... | Short summary: Nothing to be concerned about.
The runtime library is just notifying you that threads are exiting. Whether or not its related to GDI+ is unproven (since its happening in your app shutdown sequence when lots of other things are getting killed). This type of debug spew is common to see in the visual st... |
4,047,684 | 4,047,694 | VC++ 10 complains that a lot of types are not defined, C99 | I'm trying to compile an open source project I downloaded which was apparently written in VC++ 7.1.
After a lot of trouble, being a novice at C++, I managed to download and fix includes for STLPort that the project uses. However, I get something like 15,000 errors complaining that certain types are not defined. A few o... | The Visual C++ compiler does not support most C99 features.
If you want to use the standard fixed-width integer types, you need to make sure you include <cstdint> and qualify them with std:: or include <stdint.h>.
The standard fixed-width unsigned type names are uint32_t, uint16_t, and uint8_t (that is, there is no _ b... |
4,047,710 | 4,049,679 | High Quality Image Magnification on GPU | I'm looking for interesting algorithms for image magnification that can be implemented on a gpu for real-time scaling of video. Linear and bicubic interpolations algorithms are not good enough.
Suggestions?
Here are some papers I've found, unsure about their suitability for gpu implementation.
Adaptive Interpolation
Le... | You may want to have a look at Super Resolution Algorithms. Starting Point on CiteseerX
|
4,047,742 | 4,047,764 | Is there anything you can do in C++ that you cannot do in C#? | I am trying to figure out if there is anything that you can do in c++ that you absolutely cannot do in c#?
I know that there are platforms that are targeted to native libraries, but I want to know if the lowest level c# can compare with the lowest level c++.
| Device drivers. These applications operate in kernel mode, and .NET apps don't (they run in user mode). Even if you could, would you really want to? Probably not considering the overhead of the runtime and the relative difficulty of interfacing directly to hardware devices.
In software you can pretty much do anythin... |
4,048,087 | 4,048,117 | Keeping a reference instead of a pointer? | I have a class which basically is a text manager. It can draw text and whatnot. I basically want the color and text std::string to only be a constant reference. Would it then be alright to do
class TextManager {
const std::string &text;
void draw(const std::string &text) const;
public:
TextManager(const std::string &te... | This code doesn't compile. this->text = text doesn't do what you think it does - it's not like Java where assigning a reference is like changing the pointer. reference = value will actually invoke the copy operator, so it will copy the value of the rhs to the lhs, either as member-by-member copy or using the operator= ... |
4,048,132 | 4,052,218 | Does wxwidgets use rosetta in Mac? | While deciding for a cross platform language for a desktop application I want to do, I came across "wxwidgets" for C++. After testing a demo application in Mac 10.6.4 I noticed the application needed "Rosetta" to run.
My concern is: Will I always need "Rosetta" for a C++ application with wxwidgets to run on a Mac?
Note... | You can create Universe Binaries with wxWidgets. My guess is that your demo application was only compiled for PPC. (Which seems weird, actually. Was the app you tried one you built yourself from examples/, or just one you downloaded off the web?).
I've built Universal apps in wxWidgets both in Xcode (the easiest way to... |
4,048,220 | 4,048,430 | has_member_of_type - template metaprogramming in C++ | I suspect this is not possible under the current C++ standards but I'll ask anyway.
What I'm trying to achieve is to get the compiler to figure out during compile time if a class contains any member variable of type Base (along with its derivations).
e.g.
struct Base
{
};
struct Derived : public Base
{
};
struct Foo
... | No, it's not possible. You can't even access the members (unless told their names), let alone probe their types.
|
4,048,231 | 4,048,337 | Your best library for create GUI ( gtk, qt, win32 api, etc )? | In your opinion, what is the best way to create gui in Windows ? with gtk or win32 api ?
Do you recommend GTK for windows ? Yes ? NO ? Why ?
| Let's see.
Win32 is very low-level, C based, and awkward to use.
MFC is considered obsolete.
C# (or C++) with .NET is probably your primary choice for Windows-specific development.
There are even semi-limited ways to port that code to other platforms (Mono).
Java is great for very platform-independent code that "jus... |
4,048,252 | 4,169,801 | Modern books on native C++ development | I was going through the Hilo tutorial series Developing C++ Applications for Windows 7; seemed pretty interesting.
What modern books that go into details of developing C++ based applications for Windows 7? It should show how to take advantage of Windows 7 features and based on "modern" C++ (templates, Unicode, etc.). N... | I'd recommend that you ensure you're familiar with the theory in winprog.org/tutorial, then Ivor Horton's book (below), and then finally check out the WTL library.
The examples on the ribbon code in the Hilo articles use the windows API, which relies on COM objects to create the ribbon. ATL constructs like the CComPtr... |
4,048,542 | 4,048,561 | Using Vertex Buffer Objects with C++ OpenGL | I am working on a 3d tile-based strategy game and have read that implementing VBO's will significantly increase the game's frame rate and reduce the cpu usage (sounds great right?). However, among the tutorials I've looked at I can't quite get a handle on how to implement it. Has anyone had experience doing this and ... | Are these suitable?
http://www.songho.ca/opengl/gl_vbo.html
http://www.opengl.org/wiki/Vertex_Buffer_Object
|
4,048,691 | 4,048,706 | Is it possible to overload a template class? | I found that template method could be overloaded, can I do the same on template classes? If 2 template classes match a template class instantiation, we can use the parameter type in the constructor to deduce which one to use.
template <typename T>
class A{
A(T){}
};
template <typename T>
class A{
A(T*){}
};
int ... | No. This is not allowed. Instead class template can be specialized (including partial specialization). This pretty much achieves the effect of overloading (which is only for functions)
Note that template parameters can not be deduced from constructor arguments.
template<class T> struct X{
void f(){}
};
template<cla... |
4,048,749 | 4,048,833 | bitwise operations on vector<bool> | what's the best way to perform bitwise operations on vector<bool>?
as i understand, vector<bool> is a specialisation that uses one bit per boolean. I chose vector<bool> for memory saving reasons. I know that there are some problems with vector<bool> but for my needs it's apropriate.
now - what's the most performant way... | If the number of bits are fixed at compile time, you would be much better off using std::bitset
If not, (i.e. number of bits varies at runtime), then you should see and can use boost::dynamic_bitset)
In both of these, it is extremely easy to do all the bitwise operations.
|
4,048,766 | 4,048,994 | How can I tell if the function's intrinsic version is used from the disassembly? | Im trying to optimize my exercise application in VS2010.
Basically I have several sqrt, pow and memset in the core loop.
More specifically, this is what I do:
// in a cpp file ...
#include <cmath>
#pragma intrinsic(sqrt, pow, memset)
void Simulator::calculate()
{
for( int i=0; i<NUM; i++ )
{
...
float len... | You are compiling to machine code and not to .NET CLR. Right?
If you compile to .NET then the code won't be optimized until it is run through JIT. At that point .NET has its own intrinsics and other things that will happen.
If you are compiling to native machine code, you might want to play with the /arch option and th... |
4,048,813 | 4,048,828 | Tool to find all instances of a class | I'm working on a C++ project where modules are meant to be combined in a small group to serve a specific purpose (in some sort of processing pipeline).
Sometimes it's hard to know the impact of any change, because we intuitively don't even know all the places where one of our module is being used.
I know I can do Searc... | However I might not be understand your question right, but I believe doxygen can do that: http://www.doxygen.nl/
You will be able to see how everything is being used and called from what. It will give you classes calling what other classes, a whole hierarchy of your code.
|
4,048,835 | 4,048,859 | Changing things from a vector | What is the easiest way to take something out of an vector and changes its values? This isn't working the way I expected.
for(int i = 0; i < list.size(); i++) {
someType s = list.at(i);
s.x = 10;
s.y = 20;
s.z = 30;
}
However, when I go to print out the x,y,z of that someType s, it doesn't give me what I expect. Sorr... | someType s = list.at(i);
You are making a copy of the element at index i. In C++, if you want a reference to something, you need to explicitly state that you want a reference:
someType& s = list.at(i);
// ^ I'm a reference
As it is written now, you only manipulate the copy that you make, not the object in the c... |
4,048,854 | 4,049,042 | What technologies can be used to call from a native process to a C# process? | I have a native (C++) process and a managed (C#) process on the same system. I want to enable communications between the two, similar to how one could use RPC between two native processes. I know I could use WCF using Microsoft's WWSAPI in the native process., but I was wondering what other options do I have? Or is ... | If you want to communicate between two processes, you have a wide range of options, as rerun said in his answer. To his list you can add shared memory (memory mapped files) and named synchronization objects like semaphores and events. I'm sure there are others.
If you want the C++ application to call functions in the... |
4,048,998 | 4,050,740 | How to set tooltip at runtime in MFC Treeview? | How to set tooltip at runtime in MFC Treeview ?
I am creating treeview like this :
m_pTreeview->Create(WS_CHILD | WS_VISIBLE | WS_TABSTOP |
TVS_SINGLEEXPAND,CRect(38, 82, 220 ,250), this, IDC_NDS_TREEVIEW);
Any help is appreciated..
| Here some code : -- In .H file
afx_msg void OnMyTreeGetInfoTip(NMHDR pNMHDR, LRESULT pResult);
In BEGIN MESSAGE MAP block add -
ON_NOTIFY_REFLECT (TVN_GETINFOTIP, OnMyTreeGetInfoTip)
And use handler
void CMyTreeView::OnMyTreeGetInfoTip(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMTVGETINFOTIP pGetInfoTip = (LPNMTVGET... |
4,049,076 | 11,726,189 | Who should construct objects in this scenario? | I have the following class:
class PluginLoader
{
public:
PluginLoader(Logger&, PluginFactory&, ConflictResolver&);
//Functions.
private:
//Members and functions
};
Logger, PluginFactory and ConflictResolver classes are all interface classes which will be implemented in the application. I create the single ... | From your question and your comments it looks like that you are confused with two seemingly conflicting design principles.
You should encapsulate as much as possible
You shouldn't hardwire the creation of the needed objects in your implementation.
In your case, you have done right(at least from the visible interfaces... |
4,049,098 | 4,049,296 | Simple C++ template definition problem | I'm new to C++. Here is the code:
template <class T> typename lw_slist {
// .... some code
private:
typedef struct _slist_cell {
_slist_cell *next;
T data;
} slist_cell;
lw_slist::slist_cell *root;
};
Give this compilation error:
error C4430: missing type ... | A whole new question, a whole new answer:
I think that you will want it like this:
template <class T>
class lw_slist {
// .... some code
private:
struct slist_cell {
slist_cell *next;
T data;
};
slist_cell *root;
};
There is no reason to use a typedef: C++ ... |
4,049,156 | 4,049,238 | 1 bit per bool in Array C++ | bool fp[81];
From my understanding fp should use ceil(81/8) bytes because it is in succession.
Am I correct?
How can I prove this?
| No, the sizeof your buffer is implementation defined. Refer the quote from the Standard below.
Therefore the size you can expect is 81 * X where X is the size of bool, which is implementation defined.
$5.3.3/1 - "The sizeof operator yields the number of bytes in the object representation of its operand. The operand is ... |
4,049,294 | 4,049,336 | Error: copy assignment operator not allowed in union | I am compiling the code below when the following erro comes up. I am unable to find the reason.
typedef union {
struct {
const int j;
} tag;
} X;
int main(){
return 0;
}
error: member `<`anonymous union>::`<`anonymous struct> `<`anonymous union>::tag with copy assignment operator not allowed in uni... | In order to have a member of a union of some class type T, T's special member functions (the default constructor, copy constructor, copy assignment operator, and destructor) must be trivial. That is, they must be the ones implicitly declared and defined by the compiler.
Your unnamed struct does not have a trivial copy... |
4,049,351 | 4,049,369 | What is the strategy if assertion fails | Assertion is used to check whether a condition is met(precondition, postcondition, invariants) and help programmers find holes during debugging phase.
For example,
void f(int *p)
{
assert(p);
p->do();
}
My question is do we need to assume the condition could not be met in release mode and handle the case according... | If the assertion fails, the program should crash.
An assertion failing means the programmer made a fundamental mistake in their understanding of how it is possible for the program flow to proceed. This is a development aid, not a production aid. In production, one might handle exceptions, as they "might" occur, whereas... |
4,049,433 | 4,049,467 | C++ Calling a EXE from a method | Hi i need to call a external EXE (same running exe )from a C++ method i used
system("filepath");
but in the current file closed and new exe doesn't create the new instance
How can i call a exe with absolute path ?
| Have a look at ShellExecute, it should do the work.
|
4,049,549 | 4,049,565 | C++ Number input validation | I need to validate a user input using getch() only to accept numeric input
`int input_put=getch();`
if(input >=0 && < 9){
}else{
}
| getch returns a character code. The character code for "0" is 48, not 0, although you can get away with using a character constant instead (since char constants are really integer constants) and that will be more readable. So:
if (input >= '0' && input <= '9')
If you're using Visual C++ (as your tags indicate), you ma... |
4,049,580 | 4,049,599 | What is the difference between type casting and type conversion in C++ or Java? | What is the difference between typecasting and typeconversion in C++ or Java ?
| Type casting is treating a value (block of memory) referenced by a variable as being of a different type than the type the variable is declared as.
Type conversion is actually performing a conversion of that value.
In many languages, some casts (usually numeric ones) do result in conversions (this will vary quite a bit... |
4,049,669 | 4,050,065 | Operating on a string before runtime | I have a string:
B<T>::B() [with T = int]
Is there any way I can get
B<T> [with T = int] from this before run time somehow? :)
Simplifying: Is there any way to get X & Y separately from a static string XY defined as a preprocessor macro in any form before runtime?
| In current C++ I cannot think on a way to split the string at compile time. Most of the template tricks will not work on string literals. Now, I imagine that you want this to use in some sort of logging mechanism and you want to avoid the impact of performing the split at runtime in each method invocation. If that is t... |
4,049,877 | 4,052,937 | How to save XImage as bitmap? |
i'm trying to create JNI C++ library that will capture desktop video (frames).
First step is to simply make a screenshot of desktop. Code is :
#include <iostream>
#include <X11/Xlib.h>
using namespace std;
int main()
{
Display *display;
int screen;
Window root;
display = XOpenDisplay(... | To do this you have to write a convert routine for all possible XImage formats, or at least all formats your users are likely to have.
See _get_image_surface() in cairo for example:
http://cgit.freedesktop.org/cairo/tree/src/cairo-xlib-surface.c#n727
If you can't use a third-party library you will have to reimplement... |
4,049,887 | 4,050,174 | C++ - overloading assignment operator for default types | I want to overload the assignment operator for types like "int", "long" etc. That is, I want to use code like:
class CX {
private:
int data;
...
};
CX obj;
int k;
k = obj; // k should get the value of obj.data
Apparently assignment operators cannot be friend functions. How do I achieve the above?
I maybe missing... | You cannot do this. operator=() has to be a member function and cannot be overloaded for int. I see these possibilities:
Rely on an implicit conversion operator in your class. I would advice against that. I cannot remember a single time I have done this where I have not regretted and removed it later.
Write an expli... |
4,049,958 | 4,057,782 | Embedded Software Defect Rate | What defect rate can I expect in a C++ codebase that is written for an embedded processor (DSP), given that there have been no unit tests, no code reviews, no static code analysis, and that compiling the project generates about 1500 warnings. Is 5 defects/100 lines of code a reasonable estimate?
| Despite my scepticism of the validity of any estimate in this case, I have found some statistics that may be relevant.
In this article, the author cites figures from a "a large body of empirical studies", published in Software Assessments, Benchmarks, and Best Practices (Jones, 2000). At SIE CMM Level 1, which sounds... |
4,049,962 | 4,049,988 | Can I squeeze my own program between the preprocessor and compiler? | Is this a stupid question, or can I specify g++ to use a program between the preprocessor and compiler?
Alternatively, I know that I can just run the preprocessor on a file (hence all the files). Then I am guessing there is a switch to run only the compiler. So I can manually invoke these two and put my program between... | To run an alternative preprocessor, the man page suggests using -no-integrated-cpp and -B.
I have no experience with these, so I suggest you read the relevant parts in the man page.
Alternatively, you can run the compiler without invoking the preprocessor by telling g++ that the language is "preprocessed C++":
g++ -x ... |
4,049,986 | 4,050,005 | How to output unsigned/signed char or <cstdint> types as integers with << in C++ | Background:
I have template stream operators (e.g. operator << (ostream &, std::vector <T>)) (that output container elements that may possibly be of some 8-bit integer type, (e.g. unsigned char, int_least8_t, et cetera).
Problem:
Default is that these types are output as char (ASCII).
I only used char (or wchar_t or wh... | One way that comes to mind is using type traits to define the output type for each type. You would have to declare that for every type by hand. The traits could be defined as a template struct that is specialized for every data-type that has a different output-type than the data-type itself:
template< T >
struct output... |
4,050,202 | 4,050,418 | Why default argument cannot be specified for an explicit template specialization? | The below code couldn't pass the compilation, what's the consideration for this compiler error?
template<class T> void f(T t) {};
template<> void f<char>(char c = 'a') {}
Error message: Default arguments are not allowed on an explicit specialization of a function template
| I think that the rationale behind this error is due to the fact that the default arguments in the function template apply to its specialization as well and you are not allowed to define the default argument more than once in C++.
Consider the following:
#include <iostream>
template<class T> void f(T t = 'a') {}
templ... |
4,050,229 | 4,050,365 | Help me translate the C++ code to Delphi | im having hardtime in memset and memcpy. can somebody trasnlate this for me, or suggestion on how this thing work?
do{
memset(szSpeechBuf, 0x0, sizeof(char)*QSIZE);
if((nBufIter+1)*QSIZE > nRawBufLen)
{
diff = nRawBufLen - (nBufIter)*QSIZE;
if(diff < 0)
{
printf("DetectSpeech() erro... |
memset fills a number of bytes with the specified value. In Delphi, we use FillChar for this. But if the value we want to fill with is zero, you can also use the ZeroMemory function.
memcpy copies a block of bytes from one location to another (in RAM). In Delphi, we use Move for this. You can also use CopyMemory (or t... |
4,050,429 | 4,050,466 | STL iterator: "dereferencing" iterator to a temporary. Is it possible? | I'm writing a 3D grid for my scientific software and I need to iterate through the nodes of the grid to get their coordinates. Instead of holding each node object in the container I'd rather like to just calculate the coordinates on the fly while iterating. The problem is that stl::iterator requires to return reference... | You could use a member variable to hold the grid point it is currently pointing to:
class spGridIterator {
public:
typedef forward_iterator_tag iterator_category;
typedef spVector3D value_type;
typedef int difference_type;
typedef spVector3D* pointer;
typedef const spVector3D* const_pointer;
typ... |
4,050,528 | 4,050,567 | How to define an object of a templated class type? | If I have this structure:
namespace A
{
template <Class T>
struct Point
{
Point<T>(T x_, T y_) : x(x_), y(y_) {}
Point<T>() : x(0), y(0) {}
T x;
T y;
}
}
How might I define an object from the Point struct?
I tried:
A::Point point;
but it does not work.
| i.e.:
A::Point<int> point;
A::Point<int> point(1,1);
but first fix errors (note case for 'class' and missing semicolons):
namespace A
{
template <class T>
struct Point
{
Point<T>(T x_, T y_) : x(x_), y(y_) {}
Point<T>() : x(0), y(0) {}
T x;
T y;
};
}
|
4,050,693 | 4,068,841 | Sqlite - inserting rows while reading them | Imagine I have 3 rows in a sqlite table.
While reading these 3 rows I also want to insert new rows depending on the values in these 3 rows.
I do a select on these rows and use sqlite3_step function to get each row.
The problem is that sqlite3_step loops through more than 3 times, I think because it also sees the newly ... | Basically, this is how I approach this problem.
I do the updates & deletes by traversing all the rows. But I do inserts only after I have finished traversing.
Thanks for all your help.
|
4,050,713 | 4,050,774 | complexity about going from beginning to end and back through a vector | I am trying to be familiar with the complexity evaluation of algorithms. In general I think that is a good/elegant practice, but in the specific I need it to express time complexity of my C++ code.
I have a small doubt. Suppose I have an algorithm that just reads data from the beginning of a std::vector until the end... | Big-O notation simply means:
f(n) = O( g(n) ) if and only if f(n) / g(n) does not grow to infinity as n increases
What you have to do is count the number of operations you're performing, which is f(n), and then find a function g(n) that increases at least as fast as f.
In your example of going one way and then back,... |
4,050,714 | 4,050,809 | how to dynamically add a QWidget based to QGraphicsScene? | I want to add a QWidget based class(composed by buttons and labels an so on...) to my QGraphicScene scene in a special position and respecting the graphic style of my scene.?
I am using QT 4.7.
| You may use QGraphicsScene::addWidget() to add your widget to the scene and use the returned QGraphicsProxyWidget * to reposition your widget with QGraphicsItem::setPos().
Alternatively, you may look into QGraphicsWidget class.
|
4,050,757 | 4,050,919 | How to get a password with a CLI program? | I am writing a Linux CLI program. I need to get a password from the user and, obviously, I don't want the password to be echoed to the console.
There are several solutions available here, but they are all for plain C.
C command-line password input
How to mask password in c?
Getting a password in C without using getpa... | Use any of the plain C solutions:
std::string pass (100); // size the string at your max password size (minus one)
func_to_get_pass(&pass[0], pass.size());
// function takes a char* and the max size to write (including a null char)
pass.resize(pass.find('\0'));
cout << "Your password is " << pass << ".\n"; // oops!... |
4,050,901 | 4,050,942 | Performance of dynamic_cast? | Before reading the question:
This question is not about how useful it is to use dynamic_cast. Its just about its performance.
I've recently developed a design where dynamic_cast is used a lot.
When discussing it with co-workers almost everyone says that dynamic_cast shouldn't be used because of its bad performance (the... | Firstly, you need to measure the performance over a lot more than just a few iterations, as your results will be dominated by the resolution of the timer. Try e.g. 1 million+, in order to build up a representative picture. Also, this result is meaningless unless you compare it against something, i.e. doing the equiva... |
4,051,311 | 4,051,475 | Is it better to take object argument or use member object? | I have a class which I can write like this:
class FileNameLoader
{
public:
virtual bool LoadFileNames(PluginLoader&) = 0;
virtual ~FileNameLoader(){}
};
Or this:
class FileNameLoader
{
public:
virtual bool LoadFileNames(PluginLoader&, Logger&) = 0;
virtual ~FileNameLoader(... | I don't see what extra advantage approach two has over one (even considering unit testing!), infact with two, you have to ensure that everywhere you call a particular method, a Logger is available to pass in - and that could make things complicated...
Once you construct an object with the logger, do you really see the ... |
4,051,728 | 4,051,984 | Unicode and std::string in C++ | If I write a random string to file in C++ consisting of some unicode characters, I am told by my text editor that I have not created a valid UTF-8 file.
// Code example
const std::string charset = "abcdefgàèíüŷÀ";
file << random_string(charset); // using std::fstream
What can I do to solve this? Do I have to do lots o... | random_string is likely to be the culprit; I wonder how it's implemented. If your string is indeed UTF-8-encoded and random_string looks like
std::string random_string(std::string const &charset)
{
const int N = 10;
std::string result(N);
for (int i=0; i<N; i++)
result[i] = charset[rand() % charset.... |
4,051,849 | 4,051,920 | FTP Server Implementation C++ | I have to implement a kind of FTP server in C++ for a school project. The goal is learn how the FTP works internally.
I'm a lil bit lost in how to start it. I know the FTP Protocol, but I still don't know what can I do to start coding.
Someone can point me a way to start? Some links, libs in C++, etc?
Remembering that ... | First off, read the relevant RFCs. Also record a few FTP sessions using something like Wireshark.From there you should get an idea of when messages are sent and what messages are received. You can the try duplicate the functionality to the point where it can do something useful. You will probably need to look at BSD so... |
4,051,974 | 4,052,037 | Determination of type in function template | I would like to ask you for an advice about function template. I have a function that adds some data into buffer. But I need also to add an information about data type into the buffer. The type of data is a following enum:
enum ParameterType
{
UINT,
FLOAT,
DOUBLE
};
And I need to create a function template fr... | template <typename T> struct identity { };
inline void appendType_(identity<double> ) { appendType(DOUBLE); }
inline void appendType_(identity<unsigned>) { appendType(UINT); }
inline void appendType_(identity<MyType> ) { appendType(MY_TYPE); }
Then use it like so:
template<class T>
void SomeBuffer::append( T pa... |
4,052,450 | 4,052,848 | c++ class with objective-c friend | I have an application thats a mix of c++ and objective-c.
Quite a lot of the c++ classes exist merely as facades to access the underlying objective-c object from the rest of the x++ application.
My problem is one of design: The objective-c class needs to call back into the c++ class via a set of methods I'd prefer to m... | If you must do that you can wrap your Obj-C class in a C++ object that is friended to CMyView.
You'd need another level of abstraction between the two classes you have already.
|
4,052,542 | 4,052,559 | GCC -m32 flag: /usr/bin/ld: skipping incompatible | On 64 bit host I am trying to build shared libraries with -m32 option. Is it possible for these libraries to be linked with regular 64 bit libraries?
I am doing something like this:
g++ -m32 -shared source.cpp -l 64_bit_library.so -o 32_bit_library.so
and getting error messages like this:
/usr/bin/ld: skipping incompa... | It's not possible to link 32 bit applications against 64 bit libraries and vice versa. The problem is that pointers and types in general can't be passed between them. Normally the workaround is to spawn a child process of the other size and use IPC to communicate with that process.
Think about it this way: If I have a ... |
4,052,594 | 4,054,017 | Incorrect key size when porting Crypto++ AES encryption to PHP's mcrypt | Earlier I managed to port some C++ CryptoPP Rijndael_128 CBC code to MCrypt PHP, but now I'm having problems with CFB mode. The C++ and PHP results do not match (well the first byte matches but this could be coincidence, everything else doesn't). With some diagnostics, it looks like PHP's mcrypt is not setting the key ... | It's been awhile, but I had some similar problems with mcrypt and openSSL using CFB a couple years ago. In the end, I discovered mcrypt used a different default feedback chain size than openssl in CFB mode. That is to say, I believe an openSSL AES128 in CFB used a block size and feedback size of 128 bits, while mcrypt... |
4,052,691 | 4,053,208 | Performing unbiased program/script performance comparison | I want to perform a comparison of multiple implementations of basically the same algorithm, written in Java, C++ and Python, the latter executed using Pypy, Jython and CPython on a Mac OS X 10.6.4 Macbook Pro with normal (non-SSD) HDD.
It's a "decode a stream of data from a file" type of algorithm, where the relevant m... | I would recommend that you simply run each program many times (like 20 or so) and take the lowest measurement of each set. This will make it so it is highly likely that the program will use the HD cache and other things like that. If they all do that, then it isn't biased.
|
4,052,706 | 4,052,738 | Pointer deferencing and manipulating objects which are being pointed to - equivalent constructs in Java | Hello
In C++ you can do the following:
int x = 5
cout << x;
// prints 5
int* px = &x;
(*px)++;
cout <<x;
// prints 6
Is there an equivalent construct in Java
| In order to do this, you have to create an object that contains an int. Then, you can pass around a reference to that object, and you can increment the int that's in that object. But there's no way that you can have another reference to the same int and increments in one will increment the other -- unless both cases ... |
4,052,721 | 4,052,769 | How to use a struct in std::map? | I have a complex struct i want to put as a key of the std::map to make a list of all unique objects fast:
union somecomplexstruct {
struct {
more_structs val1, val2;
even_more_structs val3, val4;
lots_of_more_structs val5;
};
unsigned int DATA[3];
};
typedef map<somecomplexstruct... | std::greater<> invokes operator>() to do its work, so you need to overload that if you want to use std::greater<>.
It should look like this:
inline bool operator>(const somecomplexstruct& lhs, const somecomplexstruct& rhs)
{
// implement your ordering here.
}
|
4,052,762 | 4,053,522 | OpenCV 2.1 with Qt Creator on Windows | I have OpenCV 2.1 and Qt (Creator) installed on Windows.
Using the OpenCV C API I can link, build and run apps in Qt using OpenCV.
However, the when using the OpenCV C++ API, I am getting linking problems.
This is probably due to C++ ABI problems, since I'm using the pre-built binaries (built with MSVC-2008) for Window... | You need to make sure that CMake will find the same MinGW that was used to compile Qt. If you downloaded the QtCreator bundle, you should have a mingw directory in Qt installation directory. Make sure that this directory is in your path and that the correct version of MinGW will be used (for example using the command "... |
4,052,816 | 4,052,877 | Suggestions to Optimize Blocking Queue implementation | T BlockingQueue<T>::pop( ) {
pthread_mutex_lock(&lock);
if (list.empty( )) {
pthread_cond_wait(&cond) ;
}
T temp = list.front( );
list.pop_front( );
pthread_mutex_unlock(&lock);
return temp;
}
The above is the pop operation as defined for a templatized conc... | The concurrency handling look pretty minimal. Your underlying container is the best candidate for perf tuning. Is this really a linked list? deque would be better if you are doing FIFO ops only.
EDIT: see also sample code from Anthony Williams (who wrote current Boost.Thread) here, for tips and detailed discussion.
|
4,052,830 | 4,053,080 | Creating a spanning tree using BGL | I have a BGL graph and want to create a spanning tree using BGL.
Starting from a specified vertex, I want to add the shortest edge to my graph which connects with this vertex. From there on, I want to always pick the shortest edge which connects with the graph which exists thus far.
So, I want to add the constraint tha... | It sounds like you are growing a tree, starting with your specified vertex, by adding the lightest edge that connects a vertex in your tree to a vertex that's not in your tree. If that's the case, you are implementing Prim's algorithm, which does give you an MST. It's nicely described in the MST chapter of "Algorithms... |
4,052,990 | 4,062,198 | Saving map data in a 2d ORPG | I'm trying to figure out how I can best save the map data for a 2d ORPG engine I am developing, the file would contain tile data (Is it blocked, what actual graphics would it use, and various other properties).
I am currently using a binary format but I think this might be a bit too limited and hard to debug, what alte... | Personally, I would stick with a binary format. Whatever method you choose, it's going to be a pain in the ass to edit by hand anyway, so you may as well stick to binary which gives you a size and speed advantage.
You're also going to want a map editor anyway so that you do not have to edit it by hand.
|
4,053,084 | 4,053,096 | C++ & XML: parsing XML in C++ working in Ubuntu Environment | I am working on parsing a xml file with C++ in Eclipse running under Linux Ubuntu.
Is there any free library for this?
Or any resource that I could start with?
Thanks in advance!
| I use http://www.grinninglizard.com/tinyxml/ for my XML work in C++. It is small, fast, and drops directly in to your project.
|
4,053,432 | 4,053,549 | error C2872: 'range_error' : ambiguous symbol | I have already searched SO and google, I am not declaring the same variable in two places nor am I including something in a weird way..that I know of. The insert method should be working fine, it's a pre-written method(i guess that could be wrong too.. lol). This is the error I get.
Error:
error C2872: 'range_error' :... | range_error is defined both in your code (in the global namespace) and by the Standard Library (in the std namespace). Your use of using namespace std; to drag the entire Standard namespace into the global namespace creates an ambiguity. You should do at least one of the following:
remove using namespace std from the ... |
4,053,436 | 4,053,905 | Is it possible to iterate an mpl::vector at run time without instantiating the types in the vector? | Generally, I would use boost::mpl::for_each<>() to traverse a boost::mpl::vector, but this requires a functor with a template function declared like the following:
template<typename T> void operator()(T&){T::staticCall();}
My problem with this is that I don't want the object T to be instantiated by for_each<>. I don't ... | Interesting question! As far as I can tell, Boost.MPL does not seem to provide such an algorithm. However, writing your own should not be too difficult using iterators.
Here is a possible solution:
#include <boost/mpl/begin_end.hpp>
#include <boost/mpl/next_prior.hpp>
#include <boost/mpl/vector.hpp>
using namespace bo... |
4,053,473 | 4,053,561 | Not repeating types used as template parameters | Given the code below is there a nicer way to right it that doesn't repeat typename std::iterator_traits<T>::iterator_category twice?
template<class T, class T2>
struct foo :
bar<
foo<T, T2>, typename
std::conditional<
std::is_same<typename
std::iterator_traits<T>::itera... | Split it up (like it should be anyway):
// put in detail namespace/file or something in real code
template<class T, class T2>
struct foo_base
{
typedef foo<T, T2> foo_type;
typedef typename std::iterator_traits<T>::iterator_category category_type;
static const bool random_access = std::is_same<category_typ... |
4,053,552 | 4,053,718 | Question regarding const qualifier and constructor | Here is simple program.
If I comment constructor, I get an error
Just wanted to check what is the reason for this?
t.cc: In function 'int main(int, char**)':
t.cc:26: error: uninitialized const ... | According to the ISO standard (8.5 [dcl.init] paragraph 9):
If no initializer is specified for an object, and the object is of
(possibly cv-qualified) non-POD class type (or array thereof), the
object shall be default-initialized; if the object is of
const-qualified type, the underlying class type shall have a... |
4,053,554 | 4,053,682 | Running a C++ Console Program in full screen | How to run a C++ Console Program in full screen ? , using VS2008
| Just tested this with cl fullscreen.cpp :
#include <iostream>
#include <windows.h>
#pragma comment(lib, "user32")
int main()
{
::SendMessage(::GetConsoleWindow(), WM_SYSKEYDOWN, VK_RETURN, 0x20000000);
std::cout << "Hello world from full screen app!" << std::endl;
std::cin.get();
}
Unfortunatelly it ha... |
4,053,837 | 4,053,879 | Colorizing text in the console with C++ | How can I write colored text to the console with C++? That is, how can I write different text with different colors?
| Add a little Color to your Console Text
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
// you can loop k higher to see more color choices
for(int k = 1; k < 255; k++)
{
// pick the colorattribute k you want
SetConsoleTextAttribute(hConsole, k);
cout << k << " I want to be nice today!" << endl;
... |
4,053,918 | 4,054,138 | How to portably write std::wstring to file? | I have a wstring declared as such:
// random wstring
std::wstring str = L"abcàdëefŸg€hhhhhhhµa";
The literal would be UTF-8 encoded, because my source file is.
[EDIT: According to Mark Ransom this is not necessarily the case, the compiler will decide what encoding to use - let us instead assume that I read this string... | Why not write the file as a binary. Just use ofstream with the std::ios::binary setting. The editor should be able to interpret it then. Don't forget the Unicode flag 0xFEFF at the beginning.
You might be better of writing with a library, try one of these:
http://www.codeproject.com/KB/files/EZUTF.aspx
http://www.gnu.... |
4,054,000 | 4,054,777 | Passing only an element of a std::vector property to a BGL algorithm | I have a graph with multiple edge weightings stored as
namespace boost {
enum edge_weightvector_t {
edge_weightvector = 1337
};
BOOST_INSTALL_PROPERTY(edge, weightvector);
}
typedef boost::adjacency_list<
boost::vecS,
boost::vecS,
boost::undirectedS,
boost::no_property,
boost::... | I've did it now by first copying the desired weightings to an additional property, then running the algorithm and copying back afterwards. It is ugly, but it does the trick in my case.
|
4,054,014 | 4,054,384 | Call to VB's CreateObject method in C++ | I'm trying to call Visual Basic's CreateObject method from my C++ code. In VB, I'd simply type:
Dim obj As Object
obj = CreateObject("WScript.Network")
And that returns me the object from which I can call more methods. But how can I do that in C++? I'm following the MSDN documentation in http://msdn.microsoft.com/en-us... | First, you probably want to use CoCreateInstance http://msdn.microsoft.com/en-us/library/ms686615%28VS.85%29.aspx, or the equivalent call inside a smart pointer wrapper (eg: CComPtr<>, _com_ptr<>, etc.).
Second, to your specific question, the IID is the interface ID, the CLSID is the class ID. COM objects can have mult... |
4,054,100 | 4,054,249 | How to efficiently structure a terminal application with multiple menus? | I'm writing a console based program for my coursework, and am wondering how best to structure it so that it is both stable and efficient. I currently have
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int choice;
do
{
cout << "\E[H\E[2J" // Clear the console
... | Another possible approach is to make a class defined as a list of (menu_option, function) pairs and the know-how to turn them into menus. Then the function can be a call to another class instance's menu or it can do some operation on your database. That lets you keep your data organized away from the business "how to d... |
4,054,136 | 4,056,938 | User-defined literals (Extended literals) of C++11... which compilers support it? | In another thread I introduced some techniques we would use for Model-Driven-Development in C++ once C++11 features, in particular user-defined literals, are available. I just revised the plans for GCC 4.5 and even 4.6 and it shows that this particular feature is not supported.
Anyway, do you know if I even have any co... | Not yet, although patches for both Clang and GCC have been submitted and rejected for reworking, so you should see something soon.
|
4,054,163 | 4,054,185 | Desktop application DB | I my quest to develop a cross platform application I have decided to use C++ with the wxWidgets for the programing language. Now I am facing a dilemma on what local storage solution should I use for a for this application. Any suggestions?
Note: I am thinking of using SQLite, but I plan to store images in the DB and I ... | You can store images as binary blobs in SQLite.
|
4,054,206 | 4,054,252 | better way to do this? | I'm doing something that seems like it could be improved, but I don't have sufficient skill to improve it. Can you help?
Given:
vector<Base*> stuff;
const vector<MetaData>& metaDataContainer = Config.getMetaData();
for(vector<MetaData>::const_iterator i = metaDataContainer.begin(), end = metaDataContainer.end(); i != ... | Not really. However, you can abstract away much of the boilerplate with a factory type and use boost::ptr_vector or a container of smart pointers to manage the resources in a smart way. (See comments about the choice between smart container vs dumb container of smart pointers.)
|
4,054,350 | 4,054,468 | Why does the socket accept function not release after closesock called? | I have a server application that opens a socket and listen for a connection. In the application, I have a separate thread that creates a socket, binds it and calls the listen and accept functions on it.
When the application closes I call closesocket on the socket that was created, then wait for the socket thread to ... | Don't call accept unless select says it's OK. In that case accept will never block.
|
4,054,357 | 4,054,413 | Multiple redefinition error | After learning more about classes and pointers, I refactored a program I had and wiped out > 200 lines of code, in the process creating two other classes, Location and Piece. The problem is, after getting everything to compile, the linker complains that the constructor for Piece is defined multiple times, with a load o... |
Rebuild everything
Look for Piece::Piece, and remove all such from header files
2b. Never #include .cpp files
Look for #define that resolves to Piece
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.