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 |
|---|---|---|---|---|
1,653,958 | 1,653,965 | Why are #ifndef and #define used in C++ header files? | I have been seeing code like this usually in the start of header files:
#ifndef HEADERFILE_H
#define HEADERFILE_H
And at the end of the file is
#endif
What is the purpose of this?
| Those are called #include guards.
Once the header is included, it checks if a unique value (in this case HEADERFILE_H) is defined. Then if it's not defined, it defines it and continues to the rest of the page.
When the code is included again, the first ifndef fails, resulting in a blank file.
That prevents double decla... |
1,654,143 | 1,654,165 | Why might using a "long long" in C or C++ be a bad thing? | Why might using a "long long" in C or C++ be a bad thing?
I was compiling a runtime library the other day and in the code it checks to see if longs are 64bits and if not it uses a long long. But along with that, it sends out a #warning "using long long". I can't think of any reason for the "long long" being a warning u... | As far as I know, long long is currently standard only in C99. It will also be a type in C++0x, but most modern compilers should support it already.
However, for fixed-sized integers one might use the C99 header <stdint.h>, or in C++ <boost/cstdint.hpp>
|
1,654,149 | 1,654,182 | Static data on iphone c++ | I have data for countries which include Name, Population, Area etc for countries...
What is the best way to store them, I was thinking of static arrays in header files ...?
I am using c++ primarily for some game on iPhone
Should I consider other options like sqlite, plists, dictionaries ....?
| It depends. If the data is never going to change then static arrays in header files is probably a good enough solution. The problem is that if one day you do want to make a change to the data, you'll have to recompile your application, which might not be a concern for you. But it might also be a complete hassle, esp... |
1,654,150 | 1,654,187 | Scope of exception object in C++ | What is the scope of the exception object in C++? does it go out of scope as soon as catch handler is executed? Also, if I create an unnamed exception object and throw it, then while catching that exception does it matter if I catch it by const reference or a non-const reference?
| When a throw expression is evaluated, an exception object is initialized from the value of the expression. The exception object which is thrown gets its type from the static type of the throw expression ignoring any const and volatile qualifiers. For class types this means that copy-initialization is performed.
The exc... |
1,654,159 | 1,654,172 | How to prevent compiler doing implicit typecasting in for the class constructor argument? | #include <iostream>
using namespace std;
struct testarray{
int element;
public:
testarray(int a):element(a){}
};
class myarray
{
public:
testarray i;
public:
myarray(testarray a) : i(a){ }
} ;
int main()
{
myarray objArray[3] = {1,2,3};
return 0;
}
The above code compiles f... | You can use explicit keyword for your struct constructor.
|
1,654,381 | 1,882,767 | How can I add a wxIcon to my frame app? | I've looked all over the net and can't seem to find a standard way of including a wxIcon in my wxWidgets app that actually works! I've tried converting the icon to an XPM and including that I've also tried loading the bitmap but whatever I do it seems to compile but the icon never appears!
| If you are trying this on Windows make sure the icon is 32x32 pixels. All other sizes weren't being rendered at all...
|
1,654,444 | 1,654,455 | Why is there a class keyword in C++? | This question came to my mind when I learned C++ with a background of C. Even if there was a struct why did Stroustrup felt it was necessary to introduce the class keyword? I tried asking people at that time but couldn't get a satisfactory answer. So can the Stack Overflow community answer it?
| As David says, structs are public by default, classes are private by default. The larger point is that adding object orientation to C was a big change, and giving developers ways to express themselves accurately is an important part of designing a language.
As it turns out, the distinction between struct and class is... |
1,655,089 | 1,655,378 | CMake RequireAdministrator | I'm trying to set the RequireAdministrator manifest flag on an executable I'm building with CMake and Visual Studio.
Any ideas on how to direct CMake to set that option?
Thanks!
Billy3
| try this:
SET_TARGET_PROPERTIES(your_executable PROPERTIES LINK_FLAGS "/MANIFESTUAC:\"level='requireAdministrator' uiAccess='false'\" /SUBSYSTEM:WINDOWS")
|
1,655,096 | 1,655,160 | C++ class, its base class and circular include includes | FILE #1 (foo.h):
#ifndef FOO_H_
#define FOO_H_
#include "baseclass.h"
#include "bar.h"
class Bar;
class Foo : public baseclass {
public:
bar *varBar;
};
#endif
FILE #2 (bar.h):
#ifndef BAR_H_
#define BAR_H_
#include "foo.h"
class Foo;
class Bar {
public:
Foo *varFoo;
};
#endif
FILE #3 (baseclass.h):
#ifndef BASECLASS... | What you seem to have posted is to have a Bar member in the Foo, and a Foo member in the Bar. That is a circular dependency you need to break - if every Foo contains a Bar which contains a Foo then constructing either never terminates.
class Foo : public baseclass {
public:
Bar varBar;
};
class Bar {
... |
1,655,242 | 1,655,288 | LPD3DXFONT DrawText using DT_CALCRECT? | How do I use DT_CALCRECT to determine my rectangle bottom and right coords?
e.g I have this rect:
RECT textPos;
textPos.left = 100;
textPos.right = 100;
What do I do next to calculate the rect and draw the text?
| Mmm you just make a call to DrawText with the DT_CALCRECT parameter set, and the pointer to your original rectangle. It will modify the rectangle, extending the bottom and right values. Then you make another call to DrawText with your updated rectangle and whatever DT_ parameter needed.
http://msdn.microsoft.com/en-us/... |
1,655,466 | 1,655,494 | Can you tell iostreams which characters to treat as whitespace? | So that you could do something like this, for instance:
std::string a("01:22:42.18");
std::stringstream ss(a);
int h, m, s, f;
ss >> h >> m >> s >> f;
Which normally requires the string to be formatted "01 22 42 18".
Can you modify the current locale directly to do this?
| Take a look at scanf and fscanf. You might* be able to do something like this:
int h, m, s, f;
sscanf(a.c_str(), "%d:%d:%d.%d", &h, &m, &s, &f);
* Caveat: It's been a while for me and C++
|
1,655,501 | 1,655,534 | Shifting elements in array C++ | Im wondering why my data in 'intFront' does not stay the same. Im shifting the elements in my array left:
void stack::rotate(int nRotations)
{
for (; nRotations > 0 ;) // Number of Rotations to the left
{
intFront = &items[top+1].n;
for ( int shiftL = 0; shiftL < count-1; shiftL++ )
{
... |
You overrun your array: read of items[shiftL+1] goes beyond array bounds at last iteration,
You save a pointer to member of a structure into intFront and then override these structures by value in the inner loop - that'll sure change value intFront points to,
There's no need for doing multiple copies, i.e. no need for... |
1,655,650 | 1,655,660 | Linux optimistic malloc: will new always throw when out of memory? | I have been reading about out of memory conditions on Linux, and the following paragraph from the man pages got me thinking:
By default, Linux follows an optimistic memory allocation strategy. This means that when malloc() returns non-NULL there is no guarantee that the memory really is available. This is a really bad... | It depends; you can configure the kernel's overcommit settings using vm.overcommit_memory.
Herb Sutter discussed a few years ago how this behavior is actually nonconforming to the C++ standard:
"On some operating systems, including specifically Linux, memory allocation always succeeds. Full stop. How can allocation al... |
1,655,904 | 1,655,938 | convert pointer string to integer | I am trying to convert treePtr->item.getInvest() which contains a string to an integer. Is this possible?
| #include <sstream>
// ...
string str(*(treePtr->item.getInvest())); // assuming getInvest() returns ptr
istringstream ss(str);
int the_number;
ss >> the_number;
|
1,655,912 | 1,655,919 | problem passing in istream argument to a class constructor | I have the following code in my header file:
class Factovisors {
public:
Factovisors(std::istream& strm):strm_(strm)
{
}
void run()
{
unsigned int n,m;
while (!strm_.eof()) {
strm_ >> n >> m;
if (isFact(n,m))
... | The problem is that istream is an "interface". It has pure virtual functions, so it doesn't make sense to have a copy of it. What you might do is to keep a reference to the passed stream:
std::istream& strm_;
strm_ could be ifstream or istringstream or any input stream derived from istream.
|
1,655,960 | 1,655,975 | What are the most surprising elements of the C++ standard? | I've decided to get more acquainted with my favorite programming language, but only reading the standard is boring.
What are the most surprising, counter-intuitive, or just plain weird elements of C++? What has shocked you enough that you ran to your nearest compiler to check if it's really true?
I'll accept the first ... | The order of several declarators is actually unordered:
volatile long int const long extern unsigned x;
is the same as
extern const volatile unsigned long long int x;
|
1,655,996 | 1,656,003 | Variables as a parameters for templates in C++ | I'm trying to start learning C++ and I have a problem.
I'm trying to create a function template,
template<multimap<string, double> arr>
void calculate(string key) {
}
and use it like this:
multimap<string, double> arr;
vector<string> keys;
// ...
for_each(keys.begin(), keys.end(), calculate<arr>);
But i doesnt'compli... | I don't know what you're trying to do, but templates are parameterized by type. An ordinary function or a function object should do what you want.
So let's make your function look like this:
void calculate(const string &key, multimap<string, double>& myMap)
{
// do something...
}
now we can use the STL's binders ... |
1,656,140 | 1,656,191 | Logic of iterating through a list. Element "flickering" | [SOLVED]: Applying proper list iteration procedure fixed problem. (Shown below)
I currently have a program in which elements of a list are iterated through and erased if they meet certain conditions. Due to the nature of the program, this can be visually seen.
Objects on screen that are being iterated through sometimes... | In both loops, when you erase an element, you assign the return value of erase to the loop iterator. According to cplusplus.com, list::erase returns the element after the erased element. So that code will always skip a bullet or a block when an erase happens if I'm not mistaken. Could that have anything to do with it?
|
1,656,329 | 1,656,336 | Pointer to shift array C++ | Im trying to shift my array left as efficiently as possible. Im using pointers now, and im having trouble assigning the values back into my array:
void stack::rotate(int nRotations)
{
if ( count <= 1 ) return;
int *intFrontPtr = &items[top+1].n;
int *intBackPtr = &items[count-1].n;
int temp = 0;
for (... | c++ has a function built in in <algorithm>. Just call std::rotate(front_ptr, front_ptr + N, back_ptr);
|
1,656,790 | 1,656,838 | How do I destroy a Window correctly? | I'm programming a little game, and I set the lpfnWndProc to DefWindowProc
and after that, I made a loop in that way:
MSG lastMessage;
while (true)
{
if (PeekMessage(
&lastMessage,
this->getWindow(),
0, 0,
PM_REMOVE))
{
TranslateMessage(&lastMessage);
DispatchMessage(&lastMessage);
}
}
... | First of all, this is not how you write a message loop: it will take 100% CPU while waiting for messages, and won't remove messages for other windows from the queue. It will also never terminate. See here for an example of a message loop.
About closing windows: DefWindowProc will handle WM_CLOSE automatically and destr... |
1,657,225 | 1,699,225 | Experiences with Adobe's "Adam and Eve" C++ GUI library? | I tried out the demo application which was pretty impressive. However building it and integrating it with my own code is hard because it's such a large project.
Has anyone successfully used it for their own projects? Was is difficult to build and integrate with your own C++ code?
Link: STLab.
For the interested: there... | ASL is used fairly heavily within Adobe. The layout library (Eve) is used in many Adobe products and variants of it have been in use since Photoshop 5. The property model library (Adam) got a little use in CS4 and will likely be used more in future products. I can no longer speak with certainty because I left Adobe a f... |
1,657,364 | 1,657,373 | Cant track down access violation 0xC00000FD | Im using VS2008 and My MFC application has started to crash when setting breakpoints or running to cursor. I get lots of errors like this:-
First-chance exception at 0x78a5727c (mfc90ud.dll) in MyApp.exe: 0xC0000005: Access violation reading location 0xfffffffc.
First-chance exception at 0x00000000 in MyApp.exe: 0xC00... | Where is the stack overflow from your question title? Access violations generally indicate an invalid pointer dereference.
Use your revision history to find the first version where things started going boom, then critically analyze all pointer stuff going on in and around the code modified in that revision.
|
1,657,484 | 1,657,518 | Can you give an example of stack overflow in C++? | Can you give an example of stack overflow in C++? Other than the recursive case:
void foo() { foo(); }
| The typical case that does not involve infinite recursion is declaring an automatic variable on the stack that is too large. For example:
int foo()
{
int array[1000000];
}
|
1,657,643 | 1,657,813 | How are C++-style comments handled in GCC 4.3.3 by default? | I'm using GCC 4.3.3 on Ubuntu 9.04 64-bit and was getting errors using C++-style comments in C code. When I say "by default" in the title, I mean simply invoking gcc test.c
According to the GCC 4.3.3 docs (here), this is supported...yet I got the errors anyway.
These errors went away with a simple -std=c99 addition to ... | By defualt GCC is using C89/90 standard with GCC extensions. Strictly speaking by default it is not adhering to any specific standard, since by default it will not issue any diagnostic messages in situations when such messages are required by the standard. You need to run gcc in -ansi -pedantic mode (possibly also -Wal... |
1,657,673 | 1,657,719 | "Trap" control-d and control-c | I have a console program and I want if the user press ctrl-z the program exits and if he press ctrl-c nothing happens. In Bash i'd put a trap, what I should use in C++?
| In Unix use signal() in <signal.h> to register a function to invoke upon receiving a signal.
For example:
#include <signal.h>
void leave(int sig);
// ...
{
signal(SIGINT,leave);
for(;;) getchar();
}
// Beware: calling library fn from signal handler isn't std-conforming
// and may not work.
void lea... |
1,657,807 | 1,657,842 | Problems returning vector stack reference | I am working on an application that builds a vector of structs for items in a given directory and returns a reference of the vector for it to be read, I receive the following errors when attempting to compile the example code below:
1. 'class std::vector<indexStruct, std::allocator<indexStruct> >' has no member named '... | You've made 'indexItem' a vector, you probably just want it to be the type you want to put in 'indexItems'. Also, I'd create the new struct in your loop:
while (dirItem = readdir(dirPointer))
{
if (dirItem == NULL) throw 2;
if (dirItem->d_name[0] != '.')
{
indexStruct indexIt... |
1,657,830 | 1,658,249 | C++ template specialization via a base class | I want to be able to make the compiler shout when i call a constructor of foo with a class
that is NOT derived from _base*. The current code allows only for foo<_base*> itself. Any
easy solution ?
class _base
{
public:
// ...
};
class _derived: public _base
{
public:
// ...
};
template <typename T>
class foo... | Without Boost you can use something like the following to determine whether a pointer-to-type can be implicitly cast to another pointer-to-type:
template <class Derived, class Base>
struct IsConvertible
{
template <class T>
static char test(T*);
template <class T>
static double test(...);
static c... |
1,657,883 | 1,657,924 | Variable number of arguments in C++? | How can I write a function that accepts a variable number of arguments? Is this possible, how?
| You probably shouldn't, and you can probably do what you want to do in a safer and simpler way. Technically to use variable number of arguments in C you include stdarg.h. From that you'll get the va_list type as well as three functions that operate on it called va_start(), va_arg() and va_end().
#include<stdarg.h>
... |
1,657,988 | 1,657,992 | Resolving "'hi' is not recognized as internal or external command..." error using C++ with codeblocks on Windows Vista? | I am learning C++ in school now. Currently using C++ with codeblocks on my windows vista laptop. I noticed whenever I try to use functions from imported classes from the Clibrary I get an error in the console.
" 'hi' is not recgonized as internal or external command, operable command or batch file "
My code looks like ... | The error is exactly what it looks like: you're trying to execute with system a command that simply does not exist, so you'll get just the same error if you typed hi at a command prompt (codeblocks has nothing to do with it). Try using e.g. system("echo hi") or any other command that does exist and your results might ... |
1,658,061 | 1,658,074 | Organising project dependencies | I'm with a fairly large team and we are running into problem with the other libraries we depend on, and getting the same project files to work for every one.
The problem is that many people have more than one version of the same library (eg the project users boost 1.36, and I use boost 1.39 for some of my other stuff),... | You can use property sheets to help manage dependencies and other common project settings. Property sheets also allow you to define user-defined macros, which is what you need to do to define your own macros like MYSQL_HOME
|
1,658,469 | 1,658,582 | How do I configure indentation in vim in a specific way? | If I type the following
void main(int blah,
and then press enter, I want to continue here:
float blah);
How can I achieve this?
| :set cino=(0
For more about cinoption see here.
|
1,658,768 | 1,658,792 | Moving Qt UI code out to separate class | I'm just starting with Qt. Despite spending sometime on it this evening, I'm struggling to move my UI setup code out of main into it's own class.
#include <QtGui>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QWidget *window = new QWidget;
QLabel *hw = new QLabel(QObject::tr("Hello Wor... | Shouldn't you use a different name for the class and the instantiated variable?
QDialog *hWorld = new hWorld;
is quite confusing and the source of the error you get, use HWorld for the class instead (for example), since it is common use to start a type name with an upper case (upper camel casing).
Also, is the change ... |
1,658,821 | 1,658,831 | C++ operator[] syntax | Just a quick syntax question. I'm writing a map class (for school).
If I define the following operator overload:
template<typename Key, typename Val> class Map {...
Val* operator[](Key k);
What happens when a user writes:
Map<int,int> myMap;
map[10] = 3;
Doing something like that will only overwrite a temporary copy... | The way it works with std::map is that, if the key doesn't exist, the map class will insert a default value and then return an lvalue (an assignable reference to the value associated with the key), so it can be assigned a new value.
So, in the following code sample, assuming map is empty, this will insert 10 into the m... |
1,658,956 | 1,659,688 | C++ deque's iterator invalidated after push_front() | Just now, I'm reading Josuttis' STL book.
As far as I know -- c++ vector is a c-array that can be reallocated. So, I understand, why after push_back() all iterators and references can become invalid.
But my question is about std::deque. As I know it is array of large blocks (c-array of c-arrays). So push_front() insert... | I think that the reason iterators get invalidated but references not might be because of the possible deque implementation of an array of pointers to the deque's pages that store the elements. A reference to an element in a deque will refer directly to the element in a 'page'. However, an iterator into the deque might... |
1,658,991 | 1,659,009 | Understanding how the pointer referencing works | I am currently reading "Developer's Workshop to COM and ATL 3.0". Chapter 3 introduces GUIDs, referencing and comparisons. Pointers are painful. I could use some help in deciphering the REFGUID #define (see below) and how memcmp in IsEqualGUID works against the pointers.
Given:
typedef struct_GUID{ unsigned lo... | The REFGUID is constant ptr to a constant guid (ie neither can change).
Shoud the code not be?
BOOL IsEqualGUID(REFGUID rguid1, REFGUID rguid2)
{
return !memcmp(rguid1, rguid2, sizeof(GUID));
}
as memcmp takes:
int memcmp(const void *s1, const void *s2, size_t n);
The memcmp should be passed the... |
1,659,099 | 1,659,118 | Why is it preferable to write func( const Class &value )? | Why would one use func( const Class &value ) rather than just func( Class value )? Surely modern compilers will do the most efficient thing using either syntax. Is this still necessary or just a hold over from the days of non-optimizing compilers?
Just to add, gcc will produce similar assembler code output for eithe... | There are 2 large semantic differences between the 2 signatures.
The first is the use of & in the type name. This signals the value is passed by reference. Removing this causes the object to be passed by value which will essentially pass a copy of the object into the function (via the copy constructor). For operat... |
1,659,155 | 1,659,321 | I have a floating-point overflow problem | Well, I'm a beginner, it's my year as a computer science major. I'm trying to do
an exercise from my textbook that has me use a struct called MovieData that has
a constructor that allows me to initialize the member variables when the MovieData
struct is created. Here's what my code looks like:
#include <iostream>
#in... | Thanks for posting your complete code, the problem is now obvious. The following function is the problem:
MovieData(string t, string d, unsigned y, unsigned r, double p, double f)
{
title = t;
director = d;
year = y;
running_time = r;
}
You have omitted the following statements:
production_cost = p... |
1,659,159 | 1,659,176 | python executing existent (&big) c++ code | I have a program in C++ that uses the cryptopp library to decrypt/encrypt messages.
It offers two interface methods encrypt & decrypt that receive a string and operate on it through cryptopp methods.
Is there some way to use both methods in Python without manually wrapping all the cryptopp & files included?
Example:
im... | If you can make a DLL from that C++ code, exposing those two methods (ideally as "extern C", that makes all interfacing tasks so much simpler), ctypes can be the answer, not requiring any third party tool or extension. Otherwise, it's your choice between cython, good old SWIG, SIP, Boost, ... -- many, many such 3rd pa... |
1,659,302 | 1,659,308 | How does call by value and call by reference work in C? | In a C program, how does function call by value work, and how does call by reference work, and how do you return a value?
| Call by value
void foo(int c){
c=5; //5 is assigned to a copy of c
}
Call it like this:
int c=4;
foo(c);
//c is still 4 here.
Call by reference: pass a pointer. References exist in c++
void foo(int* c){
*c=5; //5 is assigned to c
}
Call it like this:
int c=0;
foo(&c);
//c is 5 here.
Return value
int foo(){... |
1,659,440 | 1,659,466 | 32-bit to 16-bit Floating Point Conversion | I need a cross-platform library/algorithm that will convert between 32-bit and 16-bit floating point numbers. I don't need to perform math with the 16-bit numbers; I just need to decrease the size of the 32-bit floats so they can be sent over the network. I am working in C++.
I understand how much precision I would b... | std::frexp extracts the significand and exponent from normal floats or doubles -- then you need to decide what to do with exponents that are too large to fit in a half-precision float (saturate...?), adjust accordingly, and put the half-precision number together. This article has C source code to show you how to perfo... |
1,659,547 | 1,659,599 | am trying to create class to encapsulate toolbar but the background turns black. c++ win32api | I created a simple class to hide the details of creating a toolbar in win32 API but I don't like the toolbars it is producing. (See image for clarification. I don't have reputation points so I have just posted a link)
http://i35.tinypic.com/1zmfeip.jpg
I have no idea now the black background is coming into my applicat... | Try modifying the flags parameter of ImageList_Create to include ILC_MASK as well
|
1,659,641 | 1,695,712 | Array PopFront Method C++ | Trying not to lose it here. As you can see below I have assigned intFrontPtr to point to the first cell in the array. And intBackPtr to point to the last cell in the array...:
bool quack::popFront(int& nPopFront)
{
nPopFront = items[top+1].n;
if ( count >= maxSize ) return false;
else
{
items... | I'm not entirely sure I understand what you're trying to do, but if I;m guessing right you're trying to 'pop' the 1st element of the array (items[0]) into the nPopFront int reference, then move all the subsequent elements of the array over by one so that the 1st element is replaced by the 2nd, the 2nd by the 3rd, and s... |
1,659,932 | 1,659,941 | "Expected constructor, destructor, or type conversion before '<' token" | I'm running into a syntax/parsing error, but I can't seem to locate it.
DataReader.h:11: error: expected constructor, destructor, or type conversion before '<' token
Here is DataReader.h:
#include <fstream>
#include <iostream>
#include <vector>
#ifndef DATA_H
#define DATA_H
#include "Data.h"
#endif
vector<Data*> Da... | In your header file, you need to explicitly use std::vector rather than just vector.
Also, I'm guessing that "Data.h" contains statements of the form:
#ifndef DATA_H
#define DATA_H
...
#endif
That's fine, but you should not use these include guards across #include "Data.h" as well, only within the file itself.
|
1,660,195 | 1,660,220 | C++ How to find the biggest key in a std::map? | At the moment my solution is to iterate through the map to solve this.
I see there is a upper_bound method which can make this loop faster, but is there a quicker or more succinct way?
| The end:
m.rbegin();
Maps (and sets) are sorted, so the first element is the smallest, and the last element is the largest. By default maps use std::less, but you can switch the comparer and this would of course change the position of the largest element. (For example, using std::greater would place it at begin().
Kee... |
1,660,281 | 1,660,306 | Stream and c++ - parsing file | I did it before... But I forgot.
I have a file with some data:
0.5 0.6 0.7
1.2 1.5
How can I read this in c++? I did it with stream... something like:
float var = 0;
stream >> var;
| Something like this?
std::ifstream stream("C:/a.txt");
float var = 0;
while(stream >> var)
{
//Do some processing
}
|
1,660,334 | 1,660,358 | How can I debug St9bad_alloc failures in gdb in C? | I have a program failing with:
terminate called after throwing an instance of 'std::bad_alloc'
what(): St9bad_alloc
I imagine it's something to do with malloc/free, but I don't know which one.
What breakpoint can I in gdb set that will break on the error so that I can view a stack trace?
The program is a combinatio... | It is not really malloc/free which causes the exception, it is "new" which is definitely in C++ part of your application. It looks like you are providing a parameter which is too big for "new" to allocate.
'std::bad_alloc' is caused by the following code for example:
int * p = new int[50000000];
What does backtrace s... |
1,660,352 | 1,660,425 | C++ Array initialization | the code below gives compilation error when I try to create test t[2];
because there is no default constructor for this.
But if I create Test t[2] = {test(1,2), test(2,3)}; Then it works fine.
1)But think of a situation, if we want to create more then 100 array element. We need to create 100 element in the curly brac... | In order to construct your 10 elements in the array the compiler somehow has to instaciate them through a constructor. For arrays only a default constructor (taking no arguments) can bes used, as you can not pass any arguments to the elements in the array. Therfor you have to proved a constructor
test::test()
taking n... |
1,660,492 | 17,189,385 | UTF-8 output on Windows console | The following code shows unexpected behaviour on my machine (tested with Visual C++ 2008 SP1 on Windows XP and VS 2012 on Windows 7):
#include <iostream>
#include "Windows.h"
int main() {
SetConsoleOutputCP( CP_UTF8 );
std::cout << "\xc3\xbc";
int fail = std::cout.fail() ? '1': '0';
fputc( fail, stdout... | It's time to close this now. Stephan T. Lavavej says the behaviour is "by design", although I cannot follow this explanation.
My current knowledge is: Windows XP console in UTF-8 codepage does not work with C++ iostreams.
Windows XP is getting out of fashion now and so does VS 2008. I'd be interested to hear if the pro... |
1,660,652 | 1,660,668 | What limits my use of the stack in terms of memory? | In windows (or any other OS for that matter) what determines how much stack I can use? The name of this very website makes me assume it's possible to run out of stack so should I avoid putting large amounts of data on the stack?
| It is language specific, Compiler specific and probably OS specific, but you should put large amount of data on the heap and not on the stack.
Other SO post about this
There are ways to change the stack size - but I wouldn't mess with it !
If you want to know your stack size using trial and error - just create an array... |
1,660,712 | 37,744,393 | Specification of source charset encoding in MSVC++, like gcc "-finput-charset=CharSet" | I want to create some sample programs that deal with encodings, specifically I want to use wide strings like:
wstring a=L"grüßen";
wstring b=L"שלום עולם!";
wstring c=L"中文";
Because these are example programs.
This is absolutely trivial with gcc that treats source code as UTF-8 encoded text.
But, straightforward compi... | For those who subscribe to the motto "better late than never", Visual Studio 2015 (version 19 of the compiler) now supports this.
The new /source-charset command line switch allows you to specify the character set encoding used to interpret source files. It takes a single parameter, which can be either the IANA or ISO ... |
1,660,765 | 1,661,401 | Joining a boost::thread instance in the destructor | I'm seeing an issue where a call to boost's thread->join in a destructor leads to a deadlock. I don't understand why, and I'm not too keen on keeping code that just works (and I don't understand why it does) in the project.
Class declaration (I've stripped the run() method of try/catch for brevity: according to the bo... | I've found the issue: it boils down to an over-zealous programmer.
I had originally compiled my project using DUMA (http://sourceforge.net/projects/duma/) to see if my implementation of the current module was leak-free. Unfortunately, my test sandbox also had the duma settings on, which I did not realize until I stepp... |
1,661,007 | 1,661,013 | not declared in this scope | I'm getting an error msg
DataReader.h:13: error: 'String' was not declared in this scope
DataReader.cpp:5: error: redefinition of 'std::vector<Data*, std::allocator<Data*> > DataReader'
DataReader.h:13: error: 'std::vector<Data*, std::allocator<Data*> > DataReader' previously declared here
DataReader.cpp:5: error: 'Str... | string should be lower case or std::string
|
1,661,062 | 1,661,067 | How do I declare a string without assigning a value in C++? | I know that for an integer, you can use:
int value;
I tried:
string str;
but Visual C++ gave me an error. How do I declare it without assigning a value, then using cin >> str later on to assign it?
| #include <string>
int main()
{
std::string str;
return 0;
}
Check this info on Namespaces by MSDN
|
1,661,131 | 1,661,167 | C++ university course | Do you know any university which has its C++ course available online? I'm looking for something similar to MIT-style online lectures (lecture notes, projects and examples, assignments, exams, solutions and video content).
This is what I've found on MIT, but id doesn't have video content.
| I don't know about C++ specifically, but in terms of video lectures on programming concepts, check out this:
http://academicearth.org/subjects/computer-science
|
1,661,154 | 1,661,207 | std::string in a multi-threaded program | Given that:
1) The C++03 standard does not address the existence of threads in any way
2) The C++03 standard leaves it up to implementations to decide whether std::string should use Copy-on-Write semantics in its copy-constructor
3) Copy-on-Write semantics often lead to unpredictable behavior in a multi-threaded progra... | Given that the standard doesn't say a word about memory models and is completely thread unaware, I'd say you can't definitely assume every implementation will be non-cow so no, you can't
Apart from that, if you know your tools, most of the implementations will use non-cow strings to allow multi-threading.
|
1,661,410 | 1,663,360 | How do I create a 64-bit native ATL C++ DLL in Visual Studio 2003? | I have a 32-bit ATL C++ in-proc COM server soultion. How do I port it to 64-bit Windows? I mean how do I make VC++7 emit 64-bit code? Is it possible with Visual Studio 2003?
| You need a 64bit compiler that will compile long to a 64bit long. The version which was shipped in VS2005 would do. Later versions of Visual C++ and Windows SDK have higher versions of the compiler. 64bit support is disabled in standard or lower versions of Visual C++ but not in the freely available Windows SDK. Other ... |
1,661,526 | 1,661,614 | Shorten nested namespace names | If you use nested namespaces, declarations in header files can get very long and unreadable.
//header1
namespace test { namespace test1 {
class Test {};
} } //namespace
In header2 of the program:
#include "header1"
namespace test2 {
class Test1 {
void test(test::test1::Test &test) {}
void test1(test::test1::Test... | Here is my favorite technique:
#include "header1"
namespace test2 {
class Test1 {
private:
typedef ::test::test1::Test MeaningfulName;
void test(MeaningfulName &test) {}
void test1(MeaningfulName &test) {}
void test2(MeaningfulName &test1, MeaningfulName &test2) {}
};
}
I make my typedef aliases private, ... |
1,661,529 | 1,661,564 | Is Meyers' implementation of the Singleton pattern thread safe? | Is the following implementation, using lazy initialization, of Singleton (Meyers' Singleton) thread safe?
static Singleton& instance()
{
static Singleton s;
return s;
}
If not, why and how to make it thread safe?
| In C++11, it is thread safe. According to the standard, §6.7 [stmt.dcl] p4:
If control enters
the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.
GCC and VS support for the feature (Dynamic Initialization and Destruction wit... |
1,661,556 | 1,666,190 | Use Eclipse's code completion for boost | I would like to profit from Eclipse's code completion for boost:shared_pointer in Eclipse 3.5 with CDT 6.0.
Eclipse doesn't offer any completion while I'm writing the following code:
#include <boost/shared_ptr.hpp>
#include "A.h"
typedef boost::shared_ptr<A> aPTR;
int main() {
aPTR test(new A);
test->ge...... | Eclipse CDT indexing of boost libraries starts struggling with version 1.37 (or even 1.36, couldn't verify that) already.
My workaround to benefit from code completion while using an up-to-date boost version (1.39) is the following one:
I have got two boost versions (1.35 and 1.39) on my computer.
In the Debug Build C... |
1,661,575 | 1,662,369 | How to associate non-member functions with a class in Doxygen? | I'm sure there's some way to do this with the \defgroup, \addgroup and \@{ \@} tags, but after a couple of hours of trial and (obviously) error, I'm asking SO.....
I have:
class C {
public:
void foo () const;
};
and I have some helper non-member functions that really are part of C's interface, but aren't in the cl... | \relates (or \memberof) seem to be what you are looking for.
|
1,661,795 | 1,664,324 | How to check if memory has aready been released in Destructor? | I have a simple tank wars style game using the allegro open source library. In my tank class, I initialize arrays of pointers to bitmap objects to 0. Then I create new objects with an allegro function create_bitmap which allocates the memory and initializes it.
Then I go about my business as usual.
The problem is, wh... | I think the problem is not that allegro releases the bitmaps itself (or otherwise you wouldn't need to release them at exit) but that allegro library has been deinitialized before the destructor is called.
int main()
{
ObjectManagingBitmaps o;
...
return 0;
//allegro automatically shut down here
} //o d... |
1,661,912 | 1,662,052 | Why does everybody use unanchored namespace declarations (i.e. std:: not ::std::)? | It seems to me that using unanchored namespaces is just asking for trouble later when someone puts in a new namespace that happens to have the same name as a root level namespace and mysteriously alters the meaning of a whole lot of programs. So, why do people always say std:: instead of ::std::. Do they really mean ... | The practical reason for unanchored namespaces is that one level of namespaces usually is enough. When it isn't, a second level is usually going to be used for implementation details. And finally, even when using multiple levels, they are still usually specified implicitly from root level. ie. even inside namespace ns1... |
1,661,982 | 1,662,403 | How do I get the full path for a filename command-line argument? | I've found lots of libraries to help with parsing command-line arguments, but none of them seem to deal with handling filenames. If I receive something like "../foo" on the command line, how do I figure out the full path to the file?
| POSIX has realpath().
#include <stdlib.h>
char *realpath(const char *filename, char *resolvedname);
DESCRIPTION
The realpath() function derives, from the pathname pointed to by filename, an absolute pathname that names the same file, whose resolution does not involve ".", "..", or symbolic links. The generated pathnam... |
1,662,107 | 1,662,116 | What's the difference between std::string and std::basic_string? And why are both needed? | What's the difference between std::string and std::basic_string? And why are both needed?
| std::basic_string is a class template for making strings out of character types, std::string is a typedef for a specialization of that class template for char.
|
1,662,430 | 1,662,503 | How can I force symbol a symbol reference in c++ (programmatically) | I'm trying to plug tcmalloc into a suite of software that we currently use at work. The software comprises of a lot of dll's. They all refer to a shared header file, so I can pragma link the library.
However as none of the code refers to the symbol __tcmalloc the optimizer strips the dll. Now I don't want to have to ed... | Ah, for anyone searching to the answer to this it's as follows
#pragma comment(linker, "/include:__tcmalloc")
|
1,662,624 | 1,662,644 | c++: ifstream open problem with passing a string for text file name | i'm trying to pass a string from main to another function. this string is a name of text file that needs to be oepened. as far as i can see, i am passing the string alright, but when i try to use ifstream.open(textFileName), it doesn't quite work. but when i manually hardcode it as ifstream.open("foo.txt"), it works ju... | the standard streams doesn't accept a standard string, only c-string! So pass the string using c_str():
aStream.open(textFile.c_str());
|
1,662,737 | 1,662,808 | initializing a const multidimensional array in c++ | I'm currently working through some exercises in a c++ book, which uses text based games as its teaching tool. The exercise I am stuck on involves getting the pc to select a word from a const array of words (strings), mixing the letters up and asking the player to guess the word. This was easy, but as a follow on the bo... | you could make 2d array?
string aArray[][2] = {{"wall", "brick..."},
{"glasses", "corrective eye tool thingymajig"},
{"calculator", "number cruncher"}};
not sure if the syntax is right but i hope you get the concept.
it's an array inside another array.
EDI... |
1,662,740 | 1,662,826 | Why is this boost::variant example not working? | I am getting to know boost::variant. I think this example should work.
#include <boost/fusion/sequence.hpp>
#include <boost/fusion/include/sequence.hpp>
#include <boost/variant/variant.hpp>
#include <string>
#include <vector>
#include <iostream>
#include <boost/variant/get.hpp>
boost::variant< bool,long,double,std::st... | v4[0] is not valid since v4 is a variant, not a vector. You need to use boost::get to retrieve the vector stored in it first. So, line 20 should be
boost::get<bool>(boost::get<std::vector<boost::variant<bool> > >(v4)[0]);
|
1,662,904 | 1,663,227 | Qt in a professional setting | While I have played with parts of Qt in the past I am thinking of putting some real effort into learning it but also wondering what the potential monetary payback might be down the road. So I have some general questions about Qt's future.
What is Qt's place in the job market? Are there many, or do you sense a growing... | They have been around since 1995, and recently some feared that Nokia would buy them to stifle the competition in favour of Symbian. Now that seems definitely out of the way by the way Qt will soon support Symbian and Maemo 5. Seeing the effort they spend in R&D and what their framework already provides on so many plat... |
1,662,905 | 1,663,245 | Using valid STATIC member function of class that can't be installed | I have following piece of code:
It compiles without problems under gcc-3.4, gcc-4.3, intel compiler, but fails under MSVC9.
MSVC tells "use of undefined type c_traits<C>, while compiling class template member function void foo<C>::go(void) with C=short.
The point it the compiler tries to install unused member function ... | Both compilers are right here; the behavior for your case is unspecified. ISO C++ 14.7.1[temp.inst]/9:
An implementation shall not implicitly instantiate a function template, a member template, a non-virtual member function, a member class or a static data member of a class template that does not require instantiation... |
1,663,094 | 1,663,520 | What are the differences between using array offsets vs pointer incrementation? | Given 2 functions, which should be faster, if there is any difference at all? Assume that the input data is very large
void iterate1(const char* pIn, int Size)
{
for ( int offset = 0; offset < Size; ++offset )
{
doSomething( pIn[offset] );
}
}
vs
void iterate2(const char* pIn, int Size)
{
const char... | Boojum is correct - IF your compiler has a good optimizer and you have it enabled. If that's not the case, or your use of arrays isn't sequential and liable to optimization, using array offsets can be far, far slower.
Here's an example. Back about 1988, we were implementing a window with a simple teletype interface on ... |
1,663,119 | 1,663,183 | Why is my merge sort not working? | It compiles fine, but when it runs, it adds random high numbers to the list, as well as duplicates of existing numbers. I've had a couple of people look over this, and none of them can figure it out.
void mergeSort(int list[], int length) {
recMergeSort(list, 0, length - 1);
}
void recMergeSort(int list[], int fir... | In function merge(), you're incorrectly calculating the index variable:
Assuming begin = 10, mid = 14, end = 19 (for a total array size of 0 .. 19, and you're recMergeSort()ing the higher half), your index = 10, but the tempList array is indexed 0..9 (because arraySize = last - first + 1 == 10).
So you're overflowing ... |
1,663,128 | 1,663,173 | Compiler warnings with MySQL++ with release configuration | For some reason I get some warnings about "non dll-interface class" when building with a release configuration, but not debug.
I've compared the release and debug configurations, and my ones with the MySQL++ example ones, however I cant see which setting is causing these warnings.
1>c:\sql\mysql 5.0\mysql++-3.0.9\lib\q... |
The obvious thing to me seems to be
that I'm not using a dll version of
the CRT, however since I am
("Multi-threaded DLL (/MD)" for
release) this cant be the problem, so
must be somewhere else...
1>c:\sql\mysql 5.0\mysql++-3.0.9\lib\qparms.h(49) : warning C4275: non dll-interface
class 'std::_Container_... |
1,663,157 | 1,663,198 | C++ referring to an object being constructed | In C++ I have a reference to an object that wants to point back to its owner, but I can't set the pointer during the containing class' construction because its not done constructing. So I'm trying to do something like this:
class A {
public:
A() : b(this) {}
private:
B b;
};
class B {
public:
... | Try this:
class A;
class B {
public:
B(A *_a) : a(_a) {};
private:
A* a;
};
class A {
public:
A() : b(this) {};
private:
B b;
};
Since B is contained completely in A, it must be declared first. It needs a pointer to A, so you have to forward-declare A before you declare B.
This code compiles under more-or... |
1,663,284 | 1,663,389 | Is boost::object_pool synchronized? | Is boost::object_pool synchronized?
| C++ doesn't specify anything about thread-safety, so if it isn't mentioned it likely doesn't deal with threading. Sometimes, Boost provides things that can be thread-safe out of the box, this is not one of them.
Wrap access to the pool in a mutex.
|
1,663,320 | 1,663,379 | Turning text into executable statements | This is a question out of curiousity for java or c++, I wanted to ask if it is possible to turn any text input into some executable statements?
For example say I have a text file with info like:
"class: Abc,
Param: 32"
Now say in C++ or Java I want to read that file and do something like:
new Abc(32);
How would I do ... | If your goal is to take any text input and run arbitrary commands, then the places to start looking on the JVM are the Java 6 compiler API (http://java.sun.com/javase/6/docs/api/javax/tools/package-summary.html) or JSR 223 (http://java.sun.com/developer/technicalArticles/J2SE/Desktop/scripting).
If your goal is storage... |
1,663,444 | 1,663,526 | Template specialization problem | I'm trying really hard to made this work, but I'm having no luck. I'm sure there is a work around, but I haven't run across it yet. Alright, let's see if I can describe the problem and the needs simply enough:
I have a RGB template class that can take typenames as one of its template parameters. It takes the typenam... | Perhaps I'm missing some bigger complication, but is there any reason why you can't just partially specialize the type_specification template?
Something like this:
template <int N, typename T, template <class> class Policy>
struct type_specification< fixed_pt_t<N, T, Policy> >
{
typedef fixed_pt_type type;
};
|
1,663,562 | 1,663,576 | Multi Including a .h File | In an .h file, I am declaring a global variable as:
#pragma data_seg(".shared")
#ifndef DEF_VARX
#define DEF_VARX
int VARX=0;
#endif /*DEF_VARX*/
#pragma data_seg()
#pragma comment(linker, "/SECTION:.shared,RWS")
However if I include this file in multiple cpp files, when I try to compile, I get " error LNK2005: "int V... | I think you're supposed to forward declare the variable in the .h and later define it in its shared section in a .cpp, something like:
// in a header file
#pragma once
extern int VARX;
// in a .cpp
#pragma data_seg(".shared")
int VARX=0;
#pragma data_seg()
#pragma comment(linker, "/SECTION:.shared,RWS")
|
1,663,655 | 1,665,821 | C++/Qt download file in sync | I want to achieve to download a file in a separate thread and store that file,
but I was not able to find an appropriate way to achieve this without evil delay (quite frequent download of small files, so signal+slots are too slow).
What I want to achieve:
(Pseudo Code)
request file;
wait for download finishing, timeout... | I needed something similar but for different reasons. Since QHttp and QNetworkAccessManager are both async what you could do is use a separate event loop, a full example based on QHttp can be found here. It shouldn't be too difficult to modify it for QNetworkAccessManager.
It's worth mentioning that your impression tha... |
1,663,864 | 1,663,981 | DLL Shared Data Section Does Not Exist Error | I try to declare a shared data segment in a DLL. I declare the area with:
#pragma data_seg(".shared")
int varx=0;
#pragma data_seg()
__declspec(allocate(".shared"))
// I found this declspec suggestion in another forum
#pragma comment (linker,"/section:.shared,RWS")
Also I add
SECTIONS
.shared READ WRITE... | Ive only seen that declspec used in this way:
__declspec(allocate(".shared")) int varx=0;
I would try writting only this:
#pragma comment (linker,"/section:.shared,RWS")
__declspec(allocate(".shared")) int varx=0;
avoiding declaring an empty section or a multiply defined one
|
1,663,949 | 1,664,052 | How do I get all permutations of xPy? | I'd like to calculate all the permutations of size Y of a set of size X. That is if I had (1,2,3) and want all permutations of size 2, 3P2, it would be (1,2) (1,3) (2,1) (2,3) (3,1) (3,2).
Both the GSL and C++ STL only provide xPx that I can see. Could someone point me at a C/C++ library which can do this or spell ou... | I've used this library before (note it is C++) in code that needed to do something similar. It has permutations and combinations, with and without repetition. For your problem, this should suffice (untested...):
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
std::vector<int>::iterator first = v.be... |
1,664,028 | 1,664,225 | Why should I use typedefs in C++? | Lets say I have:
set<int, less<int> > m_intset;
That works, but now I change it to typedef, and I do end up with two lines of code:
typedef set<int, less<int> > SetInt;
SetInt m_intset;
What's the advantage of such a typedef? Am I using it correctly?
| Some advantages to using typedef:
Simplification: Now, every time you would normally have needed set<int, less<int> >, you only have to type SetInt. Not a big deal if you're only using the set once, but if you've got multiple instances of the same set, or need to access iterators thereof, the shorter form is much eas... |
1,664,054 | 1,664,120 | C++ - syntax for defining/instantiating strings | I am very new to C++ and still trying to learn syntax and best practices.
I've defined a method with a single parameter:
void foo(const std::string& name)
1) Is this a proper parameter declaration for a function that will be taking in a string defined by the user in, for example, a main method?
2) If this is proper/r... | I'm not sure if I fully understand your question, but I'll try to clarify it.
You use the terminology 'method'. I'm assuming that your method is encapsulated in a class? If so, then :-
In your header file (eg. source.h),
class dog
{
...
public:
void foo(const std::string &name);
...
};
In your so... |
1,664,197 | 1,665,036 | Financial library for C/C++ | Do you know of a good open source financial library written in C (preferably) or C++?
I already looked at Quantlib, which seems too complicated for me, since I just want some basic computations (total cost of credit, all in-cost credit rate...)
Thank you very much!
| When programming for financial derivatives, I absolutely loved Bernt Arne Ødegaard's resource here:
http://finance.bi.no/~bernt/gcc_prog/recipes/recipes/node1.html
It probably has what you want, and then some. If it doesn't, I have to agree with James Black.
|
1,664,342 | 1,664,369 | Is it possible to use COM smart pointers with the CList collection | I'm attempting to create a CList with a COM smart pointer (one of the wrapper classes generated for _com_ptr_t) as the template parameter:
CList<IDispatchPtr, IDispatchPtr> list;
However I get several compilation errors similar to:
error C2664: 'void __stdcall SerializeElements(class CArchive &,class _com_ptr_t<class... | Because of the way operator& is overloaded, you need to wrap the smart pointers in CAdapt<>:
CList<CAdapt<IDispatchPtr>, CAdapt<IDispatchPtr> > list;
|
1,664,372 | 1,664,469 | Best way to store and hash <int, int> key (C++) | My goal is to create an efficient structure to store the most relevant entries of a matrix that would (in a world without memory limitations) be approximately 10^5 x 10^5 and filled with doubles. The matrix is symmetric, so it actually would contain only (10^10)/2 values.
I need to access entries many, many times in my... | If the data is going to be pretty sparse, you could use an array of hash tables.
hash_map<int,double> matrix[] = new hash_map<int,double>[10000];
for (int i = 0; i < 10000; i++) matrix[i] = new hash_map<int,double>();
Then to look up a value (x,y), you index the array with x and look up y in the hash table.
A few thin... |
1,664,502 | 1,664,559 | boost asio: maintaining a list of connected clients | I'm looking for the best way to modify the Boost Asio HTTP Server 3 example to maintain a list of the currently connected clients.
If I modify server.hpp from the example as:
class server : private boost::noncopyable
{
public:
typedef std::vector< connection_ptr > ConnectionList;
// ...
ConnectionList::co... | HTTP is stateless. That means it's difficult to even define what "currently connected client" means, not to mention keeping track of which clients are at any given time. The only time there's really a "current client" is from the time a request is received to the time that request is serviced (often only a few millisec... |
1,664,751 | 1,664,768 | why C, C++, Java does not use one complement? | I heard C, C++, Java uses two complements for binary representation. Why not use 1 complement? Is there any advantage to use 2 complement over 1 complement?
| Working with two's complement signed integers is a lot cleaner. You can basically add signed values as if they were unsigned and have things work as you might expect, rather than having to explicitly deal with an additional carry addition. It is also easier to check if a value is 0, because two's complement only contai... |
1,664,845 | 1,665,070 | Reading a file into an array | I would like to read a text file and input its contents into an array. Then I would like to show the contents of the array in the command line.
My idea is to open the file using:
inFile.open("pigData.txt")
And then to get the contents of the file using:
inFile >> myarray [size]
And then show the contents using a for ... | For context, you could have provided a link to your previous question, about storing two lists of words in different languages. There I provided an example of reading the contents of a text file into an array:
const int MaxWords = 100;
std::string piglatin[MaxWords];
int numWords = 0;
std::ifstream input("piglatin.txt"... |
1,665,018 | 1,665,034 | Memset on vector C++ | Is there any equivalent function of memset for vectors in C++ ?
(Not clear() or erase() method, I want to retain the size of vector, I just want to initialize all the values.)
| Use std::fill():
std::fill(myVector.begin(), myVector.end(), 0);
|
1,665,269 | 1,665,297 | C++ Newbie in Linker Hell | Using g++ and having linker errors. I have a simple program in split into two modules: main.cpp and Dice.h Dice.cpp.
main.cpp:
#include <iostream>
#include "Dice.h"
int main(int argc, char **argv) {
int dieRoll = Dice::roll(6);
std::cout<<dieRoll<<std::endl;
std::cin.get();
return 0;
}
Dice.h:
#if... | Your code is well-formed.
Ensure that your don't have conflicting file names, the files exist and contain what you think they do. For example, perhaps you have a Dice.cpp that's empty, and you're editing a newly created one somewhere else.
Minimize possible discrepancy by removing unnecessary files; only have main.cpp,... |
1,665,427 | 2,130,653 | Generate C++ code for BNF grammar | I have looked at the following software tools:
Ragel
ANTLR
BNF Converter
Boost::Spirit
Coco/R
YACC
ANTLR seems the most straight-forward, however its documentation is lacking.
Ragel looks possible, too, but I do not see an easy way to convert BNF into its syntax.
What other tools are available that can take BNF input... | Try boost.spirit 2.
The boost spirit user list is very active and answers are quick from the authors.
|
1,665,459 | 1,665,507 | PushFront method for an array C++ | I thought i'd post a little of my homework assignment. Im so lost in it. I just have to be really efficient. Without using any stls, boosts and the like. By this post, I was hoping that someone could help me figure it out.
bool stack::pushFront(const int nPushFront)
{
if ( count == maxSize ) // indicates a fu... | You don't need any pointers to shift an array. Just use simple for statement:
int *a; // Your array
int count; // Elements count in array
int length; // Length of array (maxSize)
bool pushFront(const int nPushFront)
{
if (count == length) return false;
for (int i = count - 1; i >= 0; --i)
Swap(a[i], a[... |
1,665,588 | 1,665,611 | Access is Denied for registry | I am playing with the registry programmatically for the first time, and it's not working that well (but at least I haven't destroyed my computer). Specifically, I keep getting back Error 5 (Access is Denied) from RegCreateKeyEx and RegSetValueEx. The thing that is strangest to me is that when HKEY_CURRENT_USER\Software... | You're not asking for any access rights. You probably want to specify KEY_WRITE (or something) for the 6th parameter (samDesired).
LONG result = RegCreateKeyEx(HKEY_CURRENT_USER, TEXT("Software\\dir1\\Sub Directory"),
0, NULL, 0, KEY_WRITE, NULL, &hkey, &dwDisposition);
|
1,665,600 | 1,665,620 | How to link against libxerces-c.so.28? | Whenever we specify -lxerces-c, this looks for libxerces-c.so library in the LIBPATH.
Q1. Why are lib files then generated as libxerces-c.so.28?
Q2. How should we link against such libraries?
The only way I can think of is create a soft link libxerces-c.so which links to the file libxerces-c.so.28. I feel this as an ... | The file name has a version number so that you can have one program that uses version 2.8 and a different program that uses version 2.9. This way, adding a new version of the library will not change the behavior of existing programs that use an old library.
Normally, there should also be a file libxerces-c.so which is... |
1,665,905 | 1,728,038 | SetLineSpacing() does not work in DirectWrite - why? | I'm rendering text in Direct2D/DirectWrite, but calling SetLineSpacing() on either TextFormat or TextLayout seems to have no effect. Does anyone know why?
| I'm 99% sure that this is a bug. I have done a little playing around with Direct2D lately and also had a problem with SetLineSpacing() on TextLayout, think it is the same as what you are describing, in that case I can confirm that it's not just you. Reopen your bug report on MS Connect, it has been closed.
|
1,665,989 | 1,667,095 | Making a 2D engine: compiling necessary libraries with the engine instead of the game | I'm making a 2D engine in C++, and I want to be able to supply a .dll and a .lib so that games can just include those and everything is fine and dandy.
I've looked at how Ogre does it, and it results in ugliness like this:
#ifdef __cplusplus
extern "C" {
#endif
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
INT WINAPI WinMa... | Why not just rename your MAIN to something like Engine::MainLoop and have the client app call that from their main.
|
1,666,073 | 1,666,204 | How port WaitForMultipleObjects to Java? | I have some code in C++ for Windows and I intend to port it to Java. But unfortunately it is not so easy as I thought. Could someone help me, please?
Please, take a look at algorithm:
HANDLE hExitEvent;
HANDLE hDataAvailabeEvent;
while(true)
{
WaitForMultipleObjects();
if (hExitEvent is set)
break;
if (hData... | A simple solution which would seem to fulfill your need is something like:
class DataProcessor implements Runnable {
private final ExecutorService executor =
Executors.newSingleThreadedExecutor();
public void stop { executor.shutdown(); }
public void process(final Data data){
executor.exe... |
1,666,093 | 4,823,889 | CPUID implementations in C++ | I would like to know if somebody around here has some good examples of a C++ CPUID implementation that can be referenced from any of the managed .net languages.
Also, should this not be the case, should I be aware of certain implementation differences between X86 and X64?
I would like to use CPUID to get info on the ma... | Accessing raw CPUID information is actually very easy, here is a C++ class for that which works in Windows, Linux and OSX:
#ifndef CPUID_H
#define CPUID_H
#ifdef _WIN32
#include <limits.h>
#include <intrin.h>
typedef unsigned __int32 uint32_t;
#else
#include <stdint.h>
#endif
class CPUID {
uint32_t regs[4];
publ... |
1,666,176 | 1,672,584 | Intermediate results using expression templates | in C++ Template Metaprogramming : Concepts, Tools, and Techniques from Boost and Beyond
... One drawback of expression templates is that they tend to encourage writing large, complicated expressions, because evaluation is only delayed until the assignment operator is invoked. If a programmer wants to reuse some inter... | For now, you can always use BOOST_AUTO() in the place of C++0x's auto keyword to get intermediate results more easily.
Matrix x, y;
BOOST_AUTO(result, (x + y) * (x + y)); // or whatever.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.