question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
2,125,669 | 2,125,685 | Use of unique on STL vector with a structure | In a programming task, I'm trying to ensure a particular vector contains only unique items. With primitive types, the operation is as simple as:
vector<int> lala;
lala.push_back(1);
lala.push_back(99);
lala.push_back(3);
lala.push_back(99);
sort(lala.begin(), lala.end()); // lala: 1, 3, 99, 99
lala.erase(unique(lala.b... | You also have to define a comparison function that should be used by sort() to sort the Rects. This comparison function should implement a strict weak ordering so that equal elements end up next to each other in the vector.
If the vector is not sorted, unique() will not find the unsorted duplicate elements.
|
2,125,750 | 2,125,800 | Must -read articles for C++ memory mangement | After reading "C++ Memory Management: From Fear to Triumph" series, I think they are must-read articles for memory management. I'd like to know what else must-read articles I shouldn't miss.
Thanks!
| Read and learn well about RAII idiom, Resource Acquisition Is Initialization from articles like the two below:
Memory and Resource Management by Stephen C. Dewhurst
Resource Acquisition is Initialization - Modern C++ Style - A Conversation with Bjarne Stroustrup, Part II
|
2,125,803 | 2,125,838 | How do game events work? | I'v always wondered how this works. Does having more slow down the game? for example how would one represent checking if a car has flipped. It could be seen as:
if (player.car.angle.y == 180)
{
do something
}
The parts that puzzle me is, when would the game check for it? The way I see it, every thing that can happen ... | In most general terms, any object in an engine has a state - if it changes state (e.g. not flipped to flipped), that is a transition.
From a transition you can fire an event or not, but as the transition does only occur when changing state the event won't be fired more then once.
As for the conditions that trigger the ... |
2,125,808 | 2,125,858 | c++ overloaded method in derived class | I have the following question:
Assume base class A with method:
A& operator+(A& a) {...}
I also have a derived class B which overloads (or at least it should so) this method:
A& operator+(B& b) {...}
The problem is that if i want to call something like:
b + a (where b is of type B and a of type A) i get a compile err... | No, it won't call the base class function. Class B has an operator+, it doesn't take the correct parameter, end of story.
You can define operator+ as a free function, not in any class. Perhaps a friend, if it needs to access private data:
A operator+(const A &lhs, const A &rhs) { ... }
B operator+(const B &lhs, const B... |
2,125,862 | 2,132,479 | Virtual functions table offset | I would like to ask you on what does the offset of the table of virtual functions for a class depend? I mean, from what I've read it at least depends on compiler, but does it varies from class to class?
Edit: by offset I mean the position of the table relative to the address of the owner object.
Edit: example code:
voi... | There is certainly a dependency on the exact class.
Remember that C++ has multiple inheritance (MI). The consequence of MI is that a single object may have multiple base subobjects. Those of course cannot be at the same address. This also means that some base subobjects don't actually start at relative offset 0.
Now, ... |
2,125,880 | 2,125,888 | Convert float to std::string in C++ | I have a float value that needs to be put into a std::string. How do I convert from float to string?
float val = 2.5;
std::string my_val = val; // error here
| Unless you're worried about performance, use string streams:
#include <sstream>
//..
std::ostringstream ss;
ss << myFloat;
std::string s(ss.str());
If you're okay with Boost, lexical_cast<> is a convenient alternative:
std::string s = boost::lexical_cast<std::string>(myFloat);
Efficient alternatives are e.g. FastFor... |
2,125,937 | 2,125,948 | Equivalent of InterlockedIncrement in Linux/gcc | It would be a very simple question (could be duplicated), but I was unable to find it.
Win32 API provides a very handy set of atomic operations (as intrinsics) such as InterlockedIncrement which emits lock add x86 code. Also, InterlockedCompareExchange is mapped to lock cmpxchg.
But, I want to do that in Linux with gcc... | GCC Atomic Built-ins
|
2,126,068 | 2,126,074 | Is it possible to automatically serialize a C++ object? | Is there something similar to Java/.NET serialization for C++?
| Boost contains a serialization library. I haven't used it myself, but usually the boost libraries work quite well.
|
2,126,209 | 2,126,259 | How to refrain from CS2512 correctly | Please help me with the following problem:
I have the following classes:
class ChemicalElement
{
private:
std::string _name;
void Init(const std::string& name);
public:
ChemicalElement(const std::string& name);
ChemicalElement(const ChemicalElement& ce);
};
class CombinationRule
{
private:
Chemical... | You should implement constructors of CombinationRule as follows so they will use appropriate constructors of ChemicalElement:
CombinationRule::CombinationRule(const ChemicalElement& ce1,
const ChemicalElement& ce2) : _ce1(ce1), _ce2(ce2)
{
...
}
CombinationRule::CombinationRule(const CombinationRule& rule) :
... |
2,126,338 | 2,126,575 | Problem compiling C++ class | I am running a C++ program which uses a class from another .cpp file. The class only has a constructor. It works when I test it separately. The main program compiles,but when I run it, I have a bug in the constructor. Any one can think of any situation that could happen? Thanks.
I guess I just run the code in terminal... | You need to split your code into a .h (header) and a.cpp (implementation) file and put:
model::model(const char* filename)
{
in the latter. Or, rewrite your class so the definition of the constructor (and any other member functions) is inside the class in the header file:
class model {
...
model(const char*) {
... |
2,126,380 | 2,126,468 | Converting mysqlpp::String to C++ int | Ok, I'm relatively new to using the mysqlpp library that is used in Visual Studio to connect to a MySQL database and am having trouble trying to convert a vector of type mysqlpp::String to a vector of type int. Does anyone have any experience with mysqlpp and would mind helping me out a little? I've posted an example o... | mysqlpp::String has operator int() so your code snippet should work. What problem are you having with it?
If you want to be more explicit, you can use mysqlpp::String's conv function:
int i = futureItemsets[j].conv<int>(0);
timeFrameItemsets.push_back(i);
|
2,126,421 | 2,126,429 | How does this pointer arithmetic work? | #include <stdio.h>
int main(void){
unsigned a[3][4] = {
{2,23,6,7},
{8,5,1,4},
{12,15,3,9}
};
printf("%u",*((int*)(((char*)a)+4)));
return 0;
}
The output in my machine is the value at a[0][1] i.e 23.Could somebody explain how is this working ?
Edit: Rolling Back to old yucky code,exactly what was pr... | So you have your array in memory as so:
2, 23, 6, 7, 8...
What this does is cast the array to a char*, which lets you access individual bytes, and it points here:
2, 23, 6, 7, 8...
^
It then adds four bytes, moving it over to the next value (more on this later).
2, 23, 6, 7, 8...
^
Then it turns it into an int* a... |
2,126,467 | 2,126,492 | Understanding pointers with file i/o in c++ | I'm trying to get a better grasp on pointers. My class assignment was to create the function for the prototype void OpenFile(const char *fileName, ifstream &inFile).
void OpenFile(const char *fileName, ifstream &inFile)
{
inFile.open(FILENAME, ios_base::in);
if (!inFile.is_open()) {
cerr << "Could not open... | First, let me say that your function looks a bit strange if you pass in a parameter fileName but then use FILENAME within and fileName is just used for error output. I guess this is not quite correct.
Second, to the const char* issue. char itself is just a char (character) and as such is only one single character. cons... |
2,126,522 | 2,126,536 | c++ virtual inheritance | Problem:
class Base {
public:
Base(Base* pParent);
/* implements basic stuff */
};
class A : virtual public Base {
public:
A(A* pParent) : Base(pParent) {}
/* ... */
};
class B : virtual public Base {
public:
B(B* pParent) : Base(pParent) {}
/* ... */
};
class C : public A, public B {
public:
C(C* pPar... | virtual base classes are special in that they are initialized by the most derived class and not by any intermediate base classes that inherits from the virtual base. Which of the potential multiple initializers would the correct choice for initializing the one base?
If the most derived class being constructed does not ... |
2,126,633 | 2,126,709 | Private inheritance and composition, which one is best and why? | suppose i have a class engin and i inherit a class car from engin class
class engin
{
public:
engin(int nobofcylinders);
void start();
};
class car:private engin
{
public:
car():e(8){}
void start()
{
e.start();
}
private:
engin e;
};
now t... | I prefer to think of inheritance as derived is a kind of base, that basically means public inheritance. In case of private inheritance it more like derived has a base, which IMHO doesn't sound right, because that's IMHO the work for composition not inheritance of any kind. So, since private inheritance and composition ... |
2,126,751 | 2,126,763 | Beginner Question - Exiting while loop, input type double as condition, C++ | I've only just recent began learning C++ and am having a little issue with while loops when the condition for the while loop is an input, of type double, from the user. I understand that if the user doesn't enter a value compatible with the double type then the loop is automatically broken. The issue is my console appl... | Your problem is that when you say:
cin >> value
and enter anything other than a double, the stream goes bad, because value is expecting a double. Your keep_window_open() function also fails, because the stream is still bad.
There are two ways round this:
Run your program from an existing command line prompt window -... |
2,127,015 | 2,127,036 | C++ Conversion Not Working | #include <iostream>
using namespace std;
/*Use void functions, they perform some action but do not return a value*/
//Function Protoype, input,read in feet and inches:
void input (double& feet, double& inches);
//Function Prototype, calculate, calculate with given formulae.
void calculate(double& feet, double& inches... | That seems a bizarre way of doing it, changing the actual input variables. I would opt instead for:
void calculate (double feet, double inches, double& meters, double& centimeters) {
double all_inches = feet * 12.0 + inches;
centimeters = all_inches * 2.54;
meters = int (centimeters / 100.0);
centimeter... |
2,127,039 | 2,127,155 | Smallest number that is evenly divisible by all of the numbers from 1 to 20? | I did this problem [Project Euler problem 5], but very bad manner of programming, see the code in c++,
#include<iostream>
using namespace std;
// to find lowest divisble number till 20
int main()
{
int num = 20, flag = 0;
while(flag == 0)
{
if ((num%2) == 0 && (num%3) == 0 && (num%4) == 0 && (num%5) == 0 && (... | There is a faster way to answer the problem, using number theory. Other answers contain indications how to do this. This answer is only about a better way to write the if condition in your original code.
If you only want to replace the long condition, you can express it more nicely in a for loop:
if ((num%2) == 0 && (... |
2,127,087 | 2,127,095 | Is this a memory leak? How should it be done? | I have something like this:
void Test(void)
{
char errorMessage[256];
spintf(errorMessage,... blablabla);
throw new CustomException(errorMessage);
}
Will this be a memory leak because errorMessage will be not freed? Or will this cause an exception when accessing the message of the exception inside a try{}... | The memory of errorMessage will already be freed when accessed by the catch handler. However, you could just copy it into a std::string in CustomException's constructor.
A memory leak, on the other hand, could be caused by the exception itself, since you put it on the heap. This is not necessary.
|
2,127,310 | 2,127,436 | C/C++ bitfields versus bitwise operators to single out bits, which is faster, better, more portable? | I need to pack some bits in a byte in this fashion:
struct
{
char bit0: 1;
char bit1: 1;
} a;
if( a.bit1 ) /* etc */
or:
if( a & 0x2 ) /* etc */
From the source code clarity it's pretty obvious to me that bitfields are neater. But which option is faster? I know the speed difference won't be too much ... | I would rather use the second example in preference for maximum portability. As Neil Butterworth pointed out, using bitfields is only for the native processor. Ok, think about this, what happens if Intel's x86 went out of business tomorrow, the code will be stuck, which means having to re-implement the bitfields for an... |
2,127,325 | 2,127,345 | std::vector insert() reallocation | I was looking through the std::vector code and I found something I didn't quite get. When capacity < size() + 1 it needs to reallocate the buffer so it can insert the new element. What it does (as far as I've been able to extract from the code) is:
allocate the new buffer
copy the prefix of the old buffer (0 - index o... | I looked through the MSVC8 vector implementation - I can't see a memmove(). The previous vector elements are not moved, they're copied and their copy c'tor is called to copy them over to the new buffer (the buffer is allocated in a single allocation, elements are constructed using placement new).
Of course this is onl... |
2,127,432 | 2,128,270 | GDB doesn't work with -D_FILE_OFFSET_BITS=64 | I'm compiling a i386 C++ app on Snow Leopard.
When I compile with -D_FILE_OFFSET_BITS=64 I can't use the binary with gdb. I get the following error message:
warning: Could not find object file "/var/folders/kw/kwmH332LGwCIh3GrRREgCk+++TI/-Tmp-//ccZfMAM5.o" - no debug information available for "test.cpp".
| This likely has nothing at all to do with -D_FILE_OFFSET_BITS=64.
When you compile on Mac OS, debug info is not pulled into the executable, but remains in the object file, and the debugger looks for it there.
From your warning message, it appears that you did:
g++ -D_FILE_OFFSET_BITS=64 -g test.cpp
This creates a temp... |
2,127,540 | 2,127,557 | Can anyone explain this algorithm for calculating large factorials? | i came across the following program for calculating large factorials(numbers as big as 100).. can anyone explain me the basic idea used in this algorithm??
I need to know just the mathematics implemented in calculating the factorial.
#include <cmath>
#include <iostream>
#include <cstdlib>
using namespace std;
int mai... | Note that
n! = 2 * 3 * ... * n
so that
log(n!) = log(2 * 3 * ... * n) = log(2) + log(3) + ... + log(n)
This is important because if k is a positive integer then the ceiling of log(k) is the number of digits in the base-10 representation of k. Thus, these lines of code are counting the number of digits in n!.
p = 0.0;... |
2,127,612 | 2,127,624 | Is there a readable implementation of the STL? | I'm on Linux; looking at the STL headers; they're really really complicated.
Is there, somewhere, a smaller version of STL that has the core features of the STL, but is actually readable?
Thanks!
| There is a book The C++ Standard Template Library, co-authored by the original STL designers Stepanov & Lee (together with P.J. Plauger and David Musser), which describes a possible implementation, complete with code - see http://www.amazon.co.uk/C-Standard-Template-Library/dp/0134376331.
|
2,127,693 | 2,127,727 | SFINAE + sizeof = detect if expression compiles | I just found out how to check if operator<< is provided for a type.
template<class T> T& lvalue_of_type();
template<class T> T rvalue_of_type();
template<class T>
struct is_printable
{
template<class U> static char test(char(*)[sizeof(
lvalue_of_type<std::ostream>() << rvalue_of_type<U>()
)]);
tem... | It's a well known technique, I'm afraid :-)
The use of a function call in the sizeof operator instructs the compiler to perform argument deduction and function matching, at compile-time, of course. Also, with a template function, the compiler also instantiates a concrete function from a template. However, this expressi... |
2,127,779 | 2,127,845 | what kind of datatype should i use for this 600851475143 in c++? | i'm using c++, even if i declare long int, there is error like......
long int num = 600851475143;
warning: integer constant is too large for ‘long’ type
which datatype should be used in this case?
| A lot of it depends on the platform and compiler you are using.
If you are on a x64 platform, a long datatype in C++ should work.
A signed long ranges from −9,223,372,036,854,775,808 to +9,223,372,036,854,775,807. An unsigned long on the other hand ranges from 0 to +18,446,744,073,709,551,615.
Also depending on the c... |
2,127,797 | 2,127,819 | Significance of -pthread flag when compiling | In various multi threaded C and C++ projects I've seen the -pthread flag applied to both the compiling and linking stage while others don't use it at all and just pass -lpthread to the linking stage.
Is there any danger not compiling and linking with the -pthread flag - i.e. what does -pthread actually do ? I'm primari... | Try:
gcc -dumpspecs | grep pthread
and look for anything that starts with %{pthread:.
On my computer, this causes files to be compiled with -D_REENTRANT, and linked with -lpthread. On other platforms, this could differ. Use -pthread for most portability.
Using _REENTRANT, on GNU libc, changes the way some libc headers... |
2,127,978 | 2,127,988 | C++ strcpy non-constant expression as array bound | I turned back to C++ after a long time in C#, PHP and other stuff and I found something strange:
temp.name = new char[strlen(name) + strlen(r.name) + 1];
this compiles
temp.name = (char *)malloc(sizeof(char[strlen(name)
+ strlen(r.name) + 1]));
this doesn't (temp.name is a char *)
The compiler error is
error ... | sizeof(...) expects a constant compile-time expression. strlen is not a compile-time expression, it is a function which needs to be executed to get a result. Therefore, the compiler is not able to reserve sufficient storage for an array declared like this:
char c[strlen("Hello")];
Although the length of the string is ... |
2,128,119 | 2,128,194 | Create Square Window C++ | Stuck on a little fiddly problem. I'm creating a GUI in C++ using XP and VS C++ using the command CreateWindow().
My question is, how do I make the inside paintable region a perfect square. When passing in the size of the window to create, some of this is deducted for the menu bar at the top, border all around etc. Are... | The way I usually do it is with AdjustWindowRect. I find it simpler than the other suggested methods (which should work just as well, it's your choice). Use it as such:
RECT rect = {0, 0, desiredWidth, desiredHeight};
AdjustWindowRect(&rect, windowStyle, hasMenu);
const int realWidth = rect.right - rect.left;
const i... |
2,128,128 | 2,128,154 | How can I generate random samples from bivariate normal and student T distibutions in C++? | what is the best approach to generate random samples from bivariate normal and student T distributions? In both cases sigma is one, mean 0 - so the only parameter I am really interested in is correlation (and degrees of freedom for student t). I need to have the solution in C++, so I can't unfortunately use already imp... | You can use the GNU GSL libraries. See here for Bivariate normal:
http://www.gnu.org/software/gsl/manual/html_node/The-Bivariate-Gaussian-Distribution.html
and Student's t-distribution here:
http://www.gnu.org/software/gsl/manual/html_node/The-t_002ddistribution.html
They are straight forward to use.
|
2,128,239 | 2,128,252 | Typecasting, ints and chars in c++ | I'm trying to write a function to detect separators as defined by an assignment and I know it is not good programming style to
#define EXCLAMATION_POINT 33, but to instead do #define EXCLAMATION_POINT '!'
This is my code:
#include <iostream>
#include <ostream>
using namespace std;
#define PERIOD '.'
#define QUESTION_... | You don't need any cast, but:
if (!IsSeparator(input))
should be:
if (IsSeparator(input))
Also, your prompt:
cout << "Enter characters: \n";
implies you can enter multiple characters. So you can, but cin.get() will only read one.
Regarding giving symbolic names to things. Suppose you are parsing a file where the sep... |
2,128,307 | 2,128,363 | Ok to provide constructor + trivial operators for behaviorless aggregates? | This is a follow-up question to 2043381.
Consider the following:
struct DataBundle
{
std::string name;
int age;
DataBundle() : age(0) {}
DataBundle(const std::string& name, int age)
: name(name), age(age) {}
void swap(DataBundle& rhs)
{name.swap(rhs.name); std::swap(age, rhs.age);}
Data... | No, no need for getters and setters yet. It is still a plain data structure where no methods implement actions modifying the data structure - compare, assign, swap are no 'behaviour' here, they're stub needed by the language to perform basic operations and to make the data structure actually usable.
You need to decide... |
2,128,321 | 2,128,727 | Can main function call itself in C++? | Can anybody tell what's the problem of the code below?
int main () {
return main();
}
I tested, it compiles correctly. It's running forever. Anymore trick behind the scene?
| TLDR: Calling main results in undefined behavior.
There seems to be confusion about the terminology used in the standard, and the implications that has for the programmer and compiler.
Firstly, the standard alone determines everything about the C++ language. If your particular version of a particular compiler allows s... |
2,128,389 | 2,128,420 | Edit values in config. file | Currently, I'm using ReadFile() and WriteFile() APIs to write & read from file. are there any API functions to replace/edit text if the data is large enough to be written again? I only heard about SetFilePointer() but i'm not quite sure how to use it to replace the text from a file.
For example, select a string/char fr... | The functions GetPrivateProfileString and WritePrivateProfileString might be good for this.
|
2,128,442 | 2,128,452 | What does (1U << X) do? | I found this piece of code:
enum
{
IsDynamic = (1U << 0), // ...
IsSharable = (1U << 1), // ...
IsStrong = (1U << 2) // ...
};
What does the (1U << X) do?
| It sets bitmasks:
1U << 0 = 1
1U << 1 = 2
1U << 2 = 4
etc...
What happens is 1U (unsigned value 1) is shifted to the left by x bits.
The code you posted is equivalent to:
enum
{
IsDynamic = 1U, // binary: 00000000000000000000000000000001
IsSharable = 2U, // binary: 00000000000000000000000000000010
... |
2,128,496 | 2,128,509 | C++ compilation problem | Pretty much forgot how to code C++ at all. Anyway, here is the problem.
I am trying to load a class defined in a .cpp file I wrote myself.
In the main function:
... ...
#include "loader.h"
... ...
model load_model("TechnologyEnterpriseFacility_Day_Gregor/
TechnologyEnterpriseFacility_Gregor.model");
... | Didn't you forget to insert model.cpp in your compilation line ?
gcc -o glrender glrender.cpp model.cpp -lglut
|
2,128,560 | 2,128,599 | How to determine if a file can be written using C++ | In C++ how can I determine if the program has either read-only access or read-write access to a file? I searched the boost filesystem library but I have yet to find something to help me. Right now I thinking of opening the file, trying to write inside and check for error, but that doesn't seem a very appropriate way of... | At the end of the day, the only way to test if you can write data to a file on a modern OS is to actually try to write it. Lots of things could have happened to the file between tests for permission and the actual write.
|
2,128,620 | 2,128,643 | How to create timer in WinApi (C++)? | How to create timer in WinApi (C++)?
| Call the SetTimer function. This allows you to specify a callback function, or to have Windows post you a WM_TIMER message.
|
2,128,838 | 2,128,955 | compile time polymorphism and runtime polymorphism | I noticed that somewhere polymorphism just refer to virtual function. However, somewhere they include the function overloading and template. Later, I found there are two terms, compile time polymorphism and run-time polymorphism. Is that true?
My question is when we talked about polymorphism generally, what's the wide... | Yes, you're right, in C++ there are two recognized "types" of polymorphism. And they mean pretty much what you think they mean
Dynamic polymorphism
is what C#/Java/OOP people typically refer to simply as "polymorphism". It is essentially subclassing, either deriving from a base class and overriding one or more virtual ... |
2,128,995 | 2,398,856 | LNK2001 error when compiling windows forms application with VC++ 2008 | I've been trying to write a small application which will work with mysql in C++. I am using MySQL server 5.1.41 and MySQL C++ connector 1.0.5. Everything compiles fine when i write console applications, but when i try to compile windows forms application exactly the same way (same libraries, same paths, same project pr... | Project + Properties, General, change Common Language Runtime support to /clr from /clr:pure
|
2,129,155 | 2,134,984 | C++ equivalent for memset on char* | I have this code
char * oldname = new char[strlen(name) + 1];
memcpy(oldname,name,strlen(name) + 1);
name = new char[strlen(oldname) + strlen(r.name) + 1];
memset(name, '\0', strlen(name));
strcat(name,oldname);
strcat(name," ");
strcat(name,r.name);
I understand that it is a no no to use memcpy and m... | char * oldname = new char[strlen(name) + 1];
//memcpy(oldname,name,strlen(name) + 1);
strcpy(oldname,name);
name = new char[strlen(oldname) + strlen(r.name) + 1];
//memset(name, '\0', strlen(name));
name[0] = '\0';
strcat(name,oldname);
strcat(name," ");
strcat(name,r.name);
I unders... |
2,129,189 | 2,129,365 | C++0x move constructor gotcha | Edit: I re-asked this same question (after fixing the problems noted with this question) here: Why does this C++0x program generates unexpected output?
The basic idea is that pointing to moveable things may net you some odd results if you aren't careful.
The C++ move constructor and move assignment operator seem like ... | There are lots of problems with the code.
Observer::observed_ is left uninitialized in the default constructor, leading to an undefined behavior when the destructor gets called.
No value but 0 is ever assigned to Observer::observed_, making the variable superfluous.
Even if there was a way to associate an observer wit... |
2,129,200 | 2,129,418 | view the default functions generated by a compiler? | Is there any way to view the default functions ( e.g., default copy constructor, default assignment operator ) generated by a compiler such as VC++2008 for a class which does not define them?
| With the clang compiler, you can see them by passing the -ast-dump argument. Clang is still in development stage, but you can already use it for these things:
[js@HOST2 cpp]$ cat main1.cpp
struct A { };
[js@HOST2 cpp]$ clang++ -cc1 -ast-dump main1.cpp
typedef char *__builtin_va_list;
struct A {
public:
struct A;
... |
2,129,230 | 2,129,242 | cout << order of call to functions it prints? | the following code:
myQueue.enqueue('a');
myQueue.enqueue('b');
cout << myQueue.dequeue() << myQueue.dequeue();
prints "ba" to the console
while:
myQueue.enqueue('a');
myQueue.enqueue('b');
cout << myQueue.dequeue();
cout << myQueue.dequeue();
prints "ab" why is this?
It seems as though cout is calling the outermost ... | There's no sequence point with the << operator so the compiler is free to evaluate either dequeue function first. What is guaranteed is that the result of the second dequeue call (in the order in which it appears in the expression and not necessarily the order in which it is evaluated) is <<'ed to the result of <<'ing ... |
2,129,235 | 2,129,768 | How to pass a row of boost::multi_array and std::vector by reference to the same template function? | I have a problem with this bit of code:
#include <boost/multi_array.hpp>
#include <boost/array.hpp>
#include <vector>
#include <iostream>
template <typename Vec>
void foo(Vec& x, size_t N)
{
for (size_t i = 0; i < N; ++i) {
x[i] = i;
}
}
int main()
{
std::vector<double> v1(10);
foo(v1, 5);
... | The problem is that for NumDims > 1, operator[] returns a temporary object of type template subarray<NumDims-1>::type.
A (not so nice) work-around would be the something like the following:
typedef boost::multi_array<double, 2> MA;
MA m1;
MA::reference ref = m1[0];
foo(ref, 5); // ref is no temporary now
An alternativ... |
2,129,263 | 2,169,192 | How to build LLVM using GCC 4 on Windows? | I have been able to build LLVM 2.6 (the llvm-2.6.tar.gz package) using MinGW GCC 3.4.5. I haven't tested properly, but it seems to work.
The trouble is, I have libraries of my own which don't build using GCC3, but which work fine in GCC4 (template issues). I believe the first official GCC4 version for MinGW is GCC 4.4.... | If at first you don't succeed...
I can now build LLVM 2.6 using MinGW GCC 4.4.0, and it isn't too hard once you know how. I still cannot run the DejaGNU tests, though at first sight that shouldn't be that hard - most likely I'll need the CygWin packages for dejagnu and expect. I also haven't built llvm-gcc yet.
Before ... |
2,129,388 | 2,129,429 | How to create a class to wrap GLUT? | I'm writing a game for school in OpenGL. Since there will be several more similar assignments I want to make a small framework for doing common things in OpenGL. I have made a few simple games before and I usually break it down into an IO class to handle input and drawing to the screen, Game class for the main game loo... | Unfortunately the glutDisplayFunc() doesn't take a void* pointer so you could've fake an object context. You will have to make a static function that can call into the correct IO instance using a static variable.
I see some slight trouble with your pattern also, though. As far as I know, glutMainLoop() never returns un... |
2,129,521 | 2,129,531 | Why doesn't sizeof parse struct members? | I know that sizeof is a compile-time calculation, but this seems odd to me: The compiler can take either a type name, or an expression (from which it deduces the type). But how do you identify a type within a class? It seems the only way is to pass an expression, which seems pretty clunky.
struct X { int x; };
int m... | An alternate method works without needing a default constructor:
return sizeof(((X *)0)->x);
You can wrap this in a macro so it reads better:
#define member_sizeof(T,F) sizeof(((T *)0)->F)
|
2,129,645 | 2,129,664 | Can you use wxMutex in an event handler? | Is it possible to use wxMutex->Lock() in an event handler? Since it's the main program thread (gui thread) it can't sleep right?
| You certainly can - it's not going to blow up your computer or melt your hard drive or cause demons to fly out of your nostrils if you try.
That said, doing anything on your UI thread that might block is bad, bad, bad, bad, bad.
So while you technically can, you really shouldn't.
|
2,129,700 | 2,129,707 | C++ Expected class-name before '{' token. Inheritance | I've been googling and reading about this and didn't come up with an answer yet, maybe someone can help me with this.
I want my UserPile class to be able to access data members and class member functions from my CardPile class. I keep getting the error mention in the title. Could someone explain what is happening? T... | You have to include CardPile.h in UserPlayer.h if you want to use the class CardPile there.
You are also missing include guards in the headers, e.g.:
// CardPile.h:
#ifndef CARDPILE_H
#define CARDPILE_H
class CardPile {
// ...
};
#endif
Without this you are effectively including CardPile.h twice in UserPlayer.cp... |
2,129,705 | 2,129,727 | Why is (rand() % anything) always 0 in C++? | I am having trouble getting rand() to work in C++. rand() normally gives me a very large number. When I try to use the modulo operator (%) to give it a range, it always returns 0, no matter what.
Seeding the random number generator at the beginning of the program doesn't help either.
| The following code works just fine for me (emitting a random number between 0 included and 1000 excluded each time it's run):
#include <cstdlib>
#include <ctime>
#include <iostream>
int main()
{
std::srand(time(0));
std::cout<<(std::rand() % 1000)<<std::endl;
return 0;
}
|
2,129,718 | 2,129,733 | Switch optimization for many cases guarantees equal access time for any case? ( C++ ) | I've seen answers here for specific languages, about switches with more than 5 cases being optimized with jump tables to guarantee constant access time for any case.
Is that so for C / C++?
Is it in particular for gcc? for visual studio?
If not, would sorting cases in order of occurrence frequency help?
| The standard doesn't guarantee anything about how the switch statement will be implemented. I've never seen a compiler produce a hash table, though quite a few will produce a jump table. Unless my memory is working even worse than usual, both VS and gcc can produce jump tables when the cases are sufficiently dense (for... |
2,130,070 | 2,133,749 | Specific Time Zone In boost::posix_time::ptime | I have the following time :
2010-01-25 03:13:34.384 - GMT Time Zone
2010-01-25 11:13:34.384 - My Local
I wish to convert to timestamp in ms. However, since I only obtain local time string from caller
"2010-01-25 11:13:34.384"
If I do it this way :
// ts is "2010-01-25 11:13:34.384" (My Local)
boost::posix_time::ptime ... | I have this in my local tree (namespace prefix omitted):
/// wall-clock translation to UTC
const ptime from_wall_clock( const ptime& value,
const time_zone_ptr& from )
{
assert( from.get());
// interpret as local time
const local_date_time from_local... |
2,130,099 | 2,175,786 | storing line numbers of expressions with boost.spirit 2 | I am planning on doing a script transformation utility (for extended diagnostic information) using Boost.Spirit 2.
While there is support for line information etc. for parsing errors, how i can store line numbers for successfully parsed expressions with Qi?
| As per the mailing list, Spirit.Classic positional iterators can also be used with Spirit 2.
There is also an article on an iter_pos-parser on the Spirit-blog.
I will update when i had time to test.
|
2,130,158 | 2,130,174 | Is the number of types in a C++ template variant limited? | I'm trying to understand how variants are implemented, and reading:
http://www.codeproject.com/KB/cpp/TTLTyplist.aspx
And I'm getting the impression that I can't write a variant that takes X types; but that the template writer picks some N, and I can only have less than-N types in a variant.
Is this correct?
Thanks!
| In C++03, there are no variadic templates. This means yes; you simply have to pick some N to go up to, and live with that.
In C++0x, there will be variadic templates, so you could use one definition for all X.
If you're looking to make changing the number easy, you can use Boost.Preprocessor and have it do the work for... |
2,130,226 | 2,130,250 | inline virtual function | In C++, my understanding is that virtual function can be inlined, but generally, the hint to inline is ignored. It seems that inline virtual functions do not make too much sense.
Is that right?
Can anybody give a case in which an inline virtual function is good?
| Under normal circumstances, a virtual function will be invoked via a pointer to a function (that's contained in the class' vtable). That being the case, a virtual function call can only be generated inline if the compiler can statically determine the actual type for which the function will be invoked, rather than just ... |
2,130,291 | 2,130,363 | App looking for an invalid dynamic library | alt text http://img63.imageshack.us/img63/5726/screenshot20100125at124.png
I keep getting multiple error windows for an app i'm developing asking for ._libpal_bullet.dll when it should really be just libpal_bullet.dll. The weird thing is after I get all the error messages, the app runs anyway using the correct dlls tha... | Thanks Extrakun, you indirectly helped me figure this one out.
I guess this happens when you copy code between OSes.
The problem was that there were duplicate files of these library names in the build folder. They were metadata files from OS X, which must have come over to the Windows side when I copied the folder to W... |
2,130,326 | 2,130,402 | In wxwidgets, how do I lock a vector that is shared between gui thread and worker thread? | If I can't call lock on a mutex in the main application thread (my event handler because you can't lock the main gui thread), how do I share any information between my worker and my main thread?
| Just have your worker thread communicate with the main thread through the event handling system. Use AddPendingEvent to send status messages back to the main thread and ProcessEvent to handle the updates.
|
2,130,387 | 2,130,400 | Would These Be Considered Magic Numbers? | I've just completed writing a program for a programming class, and I want to avoid use of magic numbers, so here's my question:
In the function below, would my array indexers be considered magic numbers?
Code:
string CalcGrade(int s1, int s2, int s3, double median)
{
const int SIZE = 23;
const int LETTER_GRADE_BARRIERS... | Yes, any number other than -1,0 or 1 is probably a magic number.
Unless you're a real guru, then you're probably allowed to use powers of two freely as well :-)
As an aside, you could probably refactor that code to be a little more understandable, something like:
string CalcGrade (int s1, int s2, int s3, double median)... |
2,130,419 | 2,130,490 | String hashing with linear probing | I am stuck trying to figure out how to do string hashing with linear probing.
Basically, the idea is to hash every string from a dictionary (90000 words), and retrieve anagrams of selected words.
Here's what I did:
created a hash table 2*90000 in size
using a simple hash function, I hash each word from the dictionary,... | Put all the letters in alphabetical order first, then hash the result with any hashing algorithm you please (crc32, md5sum, sha1, count the vowels, anything... though counting the vowels will lead to a less-efficient solution), and store the word as a leaf node to that hash entry (in a linked list, obviously) -- do a m... |
2,130,712 | 2,130,729 | Sorting digits of an integer | You are given an integer 51234 (say) we need to sort the digits of a number the output will be 12345.
How to do it without using array ?
| You can use a loop and % 10 to extract each digit.
An outer loop from 0 to 9 could be used to test if the digit exists. If it exists, print it.
In pseudo code:
n = integer // 51234
FOR digit = 0 TO 9
temp = n
REPEAT
IF temp % 10 = digit THEN PRINT digit
temp /= 10
UNTIL temp = 0
Edit: This test in gcc sh... |
2,130,802 | 2,133,783 | WCF service with Qt? | I would like my Qt app to expose a service to another app written in .Net using WCF.
Is there any support in Qt for implementing WCF services?
| AFAIK there is no 'native' Qt support for WCF or extensions; however as you know WCF can consume and expose a web service (in addition to a WCF or remoting service, etc.) All you need to do is expose it as a Web Service for the other .NET app to consume.
But that brings up an interesting aspect; usually you would writ... |
2,130,838 | 2,130,887 | Convert std::string to MSVC specific __int64 | May I know how I can convert std::string, to MSVC specific __int64?
| _atoi64, _atoi64_l, _wtoi64, _wtoi64_l
std::string str = "1234";
__int64 v =_atoi64(str.c_str());
See also this link (although it is for linux/unix): Why doesn't C++ reimplement C standard functions with C++ elements/style?
|
2,130,864 | 2,130,953 | Cannot access private member in singleton class destructor | I'm trying to implement this singleton class. But I encountered this error:
'Singleton::~Singleton': cannot access private member declared in class 'Singleton'
This is flagged in the header file, the last line which contains the closing brace.
Can somebody help me explain what is causing this problem?
Below is my sourc... | You should probably have let us know that the version of Visual C++ you're working with is VC6. I can repro the error with that.
At this point, I have no suggestion other than to move up to a newer version of MSVC if possible (VC 2008 is available at no cost in the Express edition).
Just a couple other data points - V... |
2,131,006 | 2,132,135 | How to create a ReadWriteMutex without specifying the semaphore's resource count? | The usual pattern for a ReadWriteMutex is to use a semaphore and have the writer loop to acquire all the resources:
inline void write_lock() {
ScopedLock lock(acquire_mutex_);
for (size_t i=0; i < resource_count_; ++i) {
if (sem_wait(semaphore_) < 0) {
fprintf(stderr, "Could not acquire semaphore (%s)\n",... | I found a solution: using pthread_rwlock_t (ReaderWriterLock on Windows). These locks do not require a specific 'max_readers_count'.
I suspect that the implementation for this lock uses some kind of condition variable to lock readers entry when a writer needs to write and an atomic reader count.
Comparing this with my ... |
2,131,087 | 2,341,244 | Creating dll from cpp files with nmake | There is a problem: i need to compile the dll from all source *.cpp files in a particular folder with a help of nmake.
For example, cpp files stored in the folder ".\src", and they must be compiled into one dll.
Where i can read about nmake? Or some examples?
| Checkout nmake: build DLL
|
2,131,093 | 2,131,106 | Distributing the Visual C++ Runtime Libraries (MSVCRT) | I have an ATL/WTL project developed using Visual Studio 2008 and up until now I have been statically linking with the CRT libraries, avoiding the need to ship them. However, I now need to consider using the dynamic libraries (DLL) instead - in order to reduce the size of the code and because I want to use the excellen... | Visual Studio will generate the correct manifest for you when you pass the /MD flag.
|
2,131,191 | 2,131,361 | Is it recommended to trap SIGPIPE in bash script? | I have a problem while executing a bash script from C++ using the system call command.
The script catches a SIGPIPE signal and exit with return code 141.
This problem has started to appear only in the last release of my code.
My Questions are as follows:
Why does this SIGPIPE occur now and didn't occur before?
Is it... | 1) That's very hard to answer without knowing exactly what you changed.
2) If a sequence of commands appears in a pipeline, and one of the reading commands finishes before the writer has finished, the writer receives a SIGPIPE signal. So whether you can ignore it depends on whether that is acceptable behavior for your ... |
2,131,397 | 2,167,139 | How to get Shared Object in Shared Memory | Our app depends on an external, 3rd party-supplied configuration (including custom driving/decision making functions) loadable as .so file.
Independently, it cooperates with external CGI modules using a chunk of shared memory, where almost all of its volatile state is kept, so that the external modules can read it and ... | I suppose the easiest option would be to use memory mapped file, what Neil has proposed already. If this option does not fill well, alternative is to could be to define dedicated allocator. Here is a good paper about it: Creating STL Containers in Shared Memory
There is also excellent Ion Gaztañaga's Boost.Interprocess... |
2,131,482 | 2,131,503 | Can we use a timer for itself? | Actually this is what i want to do;
When a condition appears, my program will close itself and after five minutes it will re-open.
Is it possible with only one .exe -by using any OS property-?
I do it with two .exe
if (close_condition){
//call secondary program
system ("secondary.exe");
return (0);
}
a... | You can do it with one application that simply has different behaviour if a switch is given (say myapp.exe /startme).
system() is a synchronous call by the way, it does only return when the command run is finished. In win32 CreateProcess() is what you are looking for.
You can also just follow Jays suggestion of letting... |
2,131,604 | 2,131,809 | How to implement a basic Variant (& a visitor on the Variant) template in C++? | I have tried reading:
http://www.boost.org/doc/libs/1_41_0/boost/variant.hpp
http://www.codeproject.com/KB/cpp/TTLTyplist.aspx
and chapter 3 of "Modern C++ Design"
but still don't understand how variants are implemented. Can anyone paste a short example of how to define something like:
class Foo {
void process(T... | If i had to define a variant object, i'd probably start with the following :
template<typename Type1, typename Type2>
class VariantVisitor;
template<typename Type1, typename Type2>
class Variant
{
public:
friend class VariantVisitor<Type1, Type2>;
Variant();
Variant(Type1);
Variant(Type2);
// + appropri... |
2,131,904 | 2,131,927 | Trusting the Return Value Optimization | How do you go about using the return value optimization?
Is there any cases where I can trust a modern compiler to use the optimization, or should I always go the safe way and return a pointer of some type/use a reference as parameter?
Is there any known cases where the return value optimization cant be made?,
Seems t... | Whenever compiler optimizations are enabled (and in most compilers, even when optimizations are disabled), RVO will take place. NRVO is slightly less common, but most compilers will perform this optimization as well, at least when optimizations are enabled.
You're right, the optimization is fairly easy for a compiler t... |
2,132,114 | 2,132,140 | Recursive and non recursive procedures for trees |
as we know that the trees are recursive data structures, We use recurrsion in writing the procedures of tree like delete method of BST etc.
the advantage of recurrsion is, our procedures becomes very small (for example the code of inorder traversal is of only 4 or 5 lines) rather than a non recurrsive procedure which... | Recursion is a tool like any other. You don't have to use every tool that's available but you should at least understand it.
Recursion makes a certain class of problems very easy and elegant to solve and your "hatred" of it is irrational at best. It's just a different way of doing things.
The "canonical" recursive func... |
2,132,305 | 2,226,132 | How to get a message request from its sequence number? | Given a sequence number, I need to find the corresponding request message string.
I can't find a way to it easily do that with quickFix lib.
To be short, I've had the idea to use the FileStore "body" file to help me retrieve the message request string from a sequence number,as the FileStore class exposes a convenient m... | I'm not sure why are you trying to get the 'message string' based on sequence number.
Is this during trading? Can you modify your application code? Your application gets the messages from the server/client so you can just dump the message as string (in c++ they have methods something to do with ToString() or similar).
... |
2,132,747 | 4,563,701 | Warning C4251 when building a DLL that exports a class containing an ATL::CString member | I am converting an ATL-based static library to a DLL and am getting the following warning on any exported classes that use the ATL CString class (found in atlstr.h):
warning C4251: 'Foo::str_' : class
'ATL::CStringT'
needs to have dll-interface to be used
by clients of class 'Foo'
I am correctly declaring the F... | This thread gives what I consider a better answer, by Doug Harrison (VC++ MVP):
[This warning is] emitted when you use
a non-dllexported class X in a
dllexported class Y. What's so bad
about that? Well, suppose Y has an
inline function y_f that calls a
function x_f belonging to X that is
not also inline. I... |
2,132,904 | 2,133,244 | Externalizing parameters for VS2008 C++ project compilation | Is there some way to externalize the paths of libraries that are used in the compilation process on Visual Studio 2008? Like, *.properties files?
My goal is to define "variables" referencing locations to headers files and libraries, like *.properties files are used in the Ant build system for Java.
| I think you're looking for .vsprops files. They're comparable to the *.properties files.
|
2,133,103 | 2,133,149 | Passing platform-specific data in a platform independent design? | I have a game engine design written in C++ where a platform-independent game object is contained within a platform-specific Application object.
The problem I'm trying to solve is the case where I need to pass OS-specific data from the Application to the game. In this case, I'd need to pass the main HWND from Windows f... | Remember that you only need to know the target platform at compile time. With this information, you can 'swap in and out' components for the correct platform.
In a good design, the Game should not require any information about it's platform; it should only hold the logic and related components.
Your 'Engine' classes sh... |
2,133,185 | 2,133,501 | How to get Default JVM INITIAL ARGS In JNI | I'm trying to get the default jvm args of the available JVM but I'm getty a strange output. Anyone can point me to what's wrong?
Output:
65542
�p����Y����k�.L�R���g���J����sk��,��*�Jk��xk��
Code:
#include "jni.h"
#include <iostream>
#include <dlfcn.h>
#include <cstdlib>
using namespace std;
void * JNI_FindCreateJava... | The prototype for JNI_GetCreatedJavaVMs is:
jint JNI_GetCreatedJavaVMs(JavaVM **vmBuf, jsize bufLen, jsize *nVMs);
You call the function with a *JavaVMInitArgs parameter and I am not sure why you expect your code to print anything reasonable.
|
2,133,250 | 2,133,260 | "X does not name a type" error in C++ | I have two classes declared as below:
class User
{
public:
MyMessageBox dataMsgBox;
};
class MyMessageBox
{
public:
void sendMessage(Message *msg, User *recvr);
Message receiveMessage();
vector<Message> *dataMessageList;
};
When I try to compile it using gcc, it gives the following error:
MyMessageBox does n... | When the compiler compiles the class User and gets to the MyMessageBox line, MyMessageBox has not yet been defined. The compiler has no idea MyMessageBox exists, so cannot understand the meaning of your class member.
You need to make sure MyMessageBox is defined before you use it as a member. This is solved by reversin... |
2,133,583 | 2,455,330 | WIX C++ Custom Action | I have a basic WIX custom action:
UINT __stdcall MyCustomAction(MSIHANDLE hInstaller)
{
DWORD dwSize=0;
MsiGetProperty(hInstaller, TEXT("MyProperty"), TEXT(""), &dwSize);
return ERROR_SUCCESS;
}
Added to the installer:
<CustomAction Id="CustomActionId" ... | You need to export the called function so MSI can call it using undecorated C style name
Replace your code with this
extern "C" _declspec(dllexport) UINT __stdcall MyCustomAction(MSIHANDLE hInstall);
extern "C" UINT __stdcall MyCustomAction(MSIHANDLE hInstall)
{
DWORD dwSize=0;
MsiGetPro... |
2,133,630 | 2,133,670 | Can a class method be both inline and static? | Does it even make sense?
| static means that the method isn't associated with an instance of a class. (i.e. it has no "this" pointer).
inline is a compiler hint that the code for the method ought to be included inline where it is called, instead of being called via a normal branch. (Be aware that many compilers ignore this keyword, and use their... |
2,133,651 | 2,133,952 | Spectrogram C++ library | For my current project in C++ / Qt I need a library (LGPL is preferred) which can calculate a spectrogram from a signal ( basically an array of doubles ). I already use Qwt for the GUI part.
Any suggestions?
Thanks.
| It would be fairly easy to put together your own spectrogram. The steps are:
window function (fairly trivial,
e.g. Hanning)
FFT (FFTW would be
a good choice but if licensing is an
issue then go for Kiss FFT or
similar)
calculate log magnitude
of frequency domain components
(trivial: log(sqrt(re * re + im *
im))
|
2,133,903 | 2,133,934 | Convert float to bigint (aka portable way to get binary exponent & mantissa) | In C++, I have a bigint class that can hold an integer of arbitrary size.
I'd like to convert large float or double numbers to bigint.
I have a working method, but it's a bit of a hack. I used IEEE 754 number specification to get the binary sign, mantissa and exponent of the input number.
Here is the code (Sign is ign... | Can't you normally extract the values using frexp(), frexpf(), frexpl()?
|
2,134,165 | 2,137,872 | C++ Design pattern for Search and Replace | I have big paragraph with some special characters as %1 , %2, %3
I need to know if there is any design pattern to replace those with proper values and create final paragraph.
For Example:
Following is my static paragraph.
%1 is beautiful country , %2 is the capital of %1, %1 national language is %3.
I get values of %1,... | you can use strstr or sscanf to find string pointers to a semi-pattern(both are part of the c std library), how ever, to replace, you would need to expand the memory block to accommodate the replacements(if they are bigger), have a look at grep(for unix), or see some of the string search algo's, like Boyer-Moore.
You c... |
2,134,329 | 2,136,482 | Are multiline tooltips possible using CWnd::EnableTooltips()? | I'm attempting to make my tooltips multiline, but I don't seem to be having much luck with it. I call CWnd::EnableTooltips() directly after creation (in this case, an edit box) and I handle the TTN_NEEDTEXT message. My tooltips display correctly, but only display as a single line.
I've tried adding '\n' to the stri... | I was successful in making a \n delimited tooltip into a multi-line tooltip using the following code in the TTN_NEEDTEXT handler
For DevStudio 6
CToolTipCtrl* pToolTip = AfxGetThreadState()->m_pToolTip;
pToolTip->SetMaxTipWidth(SHRT_MAX);
You have to call again each time TTN_NEEDTEXT is called or it won't stick.
I fou... |
2,134,363 | 2,134,389 | The C `clock()` function just returns a zero | The C clock() function just returns me a zero. I tried using different types, with no improvement... Is this a good way to measure time with good precision?
#include <time.h>
#include <stdio.h>
int main()
{
clock_t start, end;
double cpu_time_used;
char s[32];
start = clock();
printf("\nSleeping... | clock() reports CPU time used. sleep() doesn't use any CPU time. So your result is probably exactly correct, just not what you want.
|
2,134,384 | 2,134,792 | How to use ETW from a C++ Windows client | I'm researching Event Tracing for Windows (ETW) to allow a user-mode windows client to write out tracing information. The existing documentation is, to put it lightly, insanely incomplete. What would really help is a simple C++ example that writes out tracing messages using ETW. Does such an example exist? Is there oth... | To write a Provider for ETW, you have two options:
write it as a manifest-based provider (preferred for Windows Vista or higher). Check out an example here.
write it as a classic provider for legacy support. You can find an example here.
I suppose you want to use a manifest-based approach, as its better and can suppo... |
2,134,391 | 2,179,747 | Create an interactive logon session | I'm trying to create a utility similar to Microsoft's abandoned Super Fast User Switcher (download), which allows fast user switching without going through the Welcome screen.
I have a working implementation using the undocumented WinStationConnectW API (along with WTSEnumerateSessions), but it can only switch to a use... | I solved this in XP by calling the undocumented InitiateInteractiveLogon function in the ShellLocalMachine COM object in shgina.dll.
This method, which can only be called by the Local System account, will log a user on to the console. (It cannot log a user on to an RDP session)
The version of the DLL included with Win... |
2,134,758 | 2,135,455 | Unittest++: test for multiple possible values | i am currently implementing a simple ray tracer in c++. I have a class named OrthonormalBasis, which generates three orthogonal unit vectors from one or two specified vectors, for example:
void
OrthonormalBasis::init_from_u ( const Vector& u )
{
Vector n(1,0,0);
Vector m(0,1,0);
u_ = unify(u);
v_ = cros... | Surely if all you are testing is whether your basis is orthonormal, then that's what you need to test?
// check orthogonality
CHECK_EQUAL( 0, dot(onb.u(), onb.v));
CHECK_EQUAL( 0, dot(onb.u(), onb.w));
CHECK_EQUAL( 0, dot(onb.v(), onb.w));
// check normality
CHECK_EQUAL( 1, dot(onb.u(), onb.u));
CHECK_EQUAL( 1, dot(... |
2,134,836 | 2,134,874 | What Linux library supports sockets, ioctl calls, tuntap, etc...? | What is the name of the runtime library which implements Linux network interfaces, like sockets, tuntaps, netlink, etc...? For example when I create an UDP socket and make an ioctl call to fetch network interface info, which library actually implements that call? What are the corresponding *.so files on most linux dsti... | These are c library calls, and as such are in the libc library.
|
2,134,844 | 2,134,876 | Why can't I put a "using" declaration inside a class declaration? | I understand the troubles you can get into when you put a using declaration inside a header file, so I don't want to do that. Instead I tried to put the using (or a namespace foo =) within the class declaration, to cut down on repetitive typing within the header file. Unfortunately I get compiler errors. Seems like ... | Could you do typedef gee::whiz::abc::def::Hello Hello?
|
2,134,943 | 2,134,975 | Which overloaded version of operator will be called | Suppose i have declared subscript operators in a class
char& operator[] (int index);
const char operator[](int index) const;
In what condition the second overload is called. Is it only called through a const object.
In the following scenarios which version of operator will be called.
const char res1 = nonConstObjec... | The first one is called. Don't get confused by the return value; only the arguments are considered to select the method. In this case, the implicit this is non-const, so the non-const version is called.
|
2,135,036 | 2,135,085 | How to export C++ function as a dll that throws exception? | When I try to export the following function as a dll:
extern "C" __declspec(dllexport) void some_func()
{
throw std::runtime_error("test throwing exception");
}
Visual C++ 2008 gives me the following warning:
1>.\SampleTrainer.cpp(11) : warning C4297: 'some_func' : function assumed not to throw an exception but does... | If you are determined to do what the compiler is warning you about, why not just suppress the warning?
#pragma warning(disable: 4247)
|
2,135,094 | 2,135,268 | gcc reverse_iterator comparison operators missing? | I am having a problem using const reverse iterators on non-const containers with gcc. Well, only certain versions of gcc.
#include <vector>
#include <iostream>
using namespace std;
int main() {
const char v0[4] = "abc";
vector<char> v(v0, v0 + 3);
// This block works fine
vector<char>::const_iterato... | It is a defect in the current standard: http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#280
Edit: Elaborating a bit:
The issue is that, in the current standard:
vector::reverse_iterator is specified as std::reverse_iterator<vector::iterator>, and vector::const_reverse_iterator as std::reverse_iterator<vec... |
2,135,116 | 2,135,469 | How can I determine distance from an object in a video? | I have a video file recorded from the front of a moving vehicle. I am going to use OpenCV for object detection and recognition but I'm stuck on one aspect. How can I determine the distance from a recognized object.
I can know my current speed and real-world GPS position but that is all. I can't make any assumptions ab... | When you have moving video, you can use temporal parallax to determine the relative distance of objects. Parallax: (definition).
The effect would be the same we get with our eyes which which can gain depth perception by looking at the same object from slightly different angles. Since you are moving, you can use two suc... |
2,135,199 | 2,135,232 | How to compile this on Windows | Ok. I am trying to compile the following application on Windows (Segmenter, see step 3).
I checked out the source and changed the references so that'd all be good. It's basically a one file app, with a reference to ffmpeg.
The makefile reads:
gcc -Wall -g segmenter.c -o segmenter -lavformat -lavcodec -lavutil -lbz2 ... | The line indicates a very simple compile. It's compiling the file with one standard argument (-g for compiling with debug symbols, on MSVC it's /Zi).
But it's linking with a lot of libraries (that's all the -l options). I recognize two of those as standard compression libraries (bz2 and z), so you are going to need t... |
2,135,355 | 2,135,468 | Crash, while printing contents of linked-list | I'm having some trouble printing out the contents of a linked list. I'm using an example code that I found somewhere. I did edit it a bit, but I don't think that's why it's crashing.
class stringlist
{
struct node
{
std::string data;
node* next;
};
node* head;
node* tail;
public:
BOOLEAN append(st... | As @rmn pointed out, you're not initializing the value of node->next.
BOOLEAN append(std::string newdata)
{
if (head)
{
tail->next = new node;
if (tail->next != NULL)
{
tail=tail->next;
tail->data = newdata;
tail->next = NULL; // <- this is the part that is missing
retur... |
2,135,397 | 2,137,352 | Design options for references into a thread safe cache when evicting older entries | I'm trying to design a simple cache that follows the following rules:
Entries have a unique key
When the number of entries in the cache exceeds a certain limit, the older items are evicted (to keep the cache from getting too large).
Each entry's data is immutable until the entry is removed from the cache.
A 'reader' c... | In a native system without a higher power (such as a VM) capable of performing garbage collection, you aren't going to do much better performance or complexity wise than reference counting.
You are are correct the reference counting can be tricky - not only does the increment and decrement have to atomic, but you need ... |
2,135,441 | 2,135,511 | How to create something like firefox's bookmark sidebard in Visual Studio 2008 C++ project? | I have visual studio 2008, and want to build an GUI application that on the left side has a frame that can be minimized like the firefox bookmark sidebar. So my questions are: 1) What type of project do I need? 2) What controls actually make up the sidebar. 3) What do I make the main frame so that I can resize it whe... | It looks like a TaskPane (CTaskPane ) attached to a simple SDI frame window (taking into account firefox is doing a lot of things custom with their own toolkit (I think, and I've been known to be wrong)
Download the MFC VS2008 feature pack (with the new UI controls) and the feature pack samples and have a look at some ... |
2,135,788 | 2,137,500 | What do C and Assembler actually compile to? | So I found out that C(++) programs actually don't compile to plain "binary" (I may have gotten some things wrong here, in that case I'm sorry :D) but to a range of things (symbol table, os-related stuff,...) but...
Does assembler "compile" to pure binary? That means no extra stuff besides resources like predefined str... | C typically compiles to assembler, just because that makes life easy for the poor compiler writer.
Assembly code always assembles (not "compiles") to relocatable object code. You can think of this as binary machine code and binary data, but with lots of decoration and metadata. The key parts are:
Code and data appea... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.