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 |
|---|---|---|---|---|
7,042,014 | 23,442,347 | How do you make a pair vector out of two arrays and then sort by the first element of the pair using CUDA/Thrust? | Okay, this is going to be a mouthful.
I have a pointer to serialized 2D array, pointer arithmetic aside, I want to make a vector of pairs out of (essentially) two arrays(that I plan to get out of the 2D array). However, I need to use the Thrust library.
This is so that I can use thrust::sort() on the vector, based on t... | The original poster found a solution using thrust::sort_by_key as follows:
#include <thrust/sort.h>
...
const int N = 6;
int keys[N] = { 1, 4, 2, 8, 5, 7};
char values[N] = {'a', 'b', 'c', 'd', 'e', 'f'};
thrust::sort_by_key(keys, keys + N, values);
// keys is now { 1, 2, 4, 5, 7, ... |
7,042,161 | 7,042,515 | Why is ferror() returning EPERM when there is no space left on device - I would expect ENOSPC | I wrote a C++ application on linux using cstdio. It contains one function which should overwrite a whole device with random data. It is given a file name, creates blocks of random data in memory and writes them one after the other using fwrite() to the file.
If the device is full, the function should return. If there i... | ferror only tells you whether there was an error on the stream. To see what the error actually was, you have to examine errno.
perror examines errno which is why it prints the correct error message.
|
7,042,165 | 7,042,394 | Pattern consisting of numbers moving in clockwise direction around a rectangular shape (length and breadth decreasing each time) | I have written code for many patterns but unable to write for this..... not even getting any hint how to proceed.
I want to generate the following output:
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
...where the width and height of the rectangle are specified as inputs.
| I would do it this way:
Initialize a 5x5 two-dimensional array of integers to 0. Have a direction variable, and define constants or an enum for the four directions. Start moving 'right' from (0, 0), filling in the array with increasing values until you hit the edge or a number that is not 0. Then, increment the directi... |
7,042,564 | 7,043,375 | How to include a wxObjArray correctly? | I define a wxObjArray in my TMainFrame.h as follows:
#ifndef __TMainFrame__
#define __TMainFrame__
#include "MyApp_gui.h"
//// end generated include
#include "TRunThread.h"
#include <wx/dynarray.h>
class TMove;
WX_DECLARE_OBJARRAY(TMove, TMoveArray);
/* ...Class TMainFrame... */
/* ...Class TMove... */
#endif //... | You are going to need both WX_DECLARE_OBJARRAY and WX_DEFINE_OBJARRAY. The latter goes to an implementation file.
The reference has a full usage example and more comments.
And you might also just use std::vector.
|
7,042,578 | 7,042,709 | How to find an object with specific field values in a std::set? | I call a method which returns std::set<T> const& where T is a class type. What I'm trying to achieve is to check whether the set contains an object of type T with specific field values for an assertion in a automated test. This check should be done for multiple objects.
Here is a simple example:
Let the type T be Car s... | This depends on the implementation of T. Let's stick with your example of a class Car. Suppose that class looks something like this:
class Car {
public:
Car(std::string color, unsigned int number_of_doors,
unsigned int top_speed);
// getters for all these attributes
// implementation of operator< as... |
7,042,705 | 9,665,752 | cross-plattform use of a static .a-library on iOS and Android possible? (what about .so and .dylib ?) | I have created a static library (with extension .a) for iOS with Xcode.
These were my build-settings:
Architectures: armv6, armv7
Base SDK: iOS 4.3
Build Active Architecture Only: No
Supported Platforms: iphoneos, iphonesimulator
Valid Architectures: armv6, armv7
A check with lipo -info libassimp.a approves:
Architec... | You need to separately compile the library for Android platform. A simple example of compiling C-C++ sources for Android platform is given in the link below
http://tariqzubairy.wordpress.com/2012/03/09/arm-binaries-static-library-for-android/
For using the already pre-build version of any library on Android you just ne... |
7,042,760 | 7,042,898 | Negative square root | How do you take the square root of a negative number in C++?I know it should return a real and a complex part, I get a NaN?How do I take the real part?
| #include <complex>
int main()
{
std::complex<double> two_i = std::sqrt(std::complex<double>(-4));
}
or just
std::complex<double> sqrt_minus_x(0, std::sqrt(std::abs(x)));
|
7,042,798 | 7,042,945 | Dynamic nesting in c++? | I have a list of list . All elements will be inserted at run-time. i wish to try all combinations through all list. So the simple solution comes to mind as
for ( l1 in L1)
{ for ( l2 in L2)
{ for ( l3 in L3)
{
... // use the pair (l1,l2,l3)
}
}
}
But i dont know t... | Use recursion.
typedef std::list<std::list<int>> ListOfList;
void actOnHelper(ListOfList::const_iterator c, ListOfList::const_iterator end, std::list<int> v)
{
if (c == e) {
// do something on v
} else {
ListOfList::const_iterator nextc(c);
++nextc;
for (std::list<int>::const_iterator i =... |
7,042,858 | 7,043,195 | What is the precedence of the meta-operator ...? | What is the precedence of the meta-operator ... whose job is to unpack template type parameter packs? I imagine it's pretty low, but how low is it? The C++ standard says:
The precedence of operators is not directly specified, but it can be derived from the syntax.
Anyone up for the challenge? Of course, ... does not ... | It doesn't seem to be an operator. From N3092 (sorry I don't have a more recent draft handy)
[14.5.3] 4/ A pack expansion is a sequence of tokens that names one or
more parameter packs, followed by an ellipsis. The sequence of tokens
is called the pattern of the expansion; its syntax depends on the
context in wh... |
7,043,062 | 7,048,625 | How linker solves ambiguities when linking *.libs? | after very long long time spent with unresolved externals I found that VS2010 was linking wrong .lib file.
Files were unfortunately named with same name.
Folder with linked(unwanted) lib was set in project properties
Folder with unlinked(wanted) lib was inherited from other property sheet
Desired lib was newer date, un... | Think of LIBs to Linker as header to compiler. A LIB only has signature of exported symbols, unless it is static LIB. LIB files do not have any version attached to them.
Two LIB file can have same name, as two header files can have. It's you, the programmer, who has to use correct LIB/header file. If the linker doesn'... |
7,043,105 | 7,043,132 | How to set a character in C++? | This is probably very obvious, in fact so obvious that no C++ reference I could find online cares to document it.
I need to know how to set the byte value of a char in C/C++. For example, if I want the byte value 233 in the char, how do I do?
| Yes, it is too obvious:
char x = 233;
|
7,043,204 | 7,043,309 | CString Parsing Carriage Returns | Let's say I have a string that has multiple carriage returns in it, i.e:
394968686
100630382
395950966
335666021
I'm still pretty amateur hour with C++, would anyone be willing to show me how you go about: parsing through each "line" in the string ? So I can do something with it later (add the desired line to a list). ... | You could try it using stringstream. Notice that you can overload the getline method to use any delimeter you want.
string line;
stringstream ss;
ss << yourstring;
while ( getline(ss, line, '\n') )
{
cout << line << endl;
}
Alternatively you could use the boost library's tokenizer class.
|
7,043,333 | 7,043,395 | Undefined reference to a function when linking with g++ | I am trying to link several object files and I am getting 3 undefined reference to a function errors.
inputtest.cpp
//test of input methods
#include <iostream>
#include <string>
#include <fstream>
#include <string>
#include <vector>
#include "Vector.h"
#include "Particle.h"
#include "read_particle_input.h"
#include... | Your implementation is missing the class scope.
change
void read_particle_input(Particle_vector & particles, User_input & input_data)
{
//define local variables
to
void berger_DEM::read_particle_input(Particle_vector & particles, User_input & input_data)
{
//define local variables
|
7,043,372 | 7,043,410 | int a[] = {1,2,}; Why is a trailing comma in an initializer-list allowed? | Maybe I am not from this planet, but it would seem to me that the following should be a syntax error:
int a[] = {1,2,}; //extra comma in the end
But it's not. I was surprised when this code compiled on Visual Studio, but I have learnt not to trust MSVC compiler as far as C++ rules are concerned, so I checked the stand... | It makes it easier to generate source code, and also to write code which can be easily extended at a later date. Consider what's required to add an extra entry to:
int a[] = {
1,
2,
3
};
... you have to add the comma to the existing line and add a new line. Compare that with the case where the three already h... |
7,043,426 | 7,043,574 | Colored border of the transparent color key around text written on the transparent window | I created a Transparent Layered window with a color key that I use to make the window transparent.
So far it works all fine.
Writing text on it - using GDI+ - works, too...
The problem I encounter is, that the text has a thin border of the colorkey-color around the letters...
What I do in the WM_PAINT is:
1. Clear the ... | Try calling Graphics::SetTextRenderingHint(TextRenderingHintSingleBitPerPixelGridFit).
|
7,043,515 | 7,043,555 | Why is my texture rendered improperly in my OpenGL application? | I'm working with SDL and OpenGL, creating a fairly simple application. I created a basic text rendering function, which maps a generated texture onto a quad for each character. This texture is rendered from a bitmap of each character.
The bitmap is fairly small, about 800x16 pixels. It works absolutely fine on my de... | That sounds to me as if the Graphics card of the machine you are working on only supports power of two textures (i.e. 16, 32, 64...). 800x16 certainly would not work on such a gfx card.
you can use glGet with ARB_texture_non_power_of_two to check if the gfx card does support it.
Or use GLEW to do that check for you.
|
7,043,764 | 7,043,818 | Use template to overcome the lack of a base class? | Obviously, standard containers don't have a common base class, nor a common interface, although the method names are homogeneous.
The problem : I have to fill a container with a collection of objects of a unique type. The container can be a std::list, a std::vector or a std::deque, and possibly some other custom contai... | My favorite would be:
/*
* Fill a container with two strings. The container
* must expose the `clear` and `push_back` methods.
*/
template<typename T>
void f(T & t)
{
t.clear() ;
std::insert_iterator<T> it(t, t.end());
*it++ = "Alice";
*it++ = "Bob";
}
The constraints are now: clear and insert, so ... |
7,043,812 | 7,043,988 | Factorizing implementations of pure, virtual functions for a subset of classes | Suppose I have this class hierarchy:
class A {
public:
virtual void foo(Base *b) = 0;
};
class B {
public:
virtual void bar() = 0;
};
class C : public A, public B {
public:
virtual void viz() = 0;
};
class E : public C {
public:
/** Some non-pure virtual functions, does not implement foo */
};
clas... | I think the problem is that Impl inherits class A and class C inherits both Impl and A. This means there will be two instances of class A where first A's foo is implemented by Impl and a seconds one is still pure virtual. Virtual inheritance can solve this problem, for example:
class A {
public:
virtual void foo ()... |
7,043,909 | 7,043,929 | C++ Looping with doubles | Why is PRINT THIS in the code below never printing? I've already cout << shiftx and shifty to make sure that at some point, they both are 0.3.
for(double shifty=0; shifty < 2; shifty+=.1) {
for(double shiftx=0; shiftx < 2; shiftx +=.1) {
if((shiftx == 0.3) && (shifty == 0.3)) {
cout << "PRINT T... | The golden rule is: avoid equality tests in floating-point.
Neither 0.1 nor 0.3 can be exactly represented.
Standard reading: What Every Computer Scientist Should Know About Floating-Point Arithmetic.
To solve your particular problem, you should iterate and perform comparisons using integer types. Only convert to floa... |
7,044,168 | 7,044,252 | What does "single allocation" mean for boost::make_shared | In the boost doc of make_shared, it says:
Besides convenience and style, such a function is also exception safe and considerably
faster because it can use a single allocation for both the object and its corresponding
control block, eliminating a significant portion of shared_ptr's construction overhead.
I don't... | An "allocation" means a block of memory obtained from a call to an allocator.
Usually, creating a shared_ptr with the pointer constructor allocates memory for a "control block", which holds the reference count and the deleter. Copies of that shared_ptr all refer to the same control block, so that they share the referen... |
7,044,216 | 7,044,369 | Difference between read_some/write_some and receive/send? | I am beginning to work with Boost Asio's TCP sockets. What is the difference between read_some and receive and what is the difference between write_some and send? Thanks!
| As far as I remember, read_some and receive are actually doing the same. I think receive just calls read_some or vice versa. The one naming comes from the idea of treating a socket as a file (read/write), while the other one rather comes from a connection(send /receive) point of view. Same should be true for write_some... |
7,044,281 | 7,044,370 | Is initializing with "var{args}" a new feature of C++0x, or merely syntactic sugar? | I was reading the C++0x faq and came across the section detailing initializer lists. The examples were mostly variations of:
vector<int> vi = { 1, 2, 3 };
vector<int> vj({1, 2, 3});
// etc.
However, also listed was the form:
vector<int> vk{2};
This form appears elsewhere in the faq, and I am curious as to whether it... | One is uniform initialization, and the other is initializer lists. They are two different things, although as you can see, they can produce similar syntax.
vector<int> vk{2};
is a uniform initialization- the other two are initializer lists.
|
7,044,558 | 7,044,616 | Copy constructor and assignment operator | Here is a piece of code:
class GameBoard
{
public:
GameBoard() { cout<<"Gameboard()\n"; }
GameBoard(const GameBoard&)
{
cout<<"GameBoard(const GameBoard&)\n";
}
GameBoard& operator=(const GameBoard&)
{
cout<<"GameBoard& operator=(const GameBoard&)\n";
return *this;
... | Because your assignment operator for Checkers return a value instead of a reference as it is customary.
|
7,044,574 | 7,044,760 | About the braces in a 'case' statement in 'switch' | Today, while I was trying to write code to just add and subtract the two 2*2 matrices, in which I used a switch statement, I got an error:
case bypass initialization of local variable in function main()
Code
#include <iostream.h>
#include <conio.h>
#include <string.h>
int
main()
{
int mat1[2][2], mat2[2][2], mat... | A switch statement is just a bunch of labels and a goto done by the compiler depending on the value of the thing inside the switch test.
When you have a local variable in a function, anywhere past the declaration of that variable you can use it. For instance:
int a;
// can use a now
However, in a switch statement, if ... |
7,044,598 | 7,044,771 | C++ templates in Android NDK | I'm using Android NDK r6 and Android SDK API 8 (2.2).
I'm trying to implement a dynamic list like std::vector using templates but I get plenty of errors in the compiled .o files.
A sample:
As you can see the errors are produced in the compiled .o files, not in source files.
Class definition:
template <class T>
class A... | It's template code. You don't have the same header file to cpp file relationship like a normal C++ class. I generally restructure it like so:
Foo.h:
#ifndef FOO_H
#define FOO_H
template <class T>
class Foo
{
Foo();
};
// Note that the header file INCLUDES the cpp file. This is simply to maintain
// the general .h... |
7,044,633 | 7,050,335 | Inspecting nested Standard Library data | I'm using ddd 3.3.11 and gdb 6.5-8.fc6rh underneath it. My compiler is g++ 4.1.1.
I have a stl map container, containing as its key lookup a vector of int's (vector).
The data at the key is of MyType*.
I'm using the .gdbinit file as written by Dan Marinescu. It works great, until you nest your C++ Standard Library cont... | Using a more recent gdb, I had to add single-quotes, as well as adding namespaces, and an allocator.
(gdb) pmap myMap 'std::vector<int,std::allocator<int>>' MyType*
elem[0].left: $3 = std::vector of length 1, capacity 1 = {2}
elem[0].right: $4 = (MyType *) 0x7fffffffe060
Map size = 1
|
7,044,743 | 7,044,772 | problem handling cons ref of a class within another | what i have is two classes
//class A is a kind of config-class which have configuration details
//for class B
class A{
//....
};
class B{
public:
B(A const& _a)
:a(_a){}
private:
A const& a;
};
till this point everything is fine.
now i want is a B::configure(A const& _a) function so that i can dynamically pass the... | You cannot alter a reference after it's been initialized, whether it is const or not. The const just keeps you from making alterations to the variable that the reference refers to. So to change the variable after the instance has been constructed, you'll have to use pointers rather than references.
Your grammar was rat... |
7,044,804 | 7,044,882 | Interface with non-copyable features | I am trying to implement a logging factory and I have used an interface so that I can swap loggers whenever I like.
Here is the interface
class ILogger
{
public:
//Only allow string input. The entire ARC is going to be non-unicode.
virtual void log(std::string message, eLogLevel level=DEBUG) = 0;
protected:
... | The existence of any user-defined constructor (which includes a copy-constructor) will prevent the compiler from generating a default-constructor. Your subclass GenericLogger relies on the existence of a default-constructor for ILogger (it is implicitly called, since it is not specified otherwise in the initialization-... |
7,045,171 | 7,045,272 | Access violation in Release Mode | I get an access violation error in release mode, but not debug mode.
The error occurs when I try to close a file which was opened to read data from. This is the code:
FILE *file;
GLubyte *transferFunctionData = NULL;
transferFunctionData = new GLubyte(size);
if ( (file = fopen(fileName, "rb")) == NULL)
{
printf("C... | you should use either
transferFunctionData = new GLubyte[size];
if you want allocate array of GLubytes or
fread(transferFunctionData, sizeof(GLubyte), 1, file)
if you want to allocate and read one. Right now you are allocating one GLubyte and reading size, overwriting unallocated memory
|
7,045,384 | 7,045,516 | google protocol buffers - encode in C++, decode in Java - InvalidProtocolBufferException | Sorry, but I think I am going mad. I have this in C++:
std::stringstream message;
protoMsg.SerializeToOstream(&message);
boost::system::error_code ignored_error;
std::cout << "Writing response to socket. Byte size " << protoMsg.ByteSize() << " Buffer " << message.str().length() << std::endl;
for(int i(0);i<(int)message... | You're asking the message to be parsed from the whole of buffer - and my guess is that buffer is more than 88 bytes long.
I can't remember offhand whether parseFrom allows you to specify the maximum amount of data to read, but an alternative would be:
ByteArrayIntputStream stream = new ByteArrayInputStream(buffer, 0, l... |
7,045,414 | 7,045,554 | How do I fix multiple declaration and multiple initialization errors? | Sample 1>
namespace Exercise {
int ivar = 0;
}
int ivar = 0;
using Exercise::ivar; // <<== error
error C2874: using-declaration causes a multiple declaration of 'Exercise::ivar'
Sample 2>
namespace Exercise {
double dvar = 0;
}
int main(int argc, char* argv[])
{
using Exercise::dvar;
doub... | namespace Exercise {
int ivar = 0; // create a new variable "::Exercise::ivar"
}
int ivar = 0; // create a new variable ::ivar;
using Exercise::ivar; // add name "::ivar" to variable "::Exercise::ivar", but that name is taken!
next example:
namespace Exercise {
double dvar = 0; // create a new variable "::E... |
7,045,416 | 7,045,439 | C++ Copy Constructor Strange Behavior | Given the following code:
class monomial {
public:
mp_real coe;
int exp;
monomial *next;
};
class polynomial
{
private:
monomial *start;
public:
polynomial();
~polynomial();
void destroy_poly(monomial *);
polynomial & operator=(const polynomial &);
polynomial(const poly... | You are violating the Rule of Three:
Since you overload Copy constructor, You Should overload copy assignment operator and destructor for your class.
The above statement was in reference to general scenarios, In your code example, you can replace the should with a must.
|
7,045,436 | 7,045,961 | Few doubts regarding 1.constructor and 2.array definition at compile time | Please help me clear the concepts with following problems:
(executed and tested on linux,gcc)
Problem 1:
In the following simple example what exactly meant by A a()??
I found that this is not a definition of default constructor but a() is a function with return type is A.
If it is correct then why this code does not g... | A a(); This tells the compiler that a function a exists. Compiler says OK! But since it's never USED, the linker never check its, and so there's no linker error.
int a[]={3,4,21,5,7,86}; Unfortunately, the elements of array are not considered compile time constants and thus cannot be used to initialize arrays nor t... |
7,045,456 | 7,045,581 | Is this the correct way to implement custom event handlers? | I was looking for a way of adding custom event handlers as a c++ class member function. Found that this code actually works.
I need to separate library class and user code, allowing user code to customize library class.
Here is concept of code. Is it correct to do so? Thread safeness is out of scope in my question. Co... | I tried your code and it works fine.
Just for your information, there is another way to code your function pointer. In which case your code can be simplified just a little. Here I use a slightly different syntax for the typdef for the function pointer, which lets you drop the & symbols.
#include "stdafx.h"
#include <st... |
7,045,576 | 7,045,921 | Using more than one mutex with a conditional variable | Is there a mechanism to have a conditional variable use multiple mutexes?
I am in Linux and pthreads in C++.
In an application, I need two mutexes (instead of one) to be atomically acquired and released by pthread_cond_wait(), but the function only accepts one.
I have a class named BlockingManager and it has the method... | In C++11 (if your compiler supports it) you can use std::lock to lock two mutexes at once (without deadlock). You can use this to build a Lock2 class which references two mutexes. And then you can use std::condition_variable_any to wait on a Lock2. This all might look something like:
#include <mutex>
#include <condi... |
7,045,866 | 7,066,571 | Totalview: is there a way to hardcode a break point? | I have a parallel (MPI) c/c++ program that from time to time leads to an error under certain conditions. Once the error occurs, a message is printed and the program exits; I'd like to set a break point to see the stack and more detail regarding what caused the error. I'm using TotalView to debug things, and I'd like it... | In TotalView, the File > Signals menu option opens this window:
This is to control the default behavior in response to signal calls. SIGTRAP and SIGSTOP are reserved, and it seems TotalView treats these differently. That is raise(SIGSTOP) did not stop as expected in TotalView.
This program:
#include <signal.h>
main(i... |
7,045,879 | 7,046,144 | Determine via C++ whether a program is installed in Linux | I would like to make a system call to a Linux program from my C++ code, but I would like to check whether the program is installed on the user's machine first.
In Ubuntu, I can determine whether a package associated with that program was installed using a system call like dpkg -s gifsicle and parse its output. gifsicle... | There is no standard package manager for Linux, so dpkg is definitely the wrong answer.
For security and correctness reasons, it is probably unwise to rely on the user's PATH to locate an executable. So you probably should already be using the fully-qualified path (e.g. /usr/bin/gifsicle) in your call to system.
If so... |
7,046,116 | 7,046,194 | Another C++ was not declared in this scope error | Several questions has been asked related to this error, but each one of them practically relates to the object or type in question not declared before usage. For example:
class A
{
public:
A_Object a_obj;
};
Getting the error A_Object was not declared in this scope means A_object is not declared anywher... | Does Account.h actually also include Address.h? Such a circular reference seems the most likely situation.
|
7,046,120 | 7,046,153 | Returning value in conditional operator | I was trying to return value true or false depending upon the condition by using a conditional operator but I got an error. Here is my code,
bool isEmpty()
{
int listSize = Node::size();
listSize > 0 ? return (true) : return (false);
return false;
}
And here is the error,
error C2107: illegal index, indire... | You can only have expressions* as the operands of the ternary conditional, not statements. The usual way to say this is:
return listSize > 0 ? true : false;
or even better,
return listSize > 0;
or even better,
bool isEmpty() { return Node::size() > 0; }
*) Since you tagged this as both C and C++, know that there is... |
7,046,243 | 7,046,496 | C++ inline if fails in switch | I just found out the hard way an inline if (A?B:C) does not work as expected in a switch statement.
where A a boolean, B and C both integer unequal to 0. The result of this statement is 0 when placed inside a switch.
I found a stackoverflow post [1] where this behaviour was mentioned but I can not find any explanation ... | This is nothing to do with switch.
10 + true ? 2 : 4
is equivalent to:
(10 + true) ? 2 : 4.
If you want it to act like:
10 + (true ? 2 : 4)
then you will need to write it like that.
|
7,046,244 | 7,046,427 | Serializing a class which contains a std::string | I'm not a c++ expert but I've serialized things a couple of times in the past. Unfortunately this time I'm trying to serialize a class which contains an std::string, which I understand is pretty much like serializing a pointer.
I can write out the class to a file and read it back in again. All int fields are fine, but ... |
I'm serializing by casting the class to a char* and writing it to a
file with fstream. Reading of course is just the reverse.
Unfortunately, this only works as long as there are no pointers involved. You might want to give your classes void MyClass::serialize(std::ostream) and void MyClass::deserialize(std::ifstre... |
7,046,370 | 7,050,070 | HTTPS request with Boost.Asio and OpenSSL | I'm trying to read the ticker symbol at https://mtgox.com/api/0/data/ticker.php from my C++ application.
I use Boost.Asio and OpenSSL because the service requires HTTPS.
Boost version: 1.47.0
OpenSSL: 1.0.0d [8 Feb 2011] Win32
For the application; I took the example from http://www.boost.org/doc/libs/1_47_0/doc/html/b... | In short:
You send "HTTP 1.1" instead of "HTTP/1.1". That's surely enough to make the server refuse your request. There are other differences between your request and cURL's, you might need to change those params as well - even if they seem valid to me.
Maybe OpenSSL does not have the root certificate used by the serv... |
7,047,013 | 7,047,328 | Using C++ with Objective-C, How can I fix "Conflicting declaration 'typedef int BOOL'"? | I have a lot of code in C++, originally built on a PC. I'm trying to make it work with Objective-C on a Mac. To that end, I created an Objective-C framework to house the C++ code and added a thin wrapper. But I'm running into a typedef problem in my C++ code.
When I was working with C++ on a PC I used the BOOL variab... | I'm a little confused by some of the discussion, but instead of typedef int BOOL; how about just:
#ifndef BOOL
#define BOOL int
#endif
If you're using typedef then #undef won't work since they are two different things. #define/#undef operate on preprocessor symbols that perform replacements, whereas a typedef is pa... |
7,047,037 | 7,047,104 | What is overlaying shared memory? | I am looking at someones code comments and in a function mapping shared memory with another process it mentios grabbing a pointer and "overlaying" the shared memory.
Is that a made up word or concept or is it something very specific. I can't seem to make sense of it looking at the code either.
Thank You.
| There's nothing specific about it, nor is it a made up word. It means simply that the code overwrites the shared memory. Wikipedia entry. The Wiki entry goes on in detail about overlay programming techniques, which is a specific meaning, but the first sentence describes the general meaning of the word. I've used i... |
7,047,096 | 7,047,138 | Does sqlite C\C++ library keep DB file as Memory-mapped file? and is it possible to make it do so? | So I wonder how sqlite C/C++ API keeps opened DB: does it use Memory-mapped file? Or how to make it do so?
| Yes, it does. Just search sqlite3.c for CreateFileMapping.
|
7,047,226 | 7,047,254 | Using __thread in c++0x | I read that there was a new keyword in C++: it's __thread from what I've read.
All I know is that it's a keyword to be used like the static keyword but I know nothing else. Does this keyword just mean that, for instance, if a variable were declared like so:
__thread int foo;
then anything to do with that variable will... | It's thread_local, not __thread. It's used to define variables which has storage duration of the thread.
thread_local is a new storage duration specifier added in C++0x. There are other storage duration : static, automatic and dynamic.
From this link:
thread local storage duration (C++11 feature). The variable is al... |
7,047,388 | 7,047,476 | Access to ambiguous class member | Ive got a diamond. I want to access class member. I am using mingw.
Question is: How to access member "top::A" without redeclaring classes
#include <cstdio>
class top {
public:
const char A;
top(): A('t') {}
};
class left: public top {
public:
const char A;
left():A('l'){}
};
class right: public top {};... | Without going for virtual inheritance, you can massage the type a bit to convince the compiler to pick the correct base class:
printf("%c\n", static_cast<left&>(obj).::top::A);
|
7,047,592 | 7,047,612 | Which is efficient, itoa or sprintf? | I am in the processes of building my first C++ application and choosing an efficient C++ libraries to rely on at this stage, is one of the design consideration I am looking at.
Consequently I want to convert an integer type to string and deciding on whether to use;
sprintf(string, "%d", x);
Or
Integer to ASCI
itoa(x, ... | Don't use either of these. Use std::stringstream and so on.
std::stringstream ss;
ss << x;
ss.str(); // Access the std::string
Either way, it's quite unlikely that converting to string will be a significant part of your application's execution time.
|
7,047,619 | 7,047,659 | Parsing char array in C++ | I'm coding a httpserver and I'm stuck at parsing GET requests.
How would I parse a char buffer with something like
GET /images/logo.png HTTP/1.1
So that I only get the path and file extension but ignore the other parts?
| You don't say specifically say what sort of storage this string is in - simple char* or some string class.
So, in general, you could either do it the rather simple and dirty way, by splitting the string on the space character, and taking the second or middle section. Or, a better approach would be to get familiar wi... |
7,047,621 | 7,049,790 | Is there a way to access the value of a local variable that has become hidden inside another scope? | I know if a variable is global, the you can always access its value by preceding the variable name with ::... but is there a way to access the value of a local variable that has become hidden inside another scope?
I thinking of something like this:
void f() {
int x = 1;
{
int x = 2;
//access th... | I think C++ doesn't support this.
|
7,047,629 | 7,048,224 | Access class member "directly" like std::string | I would like the following code to be equivalent:
f = "abc";
h.data = f;
EDIT: I'd also like the ability to do the following:
f += "def"; // f.data == "abcdef";
std::string s = f; // s = "abcdef";
std::cout << f << std::endl;
std::cin >> f;
std::vector<std::string> v (f);
v.push_back(h);
// This would be overkill.... |
EDIT: I'd also like the ability to do the following: [...]
[ This would have been better served as a new question but I don't think you could have foreseen that. ]
No, you don't need to inherit from std::string. One possible way to do what you want is to add a conversion operator. (I won't address how to implement op... |
7,047,797 | 7,047,826 | getting object in each element in vector | Is there a way for an iterator to return an object in each element of a C++ Standard Library vector?
I have this code:
struct mystruct {
int field1;
}
int DoSomethingWithMyStruct(mystruct& a);
std::vector<mystruct> myVector;
std::vector<mystruct>::iterator it;
mystruct s1,s2, temp;
s1.field1=1;
s2.field1=2;
for (... | As well as what the others said, you can do this instead:
#include <algorithm>
std::for_each(myVector.begin(), myVector.end(), DoSomethingWithMyStruct);
It's short and succinct. No need of manual loop.
|
7,048,403 | 7,048,563 | Per-object Data in Allocators? | What is "Per-object Data in Allocators". I can't seem to find what this means. Anyone have a good explanation or link for what this means in terms of the C++ Language?
CLARIFICATION
Section 19.4.2 "The C++ Programming Language (Special Edition)" pg. 573
"Similarly, if allocators were allowed to be perfectly general, ... | Per-object data or local state refers to any non-static data members in the allocator class.
The issue is that currently (in c++03) there is no support for allocators with so-called local state. This is often considered to be a flaw with the allocator model in present-day c++.
Have a read through this article that det... |
7,048,533 | 7,048,589 | Mysterious line break in cout statement | I wrote a small snippet to search for matched strings in an array, then output results for parallel arrays in a nicely formatted fashion. However, I must have some fundamental misunderstanding about how string outputs work, because for the life of me I cannot get this to output correctly, no matter where I put the tab,... | Using the following source to recreate your problem:
$ cat test.cpp
#include <iostream>
#include <string>
int main() {
using std::cout;
using std::string;
const std::string array1[] = {"MatchedString1", "MatchedString2", "MatchedString3"};
const std::string arrayCopy[] = {"MatchedString1", "MatchedSt... |
7,048,552 | 7,048,732 | Trying to figure out Xcode directory system | I'm a bit stuck trying to get box2D to compile and I think it's because I don't quite understand how Xcode handles its build directories.
Box2D is folder containing a set of header and source files (in various subdirectories, etc). I've added the Box2D folder to a coco touch static library project in Xcode and when I t... | OK I figured it out!
In the targets settings page look for 'header search paths' and add the root build directory of your project to it.
|
7,048,633 | 7,048,684 | C++ Creating a simple array of LPWSTR's | As a C++ noob, I can't seem to get this right even though I know it should be simple :{ - I need to create an array of LPWSTR and then populate it with unique strings. The idea was to do something simple like this:
LPWSTR *wszArray = new LPWSTR[5];
for(int x = 0; x < 5; x++)
{
swprintf(wszArray[x], "somestring_%d"... | What you have right now is a single pointer to pointers to wide char. You're then initializing that with the address of an array of 5 dynamically allocated pointers to wide char's. That's fine as far as it goes, but does not allocate any space for the strings themselves, only for pointers to 5 strings. You then need to... |
7,048,685 | 7,048,696 | How to find hardware attached to Ubuntu OS using a C++ programs | I want to list hardwares connected to my Ubuntu OS using a C++ programs. How to start.
Thanks.
| You can use libudev.
|
7,048,888 | 7,048,972 | std::vector<std::string> to char* array | I have a std::vector<std::string> that I need to use for a C function's argument that reads char* foo. I have seen how to convert a std::string to char*. As a newcomer to C++, I'm trying to piece together how to perform this conversion on each element of the vector and produce the char* array.
I've seen several close... | You can use std::transform as:
std::transform(vs.begin(), vs.end(), std::back_inserter(vc), convert);
Which requires you to implement convert() as:
char *convert(const std::string & s)
{
char *pc = new char[s.size()+1];
std::strcpy(pc, s.c_str());
return pc;
}
Test code:
int main() {
std::vector<s... |
7,049,090 | 7,049,146 | Qt Creator Ide, problem building after adding instance of QTcpSocket | Please can someone give me an indication. When I see an error like this in visual studio, I usually know I'm missing a lib. However I'm using qt right out the box so to speak through its own ide. I do not know why QTcpSocket won't build.
mainwindow.obj:: error: unresolved external symbol
"__declspec(dllimport) p... | Inside your .pro file, you should add something like:
QT += network
So the correct libs get linked. See QtNetwork Documentation for more information.
|
7,049,189 | 7,049,202 | How to view the content of a C++ macro? | I have a macro that is dynamically generated before compilation (it's supposed to contain the build number). However I think there's some error with the way it's generated so I would like to check the content of this macro. How can I do that?
I'm using the MSVC2008 compiler.
| You can use /p option and write preprocessor output to a file. Or
You can use /E option and write preprocessor output to stdout
|
7,049,204 | 7,049,236 | Allow objects to be allocated only using dynamic allocation | I am working on a small library, where I have following requirements for any class X:
class X must be allocatable only using operator new
All the children of class X should implicitly become allocatable
only by operator new
The syntax for heap allocation should be elegant
Not much of the existing code should be change... | // Dynamic.h
class OnlyDynamic
{
template<class T> friend struct Dynamic;
virtual void*** __Restriction () = 0;
};
template<class T>
class Dynamic : public T
{
virtual void*** __Restriction () { return 0; }
~Dynamic();
public:
#ifdef Cpp0x
template<typename... Args>
Dynamic(Args... args) : T(args...) {}
#... |
7,049,214 | 7,049,225 | C++ Ifstream reads too much? | I'm trying to read a file and output the contents. Everything works fine, I can see the contents but it seems to add about 14 empty bytes at the end. Does anyone know whats wrong with this code?
int length;
char * html;
ifstream is;
is.op... | That is because html is not null-terminated string, and std::cout keeps printing character until it finds \0, or it may crash your program
Do this:
html = new char [length +1 ];
is.read(html, length);
html[length] = '\0'; // put null at the end
is.close();
cout << html;
Or, you can do this:
cout.write(html, length);
... |
7,049,271 | 7,049,366 | How might I implement this into C++? | So, I'm having some issues here implementing this math problem in C++.
Let's say I have a game that involves two randomly generated outcomes, these outcomes can either be a win or loss.
The algorithm is explained here: http://imageshack.us/f/98/terriblyexplained.png/
For example, if the first six rounds of the game go ... | #include <iostream>
#include <string>
int main()
{
double WinChance = 0.5;
double LossChance = 0.5;
std::string result;
while(std::cin >> result)
{
if(result == "Win")
{
WinChance /= 2.0;
LossChance = 1.0 - WinChance;
}
else
{
Loss... |
7,049,295 | 7,365,103 | Win32 resource editor library? | Is there any free library out there that can provide editing capabilites for resources in Win32 PE files?
It needs to be able to do the following:
Provide a reasonably simple API for altering dialog resources (including the "extended" dialog version, which is poorly documented).
Editing dialogs with UpdateResource by ... | I haven't gotten the chance to test it, but I found Anolis.Resourcer which seems to be pretty capable.
|
7,049,528 | 7,049,548 | Is there a difference between using "this" pointer and not using it? | Does using "this" pointer adds another operation to the program at runtime?
Just to give an example to explain the question better:
class C
{
public:
void set_x(int val){ x = val; }
void set_this_x(int val){ this->x = val; }
private:
int x;
};
Does the function "C::set_x()", during runtime, performs 1 les... | There is no difference between the two member functions. It has to be, since this is what the C++ Standard (ISO/IEC 14882:2003) has to say:
9.3.1 Nonstatic member functions [class.mfct.nonstatic]
2. When an id-expression (5.1) that is not part of a class member
access syntax (5.2.5) and not used to form a pointer to... |
7,049,662 | 7,049,735 | My first DLL has many compile errors I don't understand | I am attempting to create my 1st Simple DLL. I have a class(that's a singleton class) & a Window Procedure function that I declare in the DLL & want to import in my project later on. My IDE is Microsoft Visual C++ 2010 & my project is a Win32 DLL one & I have used MSVC++ default DLL template(you know how it creates all... | I think you are missing _CLASSINDLL preprocessor definition. Add it in Project -> Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions.
|
7,049,750 | 7,049,825 | Qt: connecting signal to slot having more arguments | I want to connect a signal clicked() from the button to a slot of different object.
Currently I connect signal to helper method and call desired slot from there:
connect(button, SIGNAL(clicked()), this, SLOT(buttonClicked()));
void buttonClicked() { // Helper method. I'd like to avoid it.
someObject.desiredSlot(lo... | is this what you want to do:
the signal clicked should be connected to the "desiredSlot" which takes two arguments that are returned by localFunc1 & 2 ??
this is not possible, as you can read in the QT docs. A slot can take less arguments than provided by the signal - but not the opposite way! (The documentation says "... |
7,049,770 | 7,049,798 | Problem with ostringstream and copy constructor |
Possible Duplicates:
Why copying stringstream is not allowed?
how copy from one stringstream object to another in C++?
Compiling class T fails with Visual C++ and GCC producing iostreams template errors. Here is the code:
#include <sstream>
class T
{
static T copy;
std::ostringstream log;
T() {}
... | Copy constructor and copy-assignment of any stream class in C++ has been made private. That means, you cannot make copy of std::ostringstream object:
std::ostringstream ss;
std::ostringstream ss1(ss); //not allowed - copy-constructor is private
ss1=ss; //not allowed - copy-assignment is private
|
7,049,785 | 7,097,325 | Simple way to implement public-key cryptography in C++? | I want to be able to sign a file. By that I mean that the recipient can check that the file is indeed from me and can view its content. Is there any simple way to do that in C++?
I just had a look at the PGP article on Wikipedia but they lost me somewhere in the middle of "hashing, data compression, symmetric-key crypt... | For information, after having tried most of the suggestions here, I ended up using the openpgp command line tool. It's quite lightweight once UPXed, it's cross-platform and it does what I need in an easy way.
|
7,049,814 | 7,049,821 | Does #include also mean Use | I wonder whether #include also means "use". If not, would you please tell me what the compiler will do with the extra files, included functions? If yes, does this mean they have their memories allocated in the output PE?
| #include "file.h" tells the preprocessor to open file.h and merge the content of this file with the current file in which you write #include "file.h".
That is, if you have two files as:
//file.h
extern int x;
//file.cpp
#include "file.h"
int x;
void f()
{
x = 10;
}
Then preprocessor copies the content of file.h ... |
7,049,902 | 7,050,003 | Using boost_foreach without const_iterator | Is there a way to use boost foreach without defining a const_iterator?
My use-case for this is an iterator for a vector, that can contain invalid elements. The iterator should traverse the vector, and yield only the valid elements. It should also repair the vector in the sense that it should swap each invalid item with... | Separation of concerns: the container is responsible for its invariants, the iterators for traversal. If you move the repairing to the container you can separate the logical const from the mutable, hidden parts.
Can you write your iterators the 'dumbest' way possible to disentangle them from the container? For instance... |
7,050,121 | 7,050,187 | error C2259: '<someclass>' : cannot instantiate abstract class | Am getting this compiler error while trying to compile an VS 6 VC++ code. The <someclass> is not an abstract class. And when clicked on the error the pointer points to list system file at the first line of the function
void resize(size_type _Newsize, _Ty _Val)
{
if (_Mysize < _Newsize)
_Inse... | You cannot create an instance of a class if it has any pure-virtual members. Whether those pure-virtual members were declared in that class or in a base class. A class cannot be created unless all of its members exist. A class that has pure-virtual members (whether declared in the class or in a base class) is called an... |
7,050,145 | 7,050,302 | boost::serialization: overloading load_construct_data: no accessible constructor at all | so I'm using the boost::serialization library, and I'm trying to overide how a class is constructed, since it has no default constructor. This is demonstrated here. To me it appears the function takes the class* t and then sets it to point to a newly constructed object. If i'm wrong, this is definately the source of my... | The construct referred to in your question (new(t) my_class(attribute)) is called "placement new". The way it work is that
t must already point to an allocated region of memory (placement new doesn't do allocation by default)
An instance of my_class is constructed at that memory location.
However, since in your case ... |
7,050,166 | 7,050,179 | is not a class or namespace name | I know this question has been asked and answered before, but none of the solutions seem to have worked for me, and my compiler is acting really weird with this error.
When I try and compile my code I get numerous errors such as these:
Error 1 error C2653: 'TargetList' : is not a class or namespace name c:\projec... | PCH (i.e stdafx.h) should be included first in the .cpp file. So do this:
#include "stdafx.h" //this should be included first!
#include "TargetList.h"
#include "Target.h"
See these topics:
About stdafx.h missing in my compiler(mingw32 on windows)
What does this MSVC++ compile error mean
|
7,050,246 | 7,050,284 | Valgrind detecting invalid reads in strlen | I am using Valgrind to detect memory leaks/errors in my library, and it's the first time I've ever used it. It seems to be suggesting that there's some invalid reads in std::string.
Here is the beginning of the error message
==16214== Invalid read of size 1
==16214== at 0x402701D: strlen (mc_replace_strmem.c:282)
=... | Probably you passed an invalid string into your constructor, for example by using a pointer/reference to a string that already got deleted.
|
7,050,247 | 7,050,273 | Exception class that catches many types of other exceptions | I tried to make an exception class (lets call it EXP) that will be able to catch various types of other exception classes (for instance, std::exception), but without any success.
The main problem is that there are many types of exceptions that I need to catch, and I wondered if there is a better way than writing a macr... |
first, it is generally a terrible idea to catch every exception type. Generally speaking, if you don't know what the exception is, how can you meaningfully handle when it occurs?
second, if you want to catch every exception type, you can use catch (...). However, this does not directly give you access to the caught ex... |
7,050,482 | 7,050,560 | Libusb undefined reference to | I'm trying to set up libusb API on my OS. I downloaded libusb api on libusb.org. I followed the standard installation procedure:
cd into directory
./configure
make
make check //without errors
make install
Then I launched Eclipse C/C++ and copied some code from the tutorial found on the internet. But when trying to bui... | you have to set the library linker flag for compilation in the linker,
you can get a full list in the console by executing
pkg-config --list-all
These are the libraries which you have installed on your system and you have to link against the ones you want to use.
so in your example it is libusb so you do
pkg-config ... |
7,050,509 | 7,051,042 | Compiling results in error "undefined symbols for architecture i386" | I've compiled the Box2D library in Xcode which has generated a static library file.
I linked this library to mono touch but when I try to compile I get errors about undefined symbols in various source files.
I've looked at the first few and they seem to be complaining about pointer initializations (i.e. using malloc/ne... | It can be a bit confusing but -cxx is an extra parameter to mtouch, not for --gcc_flags (which are directly passed to gcc compiler).
So mtouch extra argument should look like:
-cxx -gcc_flags "-L${ProjectDir} -lBox2D -force_load ${ProjectDir}/libBox2D.a"
-cxx will ensure g++ gets used instead of gcc - and that should... |
7,050,653 | 7,108,542 | Building a subset of boost libraries | I'm trying to build only a subset of boost libraries. For example, I have this code:
test.cpp:
#include <boost/thread.hpp>
int main (){
return 0;
}
I then do
./bcp --scan test.cpp ~/dev/boost_compact/
So the dependencies files are copied to ~/dev/boost_compact/boost.
Then, following this answer, I copy all file... | Solved the problem. The reason the libraries were not being copied was that I was using the wrong boost directory, that is
./bcp --scan --boost=<path to boost build directory> test.cpp ~/dev/boost_compact/
when I should be using
./bcp --scan --boost=<path to boost source directory> test.cpp ~/dev/boost_compact/
If no... |
7,050,720 | 7,051,001 | How to get text (or automate) from an external control in a Java application (AWT)? | There is an application which is built in the SunAWTFrame class and, as you can guess, this is a strange world for the Windows API.
So I wonder, what should I do/use to get text from controls in a GUI built with this or automate them?
Is there some sort of API or library that can accomplish this and is suitable for wor... | Your problem is likely due to the Java GUI being a Swing GUI program (note that the MS Windows class for these GUI's -- at least I know for JFrames -- is "SunAWTFrame"), and since Swing uses light-weight components, not MS Windows native components, you won't easily be able to extract window information from them. I do... |
7,050,810 | 8,009,528 | Windows IStillImage interface: can't get device list | Please take a look at my code:
#include <windows.h>
#include <Sti.h>
#include <iostream>
#pragma comment (lib, "Sti.Lib")
using namespace std;
void main ()
{
HRESULT hr = CoInitialize(NULL);
PSTI iface = 0;
hr = StiCreateInstance(GetModuleHandle(NULL), STI_VERSION, &iface, NULL);
DWORD numDevices =... | STI only works on Win XP, that's all.
|
7,050,925 | 7,051,059 | Is it possible to write a program without using main() function? | I keep getting this question asked in interviews:
Write a program without using main() function?
One of my friends showed me some code using Macros, but i could not understand it.
So the question is:
Is it really possible to write and compile a program without main()?
| Within standard C++ a main function is required, so the question does not make sense for standard C++.
Outside of standard C++ you can for example write a Windows specific program and use one of Microsoft's custom startup functions (wMain, winMain, wWinmain). In Windows you can also write the program as a DLL and use r... |
7,051,097 | 7,051,717 | Return contents of a std::wstring from C++ into C# | I have an unmanaged C++ DLL that I have wrapped with a simple C interface so I can call PInvoke on it from C#. Here is an example method in the C wrapper:
const wchar_t* getMyString()
{
// Assume that someWideString is a std::wstring that will remain
// in memory for the life of the incoming calls.
return s... | You are going to have to rewrite your getMyString function for the reasons mentioned in Hans Passant's answer.
You need to have the C# code pass a buffer in to your C++ code. That way the your code (ok, the CLR Marshaller) controls the lifetime of the buffer and you don't get into any undefined behavior.
Below is an ... |
7,051,185 | 7,051,387 | Separation of logic and UI | I'm developing a GUI application in Qt.
This is my first GUI application and I'm not very experienced and still have to wrestle with some more advanced aspects of C++ and Qt framework.
The application is pretty simple, featuring a main window and some dialogs where the user configures settings and presses a button, and... | There are several ways of doing this so your question is valid.
Your GUI class can be derived from your logic class. Not the typical approach but it depends on how your application is designed. One major drawback is that the GUI would have to stay in the same thread as logic if you don't want to involve locking-mechan... |
7,051,386 | 7,051,433 | How do I remove meta tags from a string using C++? | Need help figuring out how to extract text from context (Honda from str), need something analogous to Perl regex
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[]) {
string str;
str = "<make>Honda</make>";
//Code to extract Honda from above string
cout<<str<<en... |
need something analogous to Perl regex
Is this a trick question? :) That "something" is PCRE: "Perl-Compatible Regular Expressions".
What you really need is libxml2, and the XPath query //meta/text().
|
7,051,422 | 7,051,432 | Efficient factory functions without pointers (including smart pointers) or copies? | Suppose I have some kind of factory function which creates objects that are largely used for a very short timespan only (possibly just for the duration of the scope of the function where this factory function is called).
Like this:
foo factory(some_parameter fancy_parameter)
{
return foo(fancy_parameter);
}
//this... | Use std::unique_ptr<T>, it has zero overhead compared with a raw pointer.
Or simply return by value, but then you cannot do subtype polymorphism.
|
7,051,667 | 7,051,691 | Socket not sending entire contents on Linux (ubuntu) | I've encountered an issue when sending large segments of data through a TCP socket, having spend about 3 days trying to pick apart the issue and failing I decided it was best to turn here for help / advice.
My Project
I've written a basic HTTP server which (slightly irrelevant) can run lua scripts to output pages. This... | Your problem is that send does not guarantee to send the amount of data passed to it.
It has internal buffers that can fill, socket parameters that affect buffers, etc. You need to note how many bytes were sent, wait for a few milliseconds (for the send to move data over the wire and empty the buffer), then send the re... |
7,051,741 | 7,051,903 | Overload function on parent and child - how to access the parent function | Here is what I would like to do:
class Msg {
int target;
public:
Msg(int target): target(target) { }
virtual ~Msg () { }
virtual MsgType GetType()=0;
};
inline std::ostream& operator <<(std::ostream& ss,Msg const& in) {
return ss << "Target " << in.target;
}
class Greeting : public Msg {
std::... | Try ss<<(Msg const&)in.
And probably you have to make operator a friend of Greeting class.
#include "iostream"
#include "string"
typedef enum { TypeGreeting} MsgType;
class Msg {
friend inline std::ostream& operator <<(std::ostream& ss,Msg const& in);
int target;
public:
Msg(int target): target(target) ... |
7,051,844 | 7,051,853 | How to find the full path of the C++ Linux program from within? | I have this requirement where I need to find the full path for the C++ program from within. For Windows, I have the following solution. The argv[0] may or may not contain the full path. But I need to be certain.
TCHAR drive[_MAX_DRIVE], dir[_MAX_DIR], base[_MAX_FNAME], ext[_MAX_EXT];
TCHAR fullPath[255+1];
_splitpath(a... | On Linux (Posix?) you have a symbolic link /proc/self/exe which links to the full path of the executable.
On Windows, use GetModuleFileName.
Never rely on argv[0], which is not guaranteed to be anything useful.
Note that paths and file systems are not part of the language and thus necessarily a platform-dependent featu... |
7,051,999 | 7,054,626 | Background Subtraction – Stauffer & Grimson’s Algorithm in opencv's latest versions | There is an implementation of that algorithm in opencv version 1.0 the function is cvCreateFGDStatModel to create the background model. But I can't find it in latest versions. Does anybody knows if it was removed or renamed? And if you know other open source of that algorithm please tell me.
| It's still there, just add the appropriate include:
#include "opencv2/video/background_segm.hpp" // on OpenCV 2.3, it's inside this header!
#include "cv.h"
#include "highgui.h"
|
7,052,159 | 7,052,234 | Segfault when using std::set of pointers... can anyone explain this? | In my game I created a base class called Entity which I store in a set for processing. All my game objects derive from this class, and I have no problem adding the derived pointer types to the set in my initialization function.
The problem lies in adding new elements from within an Entity's Step() function. Now, befor... |
Why does Add(new Explosion(16,16,this)) work in GameState but
game->Add(new Explosion(16,16,game)) doesn't work inside my object?
If that is the case then the only possible explanation is that the Entity's game member doesn't actually point to the GameState. Check that it is being set properly on construction and v... |
7,052,169 | 7,053,250 | Identify audio sample in a file | I want to be able to identify an audio sample (that is provided by the user) in a audio file I've got (mp3).
The mp3 file is a radio stream that I've kept for testing purposes, and I have the Pre-roll of the show. I want to identify it in the file and get the timestamp where it's playing in the file.
Note: The solution... | This problem falls under the category of audio fingerprinting. If you have matched a sample to a song, then you'll certainly know the timestamp where the sample occurs within the song. There is a great paper by the guys behind Shazam that describes their technique: http://www.ee.columbia.edu/~dpwe/papers/Wang03-shazam.... |
7,052,411 | 7,052,454 | Is there something special about using BeginPaint/EndPain and not GetDC/ReleaseDC in response to WM_PAINT message? | One can use GetDC/ReleaseDC to draw in client area of window. But in response to WM_PAINT message one have to use BeginPaint/EndPaint. Is there something special about this?
| A WM_PAINT message is issued when a part of the window needs to be updated.
By specifying BeginPaint/EndPaint() you are telling gdi that you are actually doing that job.
If you don't call BeginPaint() for the specified region, WM_PAINT messages will be generated for as long until someone actually updates it. The functi... |
7,052,458 | 7,052,636 | problem building cpp project in eclipse | I have installed minGW and msys. In eclipse CDT I created c++ project that uses cross gcc toolchain.
Eclipse created make file which I can use through command line, so if I run make all project is correctly compiled, but if I use eclipse to build, it fails with following message
**** Build of configuration Debug for pr... | I have chosen wrong toolchain in project, changed to mingw gcc and now it works
|
7,052,568 | 7,052,582 | Why is the output operator 'os << value' and not 'value >> os'? | I am learning about streaming. The standard streams provide the << operator which can be declared as:
ostream& operator<<(stream& os, CLASS& rc);
Why is it impossible to declare it as this?
ostream& operator>>(CLASS& rc, stream& os);
Then I may be able to do something like:
rc.something >> os;
as part of its impl... | In fact it's possible to define
ostream& operator>>(CLASS& rc, ostream& os);
But then you must chain it like this:
a >> (b >> (c >> str));
The >> operator is left-associative, so by default this:
a >> b >> c >> str;
is equivalent to:
((a >> b) >> c) >> str;
which has a wrong meaning.
|
7,052,593 | 7,052,706 | Managed DLL in native VC++ 6 Application | I have a managed DLL that I want to use in a legacy application I'm modifying, so far the steps I have taken are.. pretty much following this guide to a T:
How to call a managed DLL from native Visual C++ code in Visual Studio.NET or in Visual Studio 2005
So, I created a strong name for the DLL, generated the .tlb fil... | Yes, your project setup is wrong. You seem to have added the .tlb file to the linker's Additional Dependencies setting. That's not correct, it doesn't contain any linkable code. It only contains declarations in a format that only the #import directive can understand.
Remove test.tlb from the linker settings.
|
7,052,744 | 7,052,754 | Cross Platform Browser Detection | Can anyone help me out, I need a cross platform way to detect if browsers are installed e.g. Is Firefox installed, Is Safari installed etc.
I am using wxWidgets for my GUI libary if this helps.
I can check the registry on windows but am unsure on how find out browsers for Linux and Mac. Would prefer one clean cross pla... | What's wrong with http://docs.wxwidgets.org/2.6.3/wx_miscellany.html#wxlaunchdefaultbrowser?
And why not using several ways of detection? This functionality could then be implemented in wxWidgets itself. After all, wxWidgets does exactly this and just abstracts it away using function with platform specifics hidden behi... |
7,052,824 | 7,052,885 | Streaming output to save things | I would like to << stream to save all inputs from console into a file
Here is how I tried
ofstream of("file.txt");
while(1)
{
string str;
cin>>str;
of<<str;
}
I don't see the non-English characters in the file (Edit: I mean they are Japanese, Chinese or Korean etc)
| You could stream char by char. Then it would be a true binary copy.
ofstream of("file.txt");
while(1)
{
char c;
cin>>c;
of<<c;
}
|
7,052,857 | 7,054,197 | How do you keep track of exception safety guarantees offered by each function | When writing exception safe code, it is necessary to consider the exception safety guarantee (none, basic, strong or no-throw) of all the functions called. Since the compiler offers no help, I was thinking that a function naming convention might be helpful here. Is there any kind of established notational standard indi... | I don't think you need to do anything special.
The only ones I really document are no-throw and that is because the syntax of the language allows it.
There should be no code in your project that provides no guarantee. So that only leaves strong/basic to document. For these I don't think you need to explicitly call it o... |
7,052,900 | 7,053,001 | client/server application's authentication policy | I am writing a simple protocol for a basic chat program.
my question is: once the client has authenticated by providing username and password, should I also ask the client to provide a token in it's following packets? or is it sufficient to keep it's authentication status in a table at server and never expect the clien... | You should not demand for authentication for any further messages after client has given correct credentials. If your suspect, each and every message should contain authentication information, and in this implementation you need not to authenticate via "login" - just demand security information on each message.
After s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.