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 |
|---|---|---|---|---|
5,588,084 | 5,605,407 | compilation problems using boost math | I used to installer from http://www.boostpro.com/download/ to build boost and would like to use some of the math functions. Something like this:
Plm[l][m] = boost::math::legendre_p(l,m,cosine);
Naturally, I included:
#include <boost/math/special_functions/spherical_harmonic.hpp>
And added the path to boost to my addi... | Alright, this was though one. In my code, l and m are unsigned. But there is only an overload for legendre_p(int,int,T). Thus, my function call is mapped to legendre_p(int,T,&policy) (or so I think).
|
5,588,191 | 5,588,382 | Need ideas on how to store something in C++ | I am working in a large project for a game which involves Javascript, Jquery, C++, and Awesomium. Right now I will only focus on C++ for this question. In the game, there are supposed to be two different "jobs" (you can either be a scientist or a ditchman). I need to make a way to check to see which job you currently a... | You use an "object". These are collections of state and variables that you bring around with you, effectively.
enum Job {
Scientist,
Ditchman
};
class Player {
Job j;
public:
void job(Job newjob) { j = newjob; }
Job job() { return j; }
Player() { job = Scientist; }
};
int main() {
Player p... |
5,588,281 | 5,588,342 | Class template argument dependent on constructor | With a templated number wrapping struct:
template <int I> struct Num { static const int n = I; };
and a few overloaded functions:
template <typename T>
Num<0> id(T x) { return Num<0>(); }
Num<1> id(int x) { return Num<1>(); }
Num<2> id(double x) { return Num<2>(); }
Num<3> id(char x) { return Num<3>(); }
I ... | It's perfectly possible- just pass in *((T*)nullptr) to obtain an lvalue of any type T regardless of it's constructability. After all, all you actually do with the constructor argument is pass it to id and then decltype that, which is perfectly doable in the template, since you know that the type of x is T.
template<ty... |
5,588,477 | 5,588,523 | strstr() function and "\r\n" | const char * strstr ( const char * str1, const char * str2 );
char * strstr ( char * str1, const char * str2 );
Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1
Lets say char* str2=new char(5000) is declared like this, and characters from a file are r... | It keeps going till the end of the string ('\0')
|
5,588,567 | 5,588,590 | Trouble With Building Live555 Media Server in VS2005 | This could be a very silly question to any long time C++, visual studio or live555 users but I am having problems building the live555 source code with visual studio 2005. I have found a good walk through guide for creating the projects manually because .mak files are no longer supported by newer versions of visual stu... | It seems to me that Visual studios cannot find the file, rather than it not being able to open that file type. If you right click on your project and go to
Properties->C/C++->General->Additional Include Directories
Now browse to the location of the .hh file and add it to the path. Visual studios should now be able to f... |
5,588,845 | 5,588,950 | How do I use a string in a struct instead of a char array for reading binary data | I am reading binary data into a struct, which is working just fine. Here is the code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct TaqIdx {
char symbol[10];
int tdate;
int begrec;
int endrec;
}__attribute__((packed));
int main()
{
ifstream fin("T201010A.IDX", ios::i... | I can't "comment everywhere" yet, so I apologize for this being kind of out of standard protocol around these parts. Why doesn't this break?
idx.symbol[10] = '\0';
The length of symbol is 10, won't having __attribute__((packed)) in there put a null byte into the first byte of tdate?
|
5,589,166 | 5,589,200 | Don't know template parameter types when casting a void* to a templated type | I am using the pthreads library and when I create a thread I am giving it the pointer to an object that is a templated type.
I'm inexperienced with templates (just read about them today) and need to cast the void* parameter from the method declaration the pthread runs to the templated type so I can access its members. ... | template<typename T>
void *run(void *arg) {
static_cast<A<T>*>(arg)->aMember();
}
int main() {
A<int> a;
pthread_create(..., ..., &run<int>, &a);
...
...
...
}
This does, like your original code snippet, rely on extern "C++" calling convention to be the same as what your pthread library uses... |
5,589,283 | 5,589,311 | max size of char array? | Is there a max limit to the number of bytes you can allocate to an array pointer?
For example if i use a size of 16000 then this works.
char* iobuffer=new char(16000);
iobuffer[15000]='a';
However
char* iobuffer=new char(160000);
iobuffer[150000]='a';
this does not.
It shouldn't be a memory issue so is there some int... | You've actually got your allocation code wrong. You're using parenthesis, which provide an initializer for your newly allocated value. In other words, in both cases you have a single char allocated for use, initialized to 16000 and 160000 respectively. Use brackets to dynamically allocate an array.†
After that, you sub... |
5,589,361 | 5,589,373 | C++ - Insertion Operator, const Keyword Causes Compiler Error | So I'm building a class, for simplicity, I'll dumb it down here.
This gives a compiler error: "Error: the object has type qualifiers that are not compatible with the member function."
This is the code:
ostream& operator<<(ostream& out, const Foo& f)
{
for (int i = 0; i < f.size(); i++)
out << f.at(i) << ", ... | You need to declare your "at" function and your "size" function as const, otherwise they cannot act on const objects.
So, your function might look something like this:
int Foo::at(int i)
{
// whatever
}
And it needs to look like this:
int Foo::at(int i) const
{
// whatever
}
|
5,589,381 | 5,590,050 | Calling function template specialization using C calling conventions | I have the following template
template<typename T> void f(T t) { }
And I want to pass the address of a specific specialization of it to a C function
g(&f<int>);
But as I want to be portable, I want the calling convention of "f" to match the one of C. So I experimented how language linkage affects calling convention a... | What does the C header look like? Somewhere, the C source must enumerate the callback types allowed. You should take that opportunity to have a series of macros that generate prototypes to individual stub functions, with a corresponding sequence of macros in the C++ source generating extern "C" stubs.
As to the secon... |
5,589,454 | 5,589,474 | C++ classes - how to reference a member function from another member function | I'm very new to c++ classes, so this is probably a really obvious question, but because I'm not familiar with the lingo yet I cant seem to be able to get a correct search term.
Anyway, what I am trying to do is have a public function in a class access a private function in same class.
eg
//.h file:
class foo {
float ... | Your return types don't match:
//.h file:
class foo {
float useful(float, float); // <--- THIS ONE IS FLOAT ....
public:
int bar(float);
};
//.cpp file:
int foo::useful(float a, float b){ // <-- ...THIS ONE IS INT. WHICH ONE?
//does something and returns an int
}
int foo::bar(float a){
//how do I acc... |
5,589,533 | 5,589,583 | Null References - Where in the C++ Standard |
Possible Duplicates:
C++: null reference
When does invoking a member function on a null instance result in undefined behavior?
Is there any section in the C++ standard the shows that NULL references are ill-formed?
I am trying to show my lecturer (this is for an assignment for which I am being graded) that the follo... | §8.5.3/1: "A variable declared to be a T&, that is “reference to type T” (8.3.2), shall be initialized by an object, or function, of type T or by an object that can be converted into a T."
The code above does not initialize the reference with an object or function of type T or an object that can be converted to T. The ... |
5,589,550 | 5,589,601 | Getting a memory address in my array? | I'm writing a C++ application that has a user enter a 0 (zero) or a one (1) as input, then stores the numbers as an array and sorts them so that the zeros come first and the ones come last.
However, I think I'm getting a memory address in my array that's messing up the sorting operation.
The function that accepts input... | It looks to me like you're just getting an uninitialized value in your output.
Under the circumstances, the simplest "sorting" method is probably a counting sort -- i.e., count the number of 0's and the number of 1's the user enters, and then print out the appropriate number of 0's followed by the appropriate number of... |
5,589,956 | 5,590,589 | help with linked list template | I need some help with my linked list. I think the problem is in the copy constructor or the assignment overload. it keeps giving my segmentation fault when i call:
(Queue test_int_copy(test_int);)
Any other error or poor implementation that you can see would also be very helpful.
the .h file
#ifndef QUEUE_H
#define Q... | You should initialize your head pointer in your copy constructor (and also in your operator = function by the way). If you don't do so, head might end up with an undefined value and fail the IsEmpty test, witch may lead to a crash in enqeue.
|
5,589,965 | 5,590,026 | Organizing large C++ project | Should all C++ code in a project be encapsulated into a single class with main simply calling that class? Or should the main function declare variables and classes.
| If you are going to build a large project in C++, you should at the very least read Large Scale C++ Software Design by John Lakos about it. It's a little old but it sounds like you could benefit from the fundamentals in it.
Keep in mind that building a large scale system in any language is a challenge and requires skil... |
5,590,006 | 5,590,087 | std::string not working with std::set | I'm doing a programming question from C++ Primer Plus which asks me to make a template
function that returns the number of unique elements in an array. I don't understand why
line 13 causes an error while compiling as to my knowledge, a std::string behaves like an array.
This is my code:
#include <iostream>
#include ... | Following up my immediate response that std::string is not an array, this is the way a C++ person might accomplish the task you're looking for.
#include <iterator>
#include <iostream>
#include <set>
// instead of taking an array and length, just take where you want to start and where
// you want to stop.
template <typ... |
5,590,015 | 5,590,500 | Detect the the vtable offset of a specific virtual function (using Visual C++) | Can the vtable offset of a specific virtual function be inspected?
Why? I'd like to be able to detect unintentional binary compatibility breaks (see http://techbase.kde.org/Policies/Binary_Compatibility_Issues_With_C%2B%2B for what I mean by binary compatibility).
I'm aware of the undocumented and unsupported techniqu... | Inspired by Jerry's answer, I managed to write up this function that can do the same thing for any function signature:
#include <iostream>
struct A
{
virtual void a() {}
virtual void b() {}
virtual void c() {}
};
template <class T>
int SeeBits(T func)
{
union
{
T ptr;
int i;
};... |
5,590,381 | 5,591,169 | Easiest way to convert int to string in C++ | What is the easiest way to convert from int to equivalent string in C++? I am aware of two methods. Is there an easier way?
(1)
int a = 10;
char *intStr = itoa(a);
string str = string(intStr);
(2)
int a = 10;
stringstream ss;
ss << a;
string str = ss.str();
| C++11 introduces std::stoi (and variants for each numeric type) and std::to_string, the counterparts of the C atoi and itoa but expressed in term of std::string.
#include <string>
std::string s = std::to_string(42);
is therefore the shortest way I can think of. You can even omit naming the type, using the auto keywo... |
5,590,391 | 5,590,422 | c++ implicit copy constructor and the assignment operator | I have a class defined as follows:
#include <iostream>
using namespace std;
class Point
{
int x, y;
public:
Point(int a, int b) : x(a), y(b)
{
std::cout << "Constructing point ( " << a << ", " << b << " ) "
<< std::endl;
}
Point(const Point& p) : x(p.x), y(p.y)
{
... | No, in a declaration like that the = operator actually still means to call a constructor, and the compiler probably elided away any possible copy construction as an optimization. = in a declaration would never result in an assignment being called. So in theory a temporary could be created and copy-constructed into p1.
|
5,590,430 | 5,590,829 | Mac: I get SIGABRT but the call stack is useless | I'm coding a game for Mac in c++, and I'm getting a SIGABRT, and the console prints the following:
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_lexical_cast> >'
what(): bad lexical cast: source type value could not be inte... | The debugger stopped in the wrong thread. Try t a a bt in GDB to see backtraces for all the threads.
mach_msg_trap is where threads park while they are waiting for a message to come in. So, you are looking at a thread that isn't running. Mach is the name of the message-passing interface on OS X.
|
5,590,459 | 5,590,478 | Is there any (performance-related) downside to compiling C code with the Visual Studio C++ compiler? | This is my first time developing with Visual Studio (2010) and I noticed that:
int *x = malloc(sizeof(int) * 50);
gives an error when I try to build "main.c". I'm assuming this is because VS is using its C++ compiler to build C programs.
Is the code generated by VS for C as good as it gets under Windows or should I lo... | I don't use the Visual Studio compiler purely because it's not C99 compliant, and I find C99 much easier to work with.
Personally I use MinGW + GCC instead, but I use Notepad++ instead of Visual Studio. I know that its definitely possible to get Visual Studio to compile using GCC, but I'm not aware of anyone who has d... |
5,590,621 | 5,590,656 | Why does windows need the size when calling a function? | I am trying to learn a little c++ and I have a silly question. Consider this code:
TCHAR tempPath[255];
GetTempPath(255, tempPath);
Why does windows need the size of the var tempPath? I see that the GetTempPath is declared something like:
GetTempPath(dword size, buf LPTSTR);
How can windows change the buf value witho... | Windows needs the size as a safety precaution. It could crash the application if it copies characters past the end of the buffer. When you supply the length, it can prevent that.
Array variables work like pointers. They point to the data in the array. So there is no need for the & operator.
Not sure what kind of exampl... |
5,590,649 | 5,590,704 | Problems due to extra whitespace in boost::lexical cast | This causes problems due to extra whitespace:
std::string t("3.14 ");
double d = boost::lexical_cast<double> (t);
So, I wrote this
template<typename T>
T string_convert(const std::string& given)
{
T output;
std::stringstream(given) >> output;
return output;
}
double d = string_convert<double> (t);
What can ... | Note that your code isn't always correct. If you do string_convert<double>("a"), for example, the read will fail and you'll return output uninitialized, leading to undefined behavior.
You can do this:
template<typename T>
T string_convert(const std::string& given)
{
T output;
if (!(std::stringstream(given) >> outp... |
5,590,669 | 5,648,994 | Why is that the designer generated UI classes embedded as "Aggregation" can't implement custom slots? | I see that the designer generated UI classes be embedded using any of the following methods in Qt,
Aggregation as a pointer member
Aggregation
Multiple, Private inheritance
but it is said that the second method doesn't support custom slots. Can someone elaborate on this? Why can't we implement custom slots, while us... | I don't think it's true that the second option doesn't support custom slots.
The choice is discussed in the official Qt documentation. See http://doc.qt.io/qt-4.8/designer-using-a-ui-file.html#compile-time-form-processing
However, note that the three approaches presented in this document do not correspond to the three ... |
5,590,849 | 5,591,390 | Why is this rvalue call ambiguous? | Why is this rvalue call ambiguous? I can have AA and AA& and the compiler will know to use AA&. But when i add in the third option i get an error. Obviously AA&& is a better overload then the others like int for an int is better then long. Why is this ambiguous? Is there a way i can keep all 3 overloads and make it cle... |
I can have AA and AA& and the compiler
will know to use AA&
Yes, in the case of movetest(AA());, only movetest(AA) is viable, because a (lvalue) reference to non-const cannot be bound to an rvalue. However, an rvalue reference is said to bind directly to a temporary. Thus, for overload resolution purposes the funct... |
5,590,926 | 5,591,024 | How would you write a program to reduce an equation? | I may be misinterpreting the exact phrasing on the question about which I've been thinking, but I'm curious as to how one would reduce an equation of multiple variables.
I'm assuming factoring plays a major role, however the only way I can think of doing it is to break the equation into a tree of operations and search ... | I would assume that the kind of reductions that they are looking for is that something like (2 + 3) * x should become (* 5 x) rather than (* (+ 2 3) x). In which case you can just recognize that subtrees are constant, and calculate them.
You can also use the associative and commutative laws to try to move things aroun... |
5,590,978 | 5,591,006 | Reference of Reference in C++ | I see code on StackOverflow every once in a while, asking about some overload ambiguity with something involving a function like:
void foo(int&& param);
My question is: Why does this even come up? Or rather, when would you ever have "a reference to a reference"? How is that any different from a plain old reference? I'... | It's a rvalue reference, Bjarne describes it here.
Shameless copying ("quoting"):
The rvalue reference
An rvalue reference is a compound type
very similar to C++'s traditional
reference. To better distinguish these
two types, we refer to a traditional
C++ reference as an lvalue reference.
When the term refer... |
5,590,983 | 5,591,031 | Problem occurred while compiling a cpp program in gcc | My code is
#include<iostream>
using namespace std;
int main()
{
cout <<"hi";
return 0;
}
I compile it with:
gcc d.cpp -o d
Error as follows
Undefined first referenced
symbol in file
std::basic_string<char, std::char_traits<char>, std::alloca... | g++ d.cpp -o d
Should use g++ for a c++ program compilation to link to C++ standard library.
|
5,591,183 | 5,591,231 | How make child process with same environment variables as parrent plus it's own in windows? | In windows for creating new child proccess I'm using CreateProcess function:
BOOL WINAPI CreateProcess(
__in_opt LPCTSTR lpApplicationName,
__inout_opt LPTSTR lpCommandLine,
__in_opt LPSECURITY_ATTRIBUTES lpProcessAttributes,
__in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes,
__in BOOL bI... | use getenv to get crt env add your own and set
|
5,591,293 | 5,591,299 | c++ maximum std::string length is dictated by stack size or heap size? | as asked in the question.
std::string myVar; the maximum character it can hold is dictated by stack or heap?
Thank you
| By default, the memory allocated for std::string is allocated dynamically.
Note that std::string has a max_size() function returning the maximum number of character supported by the implementation. The usefulness of this is questionable, though, as it's a implementation maximum, and doesn't take into consideration othe... |
5,591,492 | 5,591,709 | Array initialization with {0}, {0,}? | Say I want to initialize myArray
char myArray[MAX] = {0};
char myArray[MAX] = {0,};
char myArray[MAX]; memset(myArray, 0, MAX);
Are they all equal or any preferred over another?
Thank you
| They are equivalent regarding the generated code (at least in optimised builds) because when an array is initialised with {0} syntax, all values that are not explicitly specified are implicitly initialised with 0, and the compiler will know enough to insert a call to memset.
The only difference is thus stylistic. The c... |
5,591,546 | 5,591,780 | Referencing a struct declared in a template class | Alright, been at C++ for about 2 days now. Just done javascript before...
I'm making a template queue using a linked list. My compiler does not like it when I try to make a new Node struct from withink queue.cpp
//queue.h:
template <class Object>
class Queue
{
public:
Queue(); // Defau... | Inside member functions of Queue, you can refer directly to Node.
front = back = new Node; //this is line 26
and
Node * ptr = original.front->next;
What you have inside the loop will also work, where you explicitly specify the template parameters. However, note that since Node is private, unless you m... |
5,591,695 | 5,592,494 | Are there variations in the C++ STL standard? | I have always been religiously using SGI's Standard Template Library Programmer's Guide (STLPG) as a reference manual whenever I implement something in C++ using the STL. Up until yesterday it has never failed me but yesterday I was working with std::vector at work and was pair programming with a colleague of mine who ... | I usually use the C++ Reference, mainly because its Googles first hit if you search for something like c++ std vector. But I have also found the information presented there accurate.
When in doubt I reference the latest working draft of the C++ Standard. (e.g. to answer your initial question chapter 23.3.6 [vector]) Of... |
5,591,763 | 5,591,931 | Overloading subscript operator and working with double-pointers? | I have the following variable that I need to work with, and have to write my own wrapper around it for an assignment. I am going beyond the assignment (since I am going to have to use this wrapper I make) and wanting to overload the subscript operator in my wrapper in order to use it with the double pointer array. What... | It's not clear why you are using double indirection in the first place.
If pixels is a double pointer to an array of pixels, you can do
pixels& MyWrapper::operator[] (const int nIndex) {
return (*Image.pixels)[nIndex]; // where Image is of type image
}
If pixels is a pointer to an array of pointers to arrays, then... |
5,591,846 | 5,592,898 | Avoid linking in unused symbols when linking against static libs | I'm using the apple gcc to compile a dylib that I'm going to redistribute. For various reasons I'm using some libraries, let's say libz to keep it simple.
Since this library is not typically found on a Mac system I wish to static link in used symbols into the dylib by passing the path to the .a-file to simplify deploym... | Try -Wl,--gc-sections.
As regards -dead_strip (what you probably meant by -dead_code):
Before turning on the -dead_strip
option your project will first have to
be "ported" to work with dead code
stripping. This will include changing
from -gused (the default for -g) to
-gfull and re-compiling all of the objec... |
5,591,994 | 5,592,047 | Mental model for void* and void**? | Note: I'm a experienced C++ programmer, so I don't need any pointer basics. It's just that I never worked with void** and have kind of a hard time getting my mental model adjusted to void* vs. void**. I am hoping someone can explain this in a good way, so that I can remember the semantics more easily.
Consider the foll... | void* is a pointer to something, but you don't know what. Because you don't know what it is, you don't know how much room it takes up, so you can't increment the pointer.
void** is a pointer to void*, so it's a pointer to a pointer. We know how much room pointers take up, so we can increment the void** pointer to point... |
5,592,027 | 5,593,747 | Passing arrays/pointers as template parameters | I'm trying to create a template function of the following sort:
template <bool isHorizontal, float* kernel>
__global__ void smoothFilterColumns(const TwImageCUDA_Device* source, TwImageCUDA_Device*
destination)
{
// code...
}
(Don't worry about the __global__; this is being implemented on CUDA.)
Unfortunately, it won... | I doubt you will get that to work. As others point out, the C++ standard says that any object or function passed as a template parameter must have external linkage (so not defined at the scope of the current translation unit). The problem is that CUDA doesn't current support external linkage at all - every symbol used ... |
5,592,223 | 5,592,327 | adjust width on c++ program | How can i adjust width on the window of a c++ program so when the user runs the program,it will automatically be at the desirable width.
Thanks
| This adjusts the console on windows.
COORD s = { 120, 2000 };
SMALL_RECT sr = { 0, 0, 119, 49 };
CONSOLE_SCREEN_BUFFER_INFO sbi = { 0 };
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &sbi);
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), s);
if ( (sbi.srWindow.Right - sbi.srWindow.Left) != (sr... |
5,592,231 | 5,592,880 | How to write the content of different files to a vector for further use with getline | I want to save the content of different files to a vector:
Vector(0) = Content File1
Vector(1) = Content File2
...
Later on I need to read out from each index of this vector line by line (getline):
getline(Vector(0), string myString)
As I read on different sites, I can't use vector<istream> myVector.
So how can I solv... | It depends on the size of the data you want to manipulate. My two samples has been tested.
You can use a class which handles some raw pointers
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
class file_vector
{
public:
file_vector()
{}
virtual ~file_vector()
{
for( std::vector<... |
5,592,242 | 5,592,278 | Qt - What to use for a text box | I'm new to Qt, and just want to ask. What should I use to make a text box?
Thanks.
| If with text box you mean it one line then it should be QLineEdit.
Anyway I suggest you to get a look at some full working samples to learn using all available widgets.
|
5,592,478 | 5,642,662 | Visual Studio 2010 conversion of 2005 solutions (C++ projects) loses project dependencies | I am trying to convert one rather huge VS2005 solution with many C++ projects to VS2010. After automatic conversion I can see that some of the dependencies between the projects were lost and thus my VS2010 builds fail unless I manually re-add the dependencies.
Has anybody seen this behaviour?
Is there a fix for this?
... | VS2010 project conversion is fraught. And if you haven't applied VS2010 Service Pack 1 you will almost certainly be wasting your time.
Regarding project dependencies (you might not like this): MSBuild 4.0 (the VS2010 build agent) no longer looks in the solution file for project dependencies. Even if you managed to get ... |
5,592,540 | 5,592,577 | wdk ddk compiler problems with std::string and std::wstring | I've started playing around with the WDK / DDK (I'm assuming they're the same thing) samples and in particular the printer port monitor example. I've got this compiling using their build tool and I can attach to the spooler process and debug through... good stuff!
.. Problem comes when I simply want to write some debug... | std::string and std::wstring are C++ classes (actually typedefs for C++ classes), and you are compiling .c files.
Using the C++ runtime libraries in drivers feels a bit strange, I don't know if it works.
If you where to compile as C++ the include is <string> and not <string.h>.
|
5,592,583 | 5,592,685 | different mutex for push and pop | I have a class called 'subscribedQueue'. This class receives its data via its subscribed publishers (plural) calling its push method.
In another thread, this class's pop method is called to receive that data.
Thus in a sense this class is a kind of buffer between multiple publishers and their subscribers. For the imple... | Standard library containers aren't thread safe; If you attempt to modify a container from multiple threads simultaneously then bad things happen.
If you have a separate mutex for push and pop operations then you don't protect against a simultaneous push and pop from two threads, so you haven't really protected the coll... |
5,592,723 | 5,593,142 | Why do my doubles display as integers when I pass them to cout? | I have set of coordinates stored in a file. I extracted only the “x” coordinate of certain points and stored in a vector called:
vector<double> x_points;
Then, I need to get the values of minimum and maximum x coordinates inside that vector. So I used *max_element and *min_element by including <algorithm>;
double max_... | You print the values with the default precision, which is 6 digits. Exactly what you get!
Try adding a cout.precision(10); to get more digits.
|
5,592,847 | 5,593,044 | C++ generic programming subtleties | The problem I have is illustrated in the following code.
#include <iostream>
#define X 4
int main()
{
std::cout << "should be 4: " << X << std::endl;
#define Y X + 4
std::cout << "should be 8: " << Y << std::endl;
#undef Y
#define Y X+0
#undef X
#define X Y+1
std::cout << "expecting 5: " << X << std::e... | compiling with g++ -E gives this:
int main()
{
std::cout << "should be 4: " << 4 << std::endl;
std::cout << "should be 8: " << 4 + 4 << std::endl;
std::cout << "expecting 5: " << X+0 +1 << std::endl;
}
So you can see why you get the error.
|
5,592,929 | 5,593,644 | Curious Recurring Template with Operators | I have this working on G++ but on Visual Studo 2008 this will not compile.
template<typename T, typename DerivedT >
struct Foo
{
template<typename Scale>
DerivedT operator * (const Scale i)
{
DerivedT result;
return result;
}
};
template<typename T>
struct Bar : public Foo<T, Bar<T> >
{ ... | I don't know how you managed to compile this by g++ (and I actually doubt that), but your code is indeed not compilable for rather obvious reasons. Your Bar class exposes only one operator *
Bar& operator * (const Bar& boo)
and that operator expects a Bar object as a right-hand size operand. 3 will not work, 3 is not... |
5,593,035 | 5,593,190 | fastest way to wake up a thread without using condition variable | I am trying to speed up a piece of code by having background threads already setup to solve one specific task. When it is time to solve my task I would like to wake up these threads, do the job and block them again waiting for the next task. The task is always the same.
I tried using condition variables (and mutex that... | These functions should be fast. If they are taking a large fraction of your time, it is quite possible that you are trying to switch threads too often.
Try buffering up a work queue, and send the signal once a significant amount of work has accumulated.
If this is impossible due to dependencies between the tasks, then ... |
5,593,106 | 5,593,488 | Inheritance Error "Base Class Unidentified" | I have a State class that is fully implemented as outlined below. I also have a PlayState class that inherits the State class, it too is fully implemented. My compile error is "playstate.h(6): error C2504: 'State' : base class undefined"
I have checked their order in Global.h, State.h appears before PlayState.h
CODE:
S... | If some *.cpp includes "State.h" without "Global.h" somewhere before it then you will have the error that you've posted.
Because when "State.h" includes "Global.h" then "Global.h" does not include "State.h" (because of #pragma once) but it includes "PlayState.h" so in the end you have "PlayState.h" included before clas... |
5,593,287 | 5,593,402 | Can you help me understand this C++ template code? | Hya,
Can anyone please tell me how this thing is working?
template <typename T,
template <typename ELEM> class CONT = std::deque >
class Stack {
private:
CONT<T> elems; // elements
public:
void push(T const&); // push element
void pop(); // pop element
T top() const; // return top element
bool empty() const { // retur... |
What i don't understand is this : template class V
There is no such line in your question, so I can't help with that.
template< template <typename ELEM> class CONT = std::deque >
class Stack
This is a declaration of a template template parameter. You pass a template into the Stack template, and then Stack can use it... |
5,593,341 | 5,593,441 | How fast is the code | I'm developing game. I store my game-objects in this map:
std::map<std::string, Object*> mObjects;
std::string is a key/name of object to find further in code. It's very easy to point some objects, like: mObjects["Player"] = .... But I'm afraid it's to slow due to allocation of std::string in each searching in that ma... | Calculating a CRC is sure to be slower than any single comparison of strings, but you can expect to do about log2N comparisons before finding the key (e.g. 10 comparisons for 1000 keys), so it depends on the size of your map. CRC can also result in collisions, so it's error prone (you could detect collisions relativel... |
5,593,595 | 5,594,642 | How to stub/mock Qt classes? | I am new to testing and TDD but decided to give it a try and learn. Currently I am trying to develop a class SettingsManager that would handle settings of my app. It would store app's state and when it closes SettingsManager will save the state using QSettings (and read when started). Now I want to mock QSettings so I ... | I think you are unit testing QSettings, but that is not a point of unit testing.
If you want to learn TDD, start with something simpler. For example, try to create a MVP triad of classes (model and presenter should have interfaces, while view is a qt class type). Then fully unit test model and presenter. The view shoul... |
5,594,360 | 5,594,390 | How to find first duplicate item in a vector - C++? | I have a vector with different values and some of them may appear twice. (Only twice.)
How can I find the FIRST duplicate item?
Like: [a][b][b][a]
Then I'd need 'b'.
(Sorry for the newbie question.)
| If you're looking for adjacent duplicates, you can simply use std::adjacent_find.
If the duplicates aren't necessarily adjacent, then you could first std::sort the vector, and then use std::adjacent_find on the result. (See @aix's comment below)
Alternatively, you could push each element into a std::set, and look for c... |
5,594,656 | 5,594,681 | can boost::bind be used with references without copying? | Following code shows that the parameter, passed by reference, is copied when using boost::bind. Is there a way to prevent the copying without resorting to pointers (which I currently use as workaround)? (tested with gcc 4.4.3)
#include <iostream>
#include <boost/function.hpp>
#include <boost/bind.hpp>
void function1... | You should use boost::ref for passing references to boost bind.
boost::function<void()> f = boost::bind(function1, boost::ref(y));
|
5,594,684 | 5,594,847 | compute a vector which is perpendicular to another given vector (all are in 3D) | I have a vector v1 (suppose v1= a1,b2,c1) and this v1 passes through the point x1,y1,z1. Now I need a second vector, v2 which is perpendicular to the v1. Suppose that v2 is passing through the second point x2,y2,z2.
However, my final goal is to find the intersection point of above two lines. So, could you help me to ... | Your question is confusing, do you want to find the point of intersection or do you want a perpendicular vector?
There's an infinite amount of vectors that are perpendicular to your given vector. If you want just any of those, turn your v1 vector by 90 degrees: v2 = (-y1, x1, z1).
As for the line crossing, take into ac... |
5,594,686 | 5,594,728 | GCC STL bound checking | How do I enable bound checking for operator[] and iterators?
| You can activate runtime iterator and bounds checking by compiling with -D_GLIBCXX_DEBUG. Also note that random-access containers provide the always bounds-checking at()-operation in addition to operator [].
References:
GCC STL debug mode:
http://gcc.gnu.org/onlinedocs/libstdc++/manual/debug_mode_using.html#debug_mode... |
5,594,763 | 5,594,869 | Sending C# struct to C++ through a socket | I want to send a struct in C# to C++ using sockets.
For example, I use this struct:
[StructLayout(LayoutKind.sequential, Pack = 1)]
struct pos {
public int i;
public float x;
};
If I somehow convert it into bytes and send over the network, I should be able to cast it to this in c++:
struct pos {
int i;
... | The marshaller helps you with converting between .NET structs and raw bytes. In this answer, I posted a simple solution, which boils down to Marshal.StructureToPtr and Marshal.PtrToStructure. In contrast to the more advanced solutions provided by Johann du Toit, this is in my opinion the best thing you can do if all yo... |
5,594,769 | 5,599,509 | Normal (desktop) user-interface controls with QML? | I'm currently porting one of my applications to C++ with QT as a GUI.
The QML-samples look pretty darn good, but the user-interface controls don't look like the normal ones on Windows and MacOS.
I would like to use the many cool features QML offers (like animations), but also have controls which look similar to the nor... | Hedge, there are 2 reasons why your UI didn't look native:
1) Qt Quick (QML) now is in a stage when only basic primitives are available. That means there are no actual UI elements (like Button, Tool Bar, etc.) available yet. There are just some of them like list views which are included in the basic set of components. ... |
5,594,888 | 5,594,892 | how to declare a member of a class type defined in a different file | I have a header file in which I have defined a struct. I want an instance of this struct to be a member of a class that is defined in a different file. How do I do it?
| #include the header containing the struct in the header where you define the class.
Foo.h:
struct Foo {
};
Bar.h:
#include "Foo.h"
class Bar {
Foo f;
};
|
5,595,091 | 5,595,320 | using strings as a pointer to its first character | int main()
{
char name[]="avinash";
const char* nameano="a";
strtok(name,"n");
cout<<"the size of name is"<< sizeof(name);
cout<< name;
}
strtok takes in arguments (char*, const char*); name is an array, and hence a pointer to its first element. But if we make a declaration like
stri... | You are confusing several things.
strtok takes in arguments (char*, const char*)....name is an array and hence a pointer to its first element...
name is an array, and it's not a pointer to its first element. An array decays in a pointer to its first argument in several contexts, but in principle it's a completely dif... |
5,595,284 | 5,595,885 | C++: what does "T const *[]" mean? |
what does "T const *[]" as parameter
type mean?
What's the difference
compared to "T *[]"?
And as last
question: why can't I pass a "T *[]"
to a function that requires a "T
const * []" as parameter?
Thank you for your help.
Tobias
| As a type in general, it's an array of pointers to a constant T.
Try putting a name in it:
T const *x[];
and apply the usual rules: [] binds tighter than *, so it's an
array. Then the * means that its an array of pointers, and
finally, they all point to a constant T. (As usual, const
modifies whatever is to the left... |
5,595,300 | 5,597,126 | How to draw transparent rubberband on OpenGL scene | i'm using OpenGL for showing grabbed frames from video camera with texture mapping. There is no problem at all but i have to select some region of the grabbed frame then i have to zoom it, first of all i can't draw a Rubber rectangle it must be transparent when i select the some region of grabbed frame i have to see te... | Just draw a translucent (alpha < 1.0) rectangle:
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glColor4ub(255, 255, 255, 128);
glRectf(x1, y1, x2, y2);
glDisable(GL_BLEND);
|
5,595,390 | 5,599,396 | h.264 training of parsing | I'm trying to understand process of parsing h.264 NAL units (to extract information about slices, macroblocks etc.), so I'm writing simple bit stream parser for h.264
Are there any example (training) files, which, for example, contains single NAL unit or single slice?
Does anybody knows where I can get such training da... | If you want training data, you can download the H.264 reference software from http://iphome.hhi.de/suehring/tml/download/. Note that this reference software is written in c++ though. You don't need to be well versed in c++ though, you do need to be able to build the encoder and then you can use it as a tool to generate... |
5,595,517 | 5,595,640 | Properties of the modulo operation | I have the compute the sum S = (a*x + b*y + c) % N. Yes it looks like a quadratic equation but it is not because the x and y have some properties and have to be calculated using some recurrence relations. Because the sum exceeds even the limits of unsigned long long I want to know how could I compute that sum using the... | a % N = x means that for some integers 0 <= x < N and m: m * N + x = a.
You can simply deduce then that if a % N = x and b % N = y then
(a + b) % N =
= (m * N + x + l * N + y) % N =
= ((m + l) * N + x + y) % N =
= (x + y) % N =
= (a % N + b % N) % N.
We know that 0 < x + y < 2N, that is why you need to keep remainder... |
5,595,845 | 5,595,945 | Conversion from C++ to Java(Returning more than one value in java) | Not getting the char value:
#define XL 33
#define OR 113
#define NOR 313
#define TN 344
int to_bits(int critn,char *mask)
{
unsigned int x;
int begin;
if (critn < XL) begin = 1;
else if (critn < OR) begin = XL;
else if (critn < NOR) begin = OR;
else if (critn <= TN) begin = NOR;
else begin = 0;
x = crit... | Are you asking if you can output the mask as binary?
If so, this will do the job:
System.out.println(Integer.toBinaryString(mask));
or in hexadecimal:
System.out.println(Integer.toHexString(mask));
(EDIT - I previously said to use Integer.toString(mask, 2 /* or 16 */), but that formats the number as signed ..... |
5,595,913 | 5,596,660 | How do I prevent my MFC dialog's window from closing using CPropertyPage::OnOk()? | I'm working on a C++ project and have a CPropertyPage::OnOk() method.
What I'd like to happen is when the user clicks Ok or Apply, the program will perform a check, if the check is wrong, it'll supress the window from closing.
How would I go about to supressing the window from closing?
I've tried a simple return but no... | Used the following to check if value A > value B then return 0 to stop from closing!
BOOL CApptEditGen::OnKillActive()
{
CString inpValue;
m_pCtl_ApptEdit_Units->GetWindowText(inpValue);
if (atoi(inpValue) > freeUnitsAvailable)
return 0;
return CPropertyPage::OnKillActive();
}
|
5,596,204 | 5,596,237 | Very basic volume rendering using OpenGL functions (for teaching purposes) | I have some students doing a project on volume rendering. I am trying to devise the most basic possible example to get them started. What I want to do is have a window and set each pixel in the window independently, based on raycasts through the underlying volume dataset. This could easily be done with Windows API fun... | The first option, pixel by pixel will be really slow! I would suggest you to create a RGB buffer with the same size as the window and use glDrawPixels to draw it.
EDIT:
unsigned char * buffer = new unsigned char [width * height * 3];
glRasterPos(0,0);
glDrawPixels(width,height,GL_RGB,GL_UNSIGNED_BYTE,buffer);
delete []... |
5,596,403 | 5,597,567 | Implement Quick sort algorithm with partition of 3 elements, | How to convert this Quick sort algorithm into partition of 3 ,5,7,9 and 11 elements?
#include"stdafx.h"
#include<iostream>
using namespace std;
#include <stdio.h>
#include <stdlib.h>
#define size 50
void swap(int *x,int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
int partition(int i,int j )
{
return((i+j) /2);
}
... | I think your C++ teacher simply has a poor choice of wording. "partition of 3 elements" almost certainly means: choose the pivot element by picking the median of the first, middle and last elements -- this is the most common coding technique and has good properties when the array is already sorted.
Extrapolate that de... |
5,596,428 | 5,596,455 | sizeof(struct) returns unexpected value | This should be simple but I have no clue where to look for the issue:
I have a struct:
struct region
{
public:
long long int x;
long long int y;
long long int width;
long long int height;
unsigned char scale;
};
When I do sizeof(region) it gives me 40 when I am expecting 33.
Any ideas?
(mingw gcc, ... | It's padding the struct to fit an 8-byte boundary. So it actually is taking 40 bytes in memory - sizeof is returning the correct value.
If you want it to only take 33 bytes then specify the packed attribute:
struct region
{
public:
long long int x;
long long int y;
long long int width;
long long int hei... |
5,596,490 | 5,596,647 | GetThreadtimes gives strange results |
I'm monitoring a thread using GetThreadTimes every 5 microsec (more or less)
That thread is "Sleeping" for 1 minute but for some reason sometimes the "User Time" I get from GetThreadTimes changes, even though the thread is still in sleep mode.
Kernel time is always 0.
Does anybody know why it happens?
thanks :)
| It is not complete answer, but anyway here is at least 2 reasons:
There is well known problem "Thread priority inversion", for details see link, but very useful technique to resolve problem is random boosting threads. So, there is possibility that thread gets some processor time.
Thread sleeping can be implemented as ... |
5,596,790 | 5,596,825 | Clearing out Function Hiding compiler warnings in C++ | I'm getting "hiding" warnings in my compiler because a class inherits from its parent has the same name but different parameters.
Adding a function that merely pushes out a warning to say that this function does nothing (as is true in the base class, but without the warning) that matches the parameters and name of the ... | The inability of your users to access the base class function through a derived instance without explicitly writing out myDerivedObj.Base::foo(), which they're not likely to do.
Make your function signatures match up, instead, or change the function name.
|
5,596,805 | 5,597,202 | OpenCV detect if points lie along line/plane | I am working on a form of autocalibration for an optics device which is currently performed manually. The first part of the calibration is to determine whether a light beam has illuminated the set of 'calibration' points.
I am using OpenCV and have thresholded and cropped the image to leave only the possible relevant p... | Obtain the x,y coordinates of the thresholded points, then perform a linear regression to find a best-fit line. With that line, you can determine the r^2 value which effectively gives you the quality of fit. Based on that fitness measure, you can determine your calibration success.
Here is a good discussion.
|
5,596,812 | 5,596,903 | Visual Studio Compiler is highlighting Static variables differently? | I'm programming in C++ and have a method which uses a static variable. The method isn't working as I think it should; upon investigation, I found that my static variable is being highlighted in red in two places and blue in other places. Below is the code:
int GameModeState::changeJob(int number)
{
static int job =... | Part of the problem here is you're using a static local for what very likely should just be a member variable. A static local maintains it's value across all calls to a function in all threads in a process. It's much more likely that you want it to persist for all calls to changeJob in a particular GameModeState inst... |
5,596,841 | 5,597,256 | Print with GDI+ has no effect | I added GDI+ to my Win32 Application for drawing gradients quite a while ago. I worked around some problems considering mixed GDI and GDI+ output and everything works fine.
Now i started to use GDI+ also for printing, but all calls to GDI+ seem to be ignored, that work fine on screen. I double checked that there is no ... | I recently had a similar problem - creating a Graphics object from a DC applied a scaling factor that wasn't obvious, and my stuff was all rendering off the page. Fixing it was a simple one-liner:
graphics.SetPageUnit(UnitPixel);
|
5,596,854 | 5,604,139 | libxml accessing content of node cause application exit | I'm a beginner with libxml and I encounter a strange behaviour :
When I try to access to the content of and xmlNode, the application exits silently.
My code :
// Initialisation des pointeurs
xmlDocPtr doc;
xmlXPathContextPtr xpath_context;
xmlXPathObjectPtr xpath_objects;
// Chargement du document et création du conte... | In fact, as Luke says, for libxml, the content of an xmlNode is an another node.
So we have to access to the children to read the content of the selected node.
In my case, the solution is :
cout << "Valeur de la balise : " << (char*)(xpath_objects->nodesetval->nodeTab[0]->children->content) << "\n";
Thank you Luke.
|
5,596,905 | 5,597,092 | What to pass as the ColumnSize argument of ODBC SQLBindParameter in a C/C++ program? | I am learning how to use the SQLBindParameter function. I was going through a couple of examples on the Internet and it is not clear what I should be passing as the 6th argument to the SQLBindParameter function.
The example at http://msdn.microsoft.com/en-us/library/ms710963(v=vs.85).aspx passes the size of the charact... | This is to help determine the byte size of the parameter for certain types it's ignored for others.
Say you had a SQLCHAR[10] parameter you would pass 10 in as the column size:
SQLCHAR empStr[10];
SQLINTEGER len = SQL_NTS;
retcode = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, 10, 0, empStr, 0, &le... |
5,597,064 | 5,606,639 | How to convert c++ Variant to JSON? | How can I convert Variant to Java script object notation in (windows) c++?
I have a piece of hardware that returns a Variant which can contain an array(float), string or boolean data. All of variant contents should be easily converted to JSON, but is there a JSON library that does this out-of-the-box for variant? Or..... | I think you need to write this conversion manually. I'm not awarer of anything that could translate VARIANT to json or jsoncpp Value class. So just create switch that check VARTYPE vt; element of VARIANT and base on that convert it to for example jsoncpp Value. Probably you don't need to convert every type of VARIANT t... |
5,597,104 | 5,597,147 | Parse Website Data in C++ | So I am trying to develop a program that will parse a website for data, send that data into variable that I can then use for functions inside the program.
Specifically I'm trying to parse this page (Click the debuffs tab)
http://worldoflogs.com/reports/rt-1smdoscr7neq0k6b/spell/94075/
The source is pretty simple and ... | I'd look into Tag Soup. It's a parser for HTML that can cope with all the horrible HTML that's out there. There's a C++ port of it available too (haven't used that so can't comment on how stable it is).
|
5,597,337 | 5,597,496 | Save data periodically during execution | I have a program which executes constantly and I need to save data every minute.
The program process data and every minute I want to save the value of a variable and do some statistical operations to know the variation of this variable.
I thought i can make it with a signal, SIGALRM and alarm(60). My subquestion is, ca... | Your solution using alarm will work, both open and write being asynchronous-signal-safe. Though you have to be aware that interactions between alarm and sleep are undefined, so don't use them in the same program.
A different solution, especially in case you already use an epoll, would be to have a timerfd trigger the e... |
5,597,450 | 5,600,641 | Providing c++ iterators for a legacy C linked-list interface | I have a Visual Studo 2008 C++ application where I am trying to add iterator support to a legacy C-API's linked-list structure. The C interface looks like this:
typedef struct _LINKED_LIST_INFO {
struct _LINKED_LIST_INFO* Next;
const char* name;
// more elements. some are fixed-size; others are pointers to... | This is horrible (you should not do this) :
class MyInfo {
char* name() const {
return ((_LINKED_LIST_INFO*)this)->name;
}
};
class MyInfoIterator
: public std::iterator< std::input_iterator_tag, MyInfo>
{
_LINKED_LIST_INFO* p;
public:
MyInfoIterator(LINKED_LIST_INFO* pointer) : p(pointer) {}
... |
5,597,532 | 5,597,584 | Sorting an array fail | I'm trying to sort an array made of random numbers from 1 to 10 in an ascending order. I've come up with this function:
void Sort(int a[10], int n)
{
int j = 0;
for (int i = 0; i < n-1; i++)
{
j = i+1;
if (a[i] > a[j])
{
int aux = a[i];
a[i] = a[j];
... | The algorithm in your Sort function is wrong. It doesn't sort at all.
Anyway, don't reinvent the wheel, better use std::sort as:
#include <algorithm>
std::sort(array, array+10);
As for your Sort function, which you want to implement using bubble-sort algorithm, possibly for learning purpose. the correct implementati... |
5,597,812 | 5,598,034 | How do I change the font of a specific item in a CListBox/CComboBox | I have a CComboBox-derived class with a subclassed CListBox. I would like to make the first two item in the CListBox bold. How can I accomplish this?
| You need an owner-draw listbox, and override DrawItem() to draw the items. For the first two, you can use a different font than the rest.
|
5,598,173 | 5,598,856 | Flexible Array Members on iOS in Objective-C++ | I am working on some core audio code and have a problem that could be solved by a variable array in a struct--a la Flexible Array Members. In doing a bit of looking around, I see that there is a lot of dialogue about the portability and viability of Flexible Member Arrays.
From what I understand, Objective-C is C99 com... | don't bother. it's not compatible. it is messy and error prone. c++ had solutions which are managed more easily long before this feature existed. what are you tacking onto the end of your struct? normally, you'll just use something like a std::vector, std::array, or fixed size array.
UPDATE
I want to have a list of no... |
5,598,487 | 5,598,598 | Qt - iterating through QRadioButtons | I have a group project for school that I am working on. A member of my group has created a window that has ~75 radio buttons. I want to force all of them to be "clear" or "unchecked" on a button press.
Does anyone know a good way to go about doing this? I have been looking into QObjectList but I can't simply do ... | Use a QButtonGroup, set it to exclusive (then only one radiobutton will be checked at a time). It also gives you the currently checked button, in case you want to uncheck it, too. (to have no checked buttons at all).
Also note that what you probably want to modify is the "checked" property, not "checkable" (where false... |
5,598,591 | 5,598,621 | C++ Encapsulating arrays | Sorry if this has been asked before, but I can't find a clear enough answer.
What is the correct way to provide public read-only access to an array member in C++?
if i have a class like the following:
class Particle
{
double _position[10];
public:
double* get_position()
{
return _position;
... | You can return a const pointer:
class Particle
{
double _position[10];
public:
const double* get_position() const
{
return _position;
}
};
Note that I've also made the member-function const (the second const), to tell the compiler that this member-function may be called on const Particle instan... |
5,598,703 | 5,598,730 | C++ Const Usage Explanation | const int* const Method3(const int* const&) const;
Can someone explain the usage of each of the const?
| Read this: https://isocpp.org/wiki/faq/const-correctness
The final const means that the function Method3 does not modify the non mutable members of its class.
const int* const means a constant pointer to a constant int: i.e. a pointer that cannot be changed, to an int that cannot be changed: the only difference between... |
5,598,782 | 5,600,393 | Building shared library with Eclipse CDT directly | I would like to move the building of my C++ project completely to Eclipse CDT, however I am facing some configuration problems. Here is my old g++ compiler call:
g++ -I/home/lib/tinyxml
-I/usr/lib/jvm/java-6-openjdk/include
-L/usr/local/lib -L/home/konrad/tinyxml
-lboost_system
-lboost_thread
-lboos... |
That's not a problem, but actually how makefiles usually are constructed. This way, if you change one source file, you don't have to recompile all other source files, but only the one that has changed. It minimizes recompilation time.
That shouldn't be a problem, because they are options that are only used during link... |
5,598,825 | 5,599,261 | What container to choose | I thought about storing some objects ... and now I don't know what to choose.
So, now I have such code:
std::map<std::string, Object*> mObjects;
But, as I was told here before, it's slow due to allocation of std::string in each searching, so the key should be integer.
Why did I chose std::string as key? Because it's ... | I can't say for sure, but are you always accessing items in the map by a literal string? If so, then you should just use consecutive enumerated values with symbolic names, and an appropriately sized vector.
Assuming that you won't know the names until runtime 1000 items in the map seems really small for searching to po... |
5,598,890 | 5,599,105 | Boost Equivalent for Windows Events | In windows c++ I can create a handle to event
Handle h = CreateEvent(...)
I can then set and reset that event
SetEvent(...) and ResetEvent(...)
Finally, I can OpenEvents using the command OpenEvent(...)
Is there a boost equivelent for events?
| I think you need to use boost::mutex, boost::unique_lock, boost::condition_variable and possibly bool in order to imitate Events.
You actually might need sort of WaitForSingleObject in order to wait for an event. Might be like this:
void wait_for_user_input()
{
boost::unique_lock<boost::mutex> lock(mut);
while(... |
5,598,995 | 5,600,791 | DeactivateDevice vs. IOCTL_BUS_DEACTIVATE_CHILD | I am trying to understand the pros and cons of using DeactivateDevice vs. IOCTL_BUS_DEACTIVATE_CHILD, to unload a device driver, in terms of power consumption. If I would like to check the power consumption of the device when the driver was 1)loaded and 2)unloaded, which one would give me the most appropriate value in ... | It depends on what you want to do. IOCTL_BUS_ACTIVATE_CHILD is for bus drivers only (USB, PCI, etc...). upper level client drivers will use ActivateDeviceEx.
There is no equivalent wrapper function in the DDK for IOCTL_BUS_ACTIVATE_CHILD.
see: http://blogs.msdn.com/b/ce_base/archive/2007/04/19/how-bus-drivers-work.asp... |
5,599,302 | 5,599,323 | boost::asio async_write complex structure | Whats the best way to send a complex structure using boost's asio async_write... Any suggestions?
Thanks!
| You'll need to serialize the structure, some options include
Boost.Serialization
Google Protocol Buffers
I've answered several similar questions when using Boost.Serialization with Boost.Asio, here is one that may be useful to you.
|
5,599,382 | 6,865,449 | Trouble running a very simple Hello World JNI test | EDIT3: It is defiantly the compiler flags causing the problem, if I compile from the command line using Microsoft's compiler it works fine. Does anyone know what I need to change in code::blocks to fix this issue?
When I run my code I am getting a UnsatisfiedLinkError. The load step works fine, i am getting the error w... | I ended up just compiling by hand using the Microsoft's compiler.
|
5,599,498 | 5,599,670 | issues with for loops in lambdas | I am currently rewriting a small project i written some time ago, and am replacing function pointers with std::function and lambdas.
While doing this i stumbled over an issue with for loops in lambdas.
in Visual Studio 2010 (with SP1) generates strange errors when for loops are used inside lambdas, IF the lambda is def... | I can verify this behavior on Visual Studio 2010 RTM. It appears to be limited to just for loops as the following compiles just fine.
auto print_sum =
[](int n)
{
int sum=0;
int i = 1;
while (i <= n)
{
sum += i;
i++;
}
std::cout << sum <... |
5,599,561 | 5,599,701 | Variable user-defined parameter list in C++? | I'm looking for a simple way to create a user multi-parameter receiving function,
Here's some pseudo code
#include <iostream>
struct A {
int m_num;
};
void function(A* a, ...)
{
/* Pseudo-Code here */
for each parameter do
print a->m_num
end
}
int main()
{
A *a = new A();
A *b = new A(... | Old school plain C variadic arguments:
#include <cstdio>
#include <stdarg.h>
struct A {
A () : m_num (0) {}
A (int v) : m_num (v) {}
int m_num;
};
void function (A *a, ...)
{
va_list ap;
A *p = a;
va_start (ap, a);
while (p != NULL)
{
printf ("%d\n", p->m_num);
p = va_a... |
5,600,119 | 5,600,224 | c++ boost::asio::buffer and structures | Is there anyway to BASICALLY do the following:
#include <boost/asio.hpp>
struct testStruct{
int x;
int y;
};
int main(){
struct testStruct t;
boost::asio::buffer b;
b = boost::asio::buffer(t);
return 0;
}
Where it seems to fail is passing 't' into the buffer, 'b'.
| Use the scatter operation of more than a single buffer:
#include <boost/asio.hpp>
#include <vector>
struct testStruct{
int x;
int y;
};
int
main()
{
struct testStruct t;
t.x = 5;
t.y = 7;
std::vector<boost::asio::const_buffer> buffers;
buffers.push_back( boost::asio::buffer(&t.x, sizeof(... |
5,600,150 | 5,600,272 | C++ template instantiation with shared_ptr to const T | Suppose I have a class
template <typename T>
class A {
public:
template <typename V>
void f(std::tr1::shared_ptr<const std::vector<V> > v1,
std::tr1::shared_ptr<const std::vector<float> > v2) {}
};
The following does not compile:
A<string> a;
std::tr1::shared_ptr<std::vector<float> > v1(new std:... |
Why is template instantiation behaving so differently here?
A shared_ptr<T> is implicitly convertible to a shared_ptr<const T> via a converting constructor. Unfortunately, such conversions cannot be used during template argument deduction.
In order for argument deduction to succeed, the type of the argument has t... |
5,600,256 | 5,600,311 | Don't understand how this C++ method works, and want to do something similar | I'm trying to add another function to a large program I've been working on. It's a 3D game, and a lot of it was built before I got here. If I want to add something, I'll usually look for other places where something similar has been done and make my changes based off that. In this instance however the method I'm trying... | If I understand correctly what you are trying to do, then this should accomplish it:
class Action_SetJob : public Action {
public:
Action_SetJob() {}
void eval(const Dialog& dialog, State& state) const {
GameModeState::changeJob(newJob);
}
static Action* Create(const Script2::Parser::List& list... |
5,600,257 | 5,600,318 | Factoring/Refactoring a program | What does the term 'poorly factored' and 'refactoring' a program mean? Can you give a simple example to understand the basic difference ?
| Refactoring is a general technique that can refer to many tasks. It usually means cleaning up code, removing redundancy, improving code quality and readability.
A very simple example of poorly factored code:
do_task1("abc");
do_task2(123);
do_task3(7.43);
...
//100 lines later:
do_task1("abc");
do_task2(123);
do_task3(... |
5,600,288 | 5,600,368 | Change output directory of an Eclipse CDT project | I cannot find the possibility to change the output of the built files. The only I've found deactivates the whole generated makefile process, which I don't want to.
|
Right-click on your project and choose Properties.
Go under C/C++ Build, under Settings.
Click on the Build Artifact tab.
Under "Output prefix", enter the directory that you want to contain your built file (including a trailing slash).
It looks like you'll also need to modify your Run / Debug Settings with the update... |
5,600,515 | 5,601,157 | Qt: How to play sound witout blocking main thread? | I'm wondering is there a simple way in Qt to play sound without blocking the main thread ?
I know that normaly I should start a seperate thread to do this. But maybe there is a shortcut ? :)
Thanks for help.
| http://doc.qt.nokia.com/latest/qsound.html
Qt provides the most commonly required audio operation in GUI applications: asynchronously playing a sound file. This is most easily accomplished using the static play() function:
QSound::play("mysounds/bells.wav");
It seems like this is an asynchronous operation, so it sh... |
5,600,782 | 5,600,900 | boost serialization stringstream error | So...
Whenever I run the following:
#inlcude <iostream>
#include <sstream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
using namespace std;
class gps_position
{
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & a... | In main you populate ss1, then create a new std::stringstream called ss2 and try to read from that. How would you expect this to work? It's clear that ss2 contains no data.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.