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,245,414 | 5,245,439 | Gdb debugging c++, object printing | For example I can print this chunk of code with command:
print *hostx
and I get the result:
$22 = (Adaptation::Ecap::XactionRep) {<Adaptation::Initiate> = {<AsyncJob> = {_vptr.AsyncJob = 0x8beac8, stopReason = 0x0,
typeName = 0x662553 "Adaptation::Ecap::XactionRep", inCall = {p_ = 0xc8a440}, id = {static Pr... | Using standard C/C++ syntax, e.g. print hostx->id
|
5,245,499 | 5,245,560 | C++ : restrict access to the superclass' methods selectively? | This is an interview question. I am not a C++ expert yet so i need some help in finding the answer to this question ( i first want to understand the question...is it a valid question?)
Question:
Suppose I have a class B that derives
from class A and I wanted to reuse
some, but not all of the methods of A.
How wo... | I assume that
you cannot change the definition of A
you want to select which methods from A should be accessible from a B object.
The using directive solves your problem. Example:
class A
{
public: // or protected for that matter
void foo();
void bar();
};
class B : private A // or protected, depending on wh... |
5,245,556 | 5,245,815 | Regex tokenizing with Boost only getting last letters of words | I am trying to parse a simple sentence structure with Boost. This is my first time using Boost, so I could be doing this completely wrong. What I want to do is only accept strings in this format:
Must start with a letter (case insensitive)
May contain:
Alphabetic characters
Numeric characters
Underscores
Hyphens
Al... | Change your regex to: ([A-Za-z][-A-Za-z0-9_]*)
By putting the parentheses around the whole expression, the entire thing will be captured, not just the last character matched. Putting the - in front causes it to be a matched character and not a range specifier.
|
5,245,774 | 5,245,790 | How to use class which defined below? | class A{
public:
B b;
};
class B{
public:
A a;
};
I can't write in A class "B b" because class B defined below. Is any way to make it work?
thanks
| This is not possible. You need to use a pointer or a reference in one of the classes.
class B; // forward declare class B
class A {
public:
B * b;
};
class B {
public:
A a;
};
As to why it isn't possible: A contains a B contains an A contains a B ... There's no end to the recursion.
If you're used to languages (s... |
5,246,046 | 5,246,097 | How to add environment variable in C++? | Is there any way I can add environment variable in Windows via C++?
They have to be added in "My computer->properties->advanced->environment variables"
Thank you
| from MSDN :
To programmatically add or modify
system environment variables, add them
to the
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment registry key, then
broadcast a WM_SETTINGCHANGE message
with lParam set to the string
"Environment". This allows
applications, such a... |
5,246,049 | 5,246,686 | C++11 static_assert and template instantiation | In C++11, should the operation of static_assert within a template depend on whether that template has been instantiated or not? For example, with the following code
template <int I>
void sa() { static_assert(0,"Hello."); }
int main(int argc, char *argv[]) { return 0; }
GCC 4.5.0 will fail the assertion, and produce ... | GCC is correct and the other compiler is correct too. Refer to 14.6p8 in the spec
If no valid specialization can be generated for a template definition, and that template is not instantiated, the template definition is ill-formed, no diagnostic required.
Therefor, a compiler is free to reject the following
template<t... |
5,246,140 | 5,448,487 | OLE Date Time to Posix_time | what's the best way, without using MS COM libs to convert OLE date time format to a posix_datetime used by boost?
OLE date time is represented as a floating point number.
| You have to do it manually... Just no other way I've found to do this...
boost::posix_time::ptime datetime_ole_to_posix(double ole_dt)
{
static const boost::gregorian::date ole_zero(1899,12,30);
boost::gregorian::days d(ole_dt);
boost::posix_time::ptime pt(ole_zero + d);
ole_dt -= d.days();
ole_dt *= 24 * 6... |
5,246,170 | 5,308,723 | Advanced (C++) Source Code Re-Formatting with Visual Studio? | We would like to be able to reformat C++ blocks/functions of code directly from the Visual Studio IDE, so that developers easily can assure that the new code they insert adheres to our formatting guidelines.
I have found the Artistic Style tool, which pretty much covers the features we'd need. However, it only can work... | I found a blog post that describes how to integrate an external code formatter with Visual Studio: Per-Project Code Formatting in Visual Studio
(...) You can then configure your IDE(s) so
that their default formatting commands
instead use Uncrustify. In Visual
Studio, for example, one can set up an
external to... |
5,246,215 | 5,248,655 | DirectX 9 Fixed Function Textures | Using the Fixed Function rendering pipeline in DirectX 9, it's quite easy to set a texture and render vertices by doing the following:
struct vert { float x, y, z, u, v; };
device->SetFVF(D3DFVF_XYZ | D3DFVF_TEX1);
device->SetTexture(0, MyTexture);
//Draw vertices here
However, I'd like to add an additional float va... | You could set a 1D linear grayscale texture as a second texture, configured to modulate the first. Then send a single texture coordinate for the second texture (by specifying D3DFVF_TEXCOORDSIZE1 for it, I think). Speculating here -- haven't tried it myself.
To paraphrase your pseudocode: Colour = Texture0Colour(u0, v0... |
5,246,249 | 9,473,007 | Making a wrapper dll to let gamemaker handle the C++ standard libraries | Gamemaker is a neat tool which allows for some good RAD. However it has quite a few shortcomings. One of those is the lack of a good standard library.
True you have the "ds_*" type members, but those are quite lacking. The priority queue for example is only a read-once type (it's destroyed in the process). The sort fun... | The only way to "store" a data structure in a variable in Game Maker is with a handle or ID. You'll notice that using the built-in data structures does the same thing, using integers.
The method I would try would be to store all the pointers to your data structures along with their IDs in a hashtable. Then, you pass ... |
5,246,320 | 5,246,385 | How to name constructor parameters when using non-prefixed member variables? | Certainly there is no one right way to do this, but I can't even think of any decent naming scheme, that's why I'm asking here. (So: While all answers will be subjective, they will be useful nevertheless!)
The problem is as follows: For simple aggregate structs, we do not use member var prefixes.
struct Info {
int x;... | Why invent pre/postfixes? I just use the same name. C++ is designed for that to work.
struct Info {
int x;
string s;
size_t z;
Info(int x, string s, size_t z)
: x(x)
, s(s)
, z(z)
{ }
};
It's straight forward.
|
5,246,389 | 5,246,510 | How could I compare C/C99 specifications to C++ specifications? | I need to verify that I can use unions a certain way.
For C99, this answer is adequate: Union element alignment
C99 - section 6.7.2.1 Structure and
union specifiers (paragraph 14):
A pointer to a union object, suitably
converted, points to each of its
members (or if a member is a bitfield,
then to the unit in ... | In C++ (14882:2003), this is split between two paragraphs:
9.5[class.union]/1
Each data member is allocated as if it
were the sole member of a struct.
9.2[class.mem]/17
A pointer to a POD-struct object,
suitably converted using a
reinterpret_cast, points to its
initial member (or if that member is a bit-fiel... |
5,246,563 | 5,246,610 | How to link a SunriseDD C library with a C++ app? | I was looking for a lock-free hash table implementation in C or C++ and found one: SunriseDD. That was the good news :) For a few days I am trying to get this up and running but with no luck. I can compile downloaded sources as a static library using GCC C compiler. And I get libSunriseDD.a archive.
So far so good :D
... | Put -lSunriseDD last on the linker line. The linker processes arguments left to right, and searches libraries for currently undefined symbols when it processes a static library.
Also, unless the library is C++-aware, wrap includes in extern "C".
extern "C" {
#include <dd_data_dictionary.h>
}
|
5,246,587 | 5,265,593 | How to write a boost::lambda functor that returns a new functor | How can I write a lambda expression with two placeholders, one for the callable object, and one for the function argument, such that supplying the callable object first returns a unary function.
In the example below, generate should be a lambda expression with the first placeholder for the callable object itself, and ... | If using Boost.Phoenix the answer would have been a little easier:
#include <boost/phoenix/phoenix.hpp>
struct callable
{
typedef bool result_type;
bool operator()(int) const
{
return true;
}
};
int main()
{
using phx::bind;
using phx::lambda;
using phx::arg_names::_1;
using p... |
5,246,599 | 5,247,827 | understanding a qthread subclass's run method and thread context | i have an encoder class with lots of methods . this is a subclass of Qthread. i am new to multi-threading and
trying to understand how this class is
threading its methods
... i understand to thread a method it has to be in a subclass of qthread. and the run of this implements the threaded code for this class. And... |
The class you have written creates a thread and initializes a QObject::timer. It then goes on to call a user defined init() function then the QThread::exec() function.
My guess is that you intended that exec() would be a user defined function where the actual work is to occur. Be aware that QThread::exec() processes ... |
5,246,715 | 5,247,090 | If I add compiler optimisation flags to my application should I also rebuild my toolkit with the same flags? | To optimise my application I am testing different compiler (VS2008) options in my qmake project file.
QMAKE_CXXFLAGS += /MP /Ox /arch:SSE2 /GL
However it occurs to me that whilst I get the optimised binary for my application, the Qt DLL's which it depends on are not optimised in the same way.
Should I recompile my Q... | I don't think recompiling Qt makes sense here. Normally, the (release mode) DLLs will be compiled with sufficient optimisation for most uses. Normally Qt is used for the GUI, and if your application has performance issues because the Qt code isn't fast enough, there will be other reasons for that. Concentrate on findin... |
5,246,817 | 5,246,880 | Fastest way to check if a number is in a list of numbers | I need to check whether an ID (a long integer) is in a list of ~10,000 IDs. I need to do this about 10^9 times over on a loop, and speed is relatively important. Is using a c++ set the quickest way to do this? Something like:
set<long> myset;
// (Populate myset)
long id = 123456789;
if(myset.find(id) != myset.end()... | The quickest way, if your long has a limited range, is a bitmap (e.g. vector<bool>). If that's not doable, a unordered_set (hash_set) should be attempted. And if that keeps hitting worst-case, then use a set
|
5,246,934 | 5,247,077 | CWinThread Enquiries (MFC) | I have a very simple question about how CWinThread works and where is the entry point everytime I called ResumeThread(). I'm looking for an entry that looks similar as "main" function where I can perform some operations and branches.
I'm also wondering how to end or kill running threads at any point from different thre... | The primary entry point for a class derived from CWinThread is the virtual Run() function. However, there is also an InitInstance() function which is called beforehand, and an ExitInstance() function called afterwards.
You should never call ExitInstance() yourself. Instead, call AfxEndThread, or just return from Run().... |
5,246,969 | 5,247,009 | string literal uniqueness requirements | I've always understood that the storage of string literals is implementation defined, so the compiler is free to roll up multiple literals such that, given
static const char* foo = "blah";
static const char* bar = "blah";
foo and bar can point to the same memory. However, I can't figure out if thats also true when:
st... | A well-formed program cannot tell whether foo and blah are stored at the same address or not, so I believe that yes the optimizer could fold the constants together.
[expr.rel] (draft 3225) says:
If two pointers p and q of the same type point to different objects that are not members of the same
object or elements of ... |
5,247,157 | 5,247,398 | Modelling clothing in C++ | I'm looking to write a bit of software that will end up drawing a human frame (which can be configured with various parameters), and the plan is to have some sort of clothing placed on the dummy.
I've looked at Blender, and OpenGL libraries as well as other rendering and physics engines, I'm not looking for you to tell... | Unfortunately, developing a system like the one your talking about would be insanely difficult. On the plus side, there are alot of easy to use technologies that will help you attain your goal hopefully.
Generally, the way that this type of thing works is as follows: You make some 3d asset in a modeling program such as... |
5,247,221 | 5,247,301 | C++: File open call fails | I have the following code in one of my library functions that I am calling many times in a loop. After a large number of iterations I find that open returns -1 which it shouldn't have as the previous iterations worked fine. What may be the cause. How can I get more details on the error.?
int mode;
if (fileLen == 0)
... | perror is the standard function to map errno to string and print it out to stderr:
if (myFilDes == -1)
perror("Unable to open file: ");
man errno / man perror / man strerror for more info.
|
5,247,259 | 5,247,373 | C++: Array and shared memory | I am trying to create a piece of shared memory in order to share an array, here is my example:
int main(){
key_t key;
int shm_id;
int arr[10];
key=ftok("~/.bashrc",1);
shm_id = shmget(key, 10*sizeof(int), 0666 | IPC_CREAT);
arr = (int*)shmat(shm_id, NULL, 0);
arr[0]=101;
printf("%d\n... | Remove this line:
int arr[10];
and change the call to shmat() to:
int* arr = (int*)shmat(shm_id, NULL, 0);
A pointer variable can be used as an array, so arr[0]=101 will still work.
(As @Andrew commented, its better to declare variables at the point where they are first used. This reduces the risk of using an uniniti... |
5,247,355 | 5,253,850 | Using a pointer to a parser in boost::spirit | Basically I'm doing an expression parser. As I'm in need of as good as possible performance, and according to the documentation construction of a grammar can be rather slow, I'd like to reuse the grammar and bind the symbol table just before parsing. As the client of the grammar is likely to have a symbol table that's ... | I believe a simple
qi::symbols<char, double>* m_Symbols;
qi::rule<Iterator, double(), ascii::space_type> m_Val;
m_Val = qi::int_ | qi::double_ | qi::lazy(*m_Symbols);
should do what you need. The lazy parser (see here) evaluates its argument (repeatedly) at parse time only.
|
5,247,714 | 5,247,790 | Struct existence in functions/methods | Say
a_function(mystruct::create().execute());
create() creates an instance of struct as mystruct s()
then the method execute() returns something.
does the struct continue to exist for the entire time the function is executed or is it released?
| The temporary struct object exists until the full expression is over. That means until a_function has been returned from.
See 12.2 in C++03.
|
5,247,843 | 5,247,903 | Problem counting words from a phrase without using std::map | i want to see the number of appearance of words from some phrases.
My problem is that i can't use map to do this:
map[word] = appearnce++;
Instead i have a class that uses binary tree and behaves like a map, but i only have the method:
void insert(string, int);
Is there a way to counts the words apperances using this... | Presumably you also have a way to retrieve data from your map-like structure (storing data does little good unless you can also retrieve it). The obvious method would be to retrieve the current value, increment it, and store the result (or store 1 if retrieving showed the value wasn't present previously).
|
5,247,957 | 5,249,052 | c++ bit flags in opengl shaders (glsl) | What would be the best way to send my bit flag to the fragment shader in order to be able to if() against it?
I have the following bit flag (enum):
uint32_t options;
enum Options {
ON = 1 << 0, /// row 1 | enable or disable
OFF = 1 << 1,
DUMMY1 = 1 << 2,
... | There will be no point in elegant enumeration of your flags because of the different code paths that you want to use. In C++ you could do something like a jump function table, but in GLSL you can't do that (and believe me - you don't want to). So check in a regular way:
if (options & (ON | PHOTOREALISTIC)) { /*do some... |
5,248,016 | 5,248,042 | Compound expression vs. Expression vs. Sub-expression | I feel I got a little confused here distinguishing sub-expression from expression.
Compound expression - An expression involving more than one operator.
E.g. 1 + 1 * 1
Expression - An operator with one or more operands.
E.g 1 + 1 or + 1
is there a level below the expression which is called a sub-expression?
| An expression may not have an operator. For example, in the following:
int a = 0;
a;
a is an expression. An expression is, to quote the C++ Standard, "a sequence of operators and operands that specifies a computation" (C++03 5/1). Here, a is an "operand" even though there is no operator.
A subexpression is any exp... |
5,248,237 | 5,282,508 | How to compile googletest on windows using mingw with msys? | My need is simple. I have to compile and use googletest on windows using MinGW with msys. Has anyone some experience doing this?
Thanks for answers.
| It took me some time but I figured it out. Here is the guide for anyone who face the same problem.
To be able to compile GoogleTest on Windows follow this instructions:
I assume you have MinGW with MSYS istalled.
Download and install CMake from the official site http://www.cmake.org/. Use the Win32 installer
version.... |
5,248,291 | 5,276,059 | alternatives to std::string to use with boost::asio | boost::asio's various read and write functions and methods accept boost::asio::buffer. According to buffer's documentation, a mutable std::string cannot be wrapped in boost::asio::buffer, and thus cannot be used for asio's read functions. This is probably due to the fact that std::string does not allow mutable access t... | This is to answer Eli's comment
I didn't mention asio::streambuf in my
question originally, indeed because it
wasn't 100% clear to me how to use it
with fixed size reads and asio. Could
you point to an example (or add one as
an answer) of showing how to read
fixed-length chunks into a
std::sstream?
Here... |
5,248,302 | 5,249,261 | how do I use find window and sendmessage in empty visual c++ project (or console app) | I want to make the most simplest application that can communicate via windows send messages (and parse json). I have found a sample code:
CWnd* pWnd = FindWindow("old title");
pWnd->SendMessage(WM_SETTEXT,0,(LPARAM)"New title");
That works... but only if I use MS Visual Studios "create new MFC form application" wizard... | If you want something so simple, then I'd just forget all about MFC and start with a basic console app from the New Project Wizard. MFC seems rather heavy duty for something so simple.
|
5,248,309 | 5,248,837 | Compiler and CPU reordering | I have this following situation.
volatile double val1 = 10.0;
volatile double val2 = 20.0;
double SetValues(double d1, double d2)
{
double ret = d1-d2;
InterlockedExchange64( (volatile long long*)&val1, *((long long*)&d1) ); // val1 = d1;
InterlockedExchange64( (volatile long long*)&val2, *((long long*)&d2) ); /... | The compiler can never reorder calls to functions in external libraries. If your compiler implements these functions as intrinsics, it will be smart enough not to reorder them.
As far as CPU reordering is concerned, the MSDN documentation says "This function generates a full memory barrier (or fence) to ensure that me... |
5,248,571 | 5,249,001 | Is there const in C? | This question may be naive, but:
is there const keyword in C?
since which version?
are there any semantic and/or syntactic differences between const in C and C++?
| There are no syntactic differences between C and C++ with regard to const keyword, besides a rather obscure one: in C (since C99) you can declare function parameters as
void foo(int a[const]);
which is equivalent to
void foo(int *const a);
declaration. C++ does not support such syntax.
Semantic differences exist as ... |
5,248,599 | 5,248,616 | Too many actual parameters for macro? | Code:
#include <iostream>
using namespace std;
#define ADD(x,y) ((x)+(y))
int main( int argc, char** argv )
{
cout << ADD(1,2,) << endl;
return 0;
}
Compiler output:
1>Compiling...
1>main.cpp
1>c:\warn_test\main.cpp(9) : warning C4002: too many actual parameters for macro 'ADD'
Why isn't this... | You use ADD(1,2,), note the second ,. Remove that and it will compile just fine!
@schnaader: You are right, I read too fast. Sorry.
[edit]
Please provide more details about the compiler in question. I use: g++ (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5, and this is the result I get:
test.cpp:9: error: macro "ADD" passed 3 a... |
5,248,704 | 5,251,713 | How to redirect standard output to output window from Visual Studio | Is it possible to redirect standard output to the output window from Visual Studio?
I use OutputDebugString in my program, but I use some libraries that have output debug messages with printf's or cout's.
| Straightforward standard output redirection will not work, as there is no handle corresponding to OutputDebugString. However, there should be a way:
It could be done by redirecting standard output to a pipe, and then creating a thread which would read the pipe and print anything read from it using OutputDebugString.
No... |
5,248,776 | 5,248,879 | Integration of C++ in C infrastructure | C++ is real handy in most projects, but sometimes you just have to integrate with existing C style functions.
How do you do that in a neat way, especially, if you work with strings?
I had an idea that I could use construct like this:
std::string buffer;
buffer.resize(1024);
GetBackCStyleString(&buffer[0], 1024);
But ... | That's a good solution. If you want the size to be accurate, call resize again after the function returns and you can calculate the actual length.
e.g.
buffer.resize(GetBackCStyleString(&buffer[0], buffer.size());
if the function returns the length, or
GetBackCStyleString(&buffer[0], buffer.size()
buffer.resize(strle... |
5,248,877 | 5,249,294 | Accessing static member through invalid pointer: guaranteed to "work"? | Setup
Given this user-defined type:
struct T
{
static int x;
int y;
T() : y(38);
};
and the requisite definition placed somewhere useful:
int T::x = 42;
the following is the canonical way to stream the int's value to stdout:
std::cout << T::x;
Control
Meanwhile, the following is (of course) invalid due ... |
it's not clear whether "evaluation" here involves an actual dereference.
I read "evaluation" here as "the subexpression is evaluated." That would mean that the unary * is evaluated and you perform indirection via a null pointer, yielding undefined behavior.
This issue (accessing a static member via a null pointer) i... |
5,248,889 | 5,411,793 | Differences between FFTW and CUFFT output | In the char I have posted below, I am comparing the results from an IFFT run in FFTW and CUFFT.
What are the possible reasons this is coming out different? Is it really THAT much round off error?
Here is the relevant code snippet:
cufftHandle plan;
cufftComplex *d_data;
cufftComplex *h_data;
cudaMalloc((void**)&d_data,... | So it looks like CUFFT is returning a real and imaginary part, and FFTW only the real. The cuCabsf() function that comes iwth the CUFFT complex library causes this to give me a multiple of sqrt(2) when I have both parts of the complex
As an aside - I never have been able to get exactly matching results in the intermed... |
5,249,026 | 5,249,088 | reading binary files C++ | I would like to ask for help ... I am starting in C++ and I got this homework at school ... We got to write function bool UTF8toUTF16 (const char * src, const char * dst ); which is supposed to read src file coded in UTF-8 and write it into dst file but in UTF-16. We also mustn't use any other libraries than in my code... | You don't know how big a character is in utf8 until you finish parsing it, you need to read "chars" one at a time until you have a complete utf8 character.
edit - you don't say what you are getting as an output - but I suspect it's a byte ordering issue.
You might be better reading the input (if you know it is always a... |
5,249,418 | 5,249,436 | "warning: use of old-style cast" in g++ |
Possible Duplicate:
When should static_cast, dynamic_cast and reinterpret_cast be used?
With this C++ code,
char* a = (char*) b;
I got warning warning: use of old-style cast.
What would be the new-style cast?
| reinterpret_cast, static_cast, dynamic_cast and const_cast are the c++ cast alternatives.
const_cast to remove const/volatile from a const variable.
dynamic_cast to perform runtime validity checks when casting in between polymorphic types
static_cast to perform e.g up/down-cast in a inheritance hierarchy, but with no ... |
5,249,431 | 5,249,569 | Linker Trouble: How to determine where a "/DEFAULTLIB" is coming from | I am trying to find a good way to determine what module at link time is causing a certain library to get processed as a "/DEFAULTLIB" as seen in the verbose linker output from Visual Studio.
Here is my situation, I have several static library pre-requisites and each has a release and a debug version (BlahD.lib and Blah... | Look for #pragma comment(lib) in the source. See if it perhaps is dependent on a #define - This is a common way for a SDK to ensure that the right libs are linked, and you may need to define THESDK_DEBUG or THESDK_RELEASE for the logic to work out.
Additional information:
I discovered in Visual Studio 2008 that even co... |
5,249,747 | 5,249,786 | "primary-expression before '.' token error" in g++ | I have this C++ code to generate "primary-expression before '.' token' error with g++ compiler. It compiles OK with cl (MSVC) compiler.
template<typename T>
class A : public std::auto_ptr<T>
{
typedef std::auto_ptr<T> Super;
public:
A() : Super() { }
A(T* t) : Super(t) { }
A(AP<T>& o) : Super(o) { }
... | Super is a type. If you want to call the base class function, you can do so via this:
this->get();
Note that this-> is only required here because get() is a member function of a dependent base class; that is, a base class that is dependent upon the template parameter T. For more information, consult the Parashift C+... |
5,249,835 | 5,250,058 | "expected nested-name-specifier before ‘const’ error" with typename const in g++ | I have this code in C++
template<typename T>
class DD
: public enumerables<T>
{
...
private:
typename const DD<T>& mContainer;
}
And it gives me two error messages :
error: expected nested-name-specifier before ‘const’
error: invalid declarator before ‘&’ token
What's wrong with typename const code? It compiles... | Well, what's that typename doing there? You are not referring to a nested type, so typename is totally unnecessary there. I'd say that the error is caused by that unjustified use of typename, not by ordering of the parts of the declaration or anything else.
It should be just
const DD<T>& mContainer;
or even
const DD&... |
5,249,895 | 5,249,910 | How to cast away the volatile-ness? | How to cast away the volatile-ness? Which c++ style cast should I use?
| Use const_cast.
For example,
volatile sample *pvs = new sample();
sample *ps = const_cast<sample*>(pvs); //casting away the volatile-ness
That is, const_cast is used to cast away both const-ness as well as volatile-ness. Unfortunately, its name doesn't contain the term "volatile". Maybe, that is because the keyword co... |
5,249,948 | 5,249,963 | Is returning a reference for accessor idiomatic? | In C++, it is possible to create an accessor which returns a reference to a private field.
class Cls {
private:
int _attr;
public:
int& attr() { return _attr; }
};
such that the attribute can be accessed as such:
// set
c.attr() = 4;
// get
cout << c.attr() << endl;
Is this style of accessor ... | No, that code would be unsurprising, as long as you also provide a const overload:
class Cls {
int _attr;
public:
int& attr() { return _attr; }
int const& attr() const { return _attr; }
};
However, I would consider the following idiomatic, for the reasons mentioned by Chris Lutz and Mark B:
class Cls {
... |
5,250,097 | 5,250,227 | Help porting c++ to php code | I need if possible port this function to c++:
static unsigned char bux_code[3] = {0xFC, 0xCF, 0xAB};
void bux_convert(char* buf, int size)
{
int n = 0;
// ----
for (n=0;n<size;n++)
{
buf[n]^=bux_code[n%3];
}
}
What i have done:
$bux_code = array("\xFC", "\xCF", ... | In PHP you can't always address an offset of a string like $mystring[5] or $mystring[$k] and then treat the resulting character as a numeric value in every respect. Here's a way you could get around it: turn the string into an array at the start of bux_convert(), using str_split(), and then turn it back into a string a... |
5,250,277 | 5,409,175 | Is there anyway to allow one application thread to continue while at a breakpoint in GDB? | While debugging an application using the Apache Zookeeper C runtime library, I run into issues when setting breakpoints with the default all-stop mode in GDB. With the Zookeeper thread being unable to run, the server will timeout the session and thus delete any ephemeral znodes you may have created. Using non-stop mode... | With Zookeeper it turns out there is a hack you can perform in order to allow a session to continue while interrupted in gdb. This hack leverages a few properties of Zookeeper and gdb:
You can have multiple Zookeeper clients with same session ID
gdb doesn't stop child processes at parent breakpoints
You can ignore gdb... |
5,250,401 | 5,250,492 | Bug in code using boost named_semaphore | I would keep some data in shared memory, using named semaphores to manage access:
#include <boost/interprocess/sync/named_semaphore.hpp>
struct shared_memory_buffer
{
// Application data
int items[10];
// Synchronization data
boost::interprocess::named_semaphore syncSem;
shared_memory_buffer()
... | boost::interprocess::open_or_create_t is a type – you presumably want to pass boost::interprocess::open_or_create, which of course is an instance of open_or_create_t. This is documented here.
|
5,250,526 | 5,250,562 | "expected type-specifier" error in g++ | I have a DD class
template<typename T>
class DD
: public IEnumerable<T>
{
typedef IEnumerable<T> Super;
typedef std::set<T*> Container;
And a method
template<typename T>
bool DD<T>::Enumerator::Move()
{
if(!mIt.get())
mIt.reset(
new Container::iterator( <-----
mContainer.GetC... | Try:
new typename Container::iterator
When you are in a C++ template, the compiler doesn't know whether Container::iterator is a type or something else. So you need to explicitly say that its a type.
On another note, creating an iterator with new is almost certainly wrong.
|
5,250,578 | 5,250,716 | Large exponents in C++ | In C++, how can I calculate something like 2009^1389? (That's 2009 raised to the 1389th power, not the bitwise XOR.)
| Simple answer: You can't. That is: 2009^1389 is too large a number to fit into any of the numeric types available to you in C. (Strictly, it's possible that you might have million-bit ints or floats or something, since the C language standard is deliberately rather indefinite about these things, but in practice you don... |
5,250,609 | 5,250,627 | Cast int as byte array in C++ | I am trying to use implement the LSB lookup method suggested by Andrew Grant in an answer to this question: Position of least significant bit that is set
However, it's resulting in a segmentation fault. Here is a small program demonstrating the problem:
#include <iostream>
typedef unsigned char Byte;
int main()
{ ... | Use this:
(Byte*) &value;
You don't want a pointer to address 300, you want a pointer to where 300 is stored. So, you use the address-of operator & to get the address of value.
|
5,250,862 | 5,252,151 | Win7 GLUT window doesn't receive events | I have created a simple Visual Studio Express 2010 C++ project using GLUT and OpenGL,
it compiles and runs ok, except that the window it creates receives no events..
the close/minimize buttons don't do anything (not even mouseover) no context menu on the task bar on right click, and the window doesn't come to the foreg... | You miss a display callback. Could you try:
void display();
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitWindowSize(window_width, window_height);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutCreateWindow("MyApp");
/// glutIdleFunc(main_loop_function);
glutDisplayFunc(di... |
5,250,940 | 5,250,970 | How do I publish a QT LGPL program | I believe I have too dynamically link my program. How do I link my program too QT and then install it by an nsis installer, on Windows? Do I use QMake?
| Just ship your program with the Qt dll's you have used - assuming you have made no changes to the Qt source.
On linux you can assume they have the correct dlls or will get them from their distribution's repository automatically with the dependencies checker.
On windows you really need the Dlls for the same compilers s... |
5,251,042 | 5,435,410 | Passing Python array to c++ function with SWIG | I have written a good bit of code in python and it works great. But now I'm scaling up the size of the problems that I'm analyzing and python is dreadfully slow. The slow part of the python code is
for i in range(0,H,1):
x1 = i - length
x2 = i + length
for j in range(0,W,1):
#print i... | You can use arrays as it is described here: Doc - 5.4.5 Arrays, the carray.i or std_vector.i from the SWIG library.
I find it easier to work with std::vector from the SWIG library std_vector.i to send a python list to a C++ SWIG extension. Though in your case where optimization matters, it may not be the optimal.
In ... |
5,251,403 | 7,463,972 | Binary Serialization of std::bitset | std::bitset has a to_string() method for serializing as a char-based string of 1s and 0s. Obviously, this uses a single 8 bit char for each bit in the bitset, making the serialized representation 8 times longer than necessary.
I want to store the bitset in a binary representation to save space. The to_ulong() method is... | This is a possible approach based on explicit creation of an std::vector<unsigned char> by reading/writing one bit at a time...
template<size_t N>
std::vector<unsigned char> bitset_to_bytes(const std::bitset<N>& bs)
{
std::vector<unsigned char> result((N + 7) >> 3);
for (int j=0; j<int(N); j++)
result[j... |
5,251,483 | 5,251,891 | Linux & Windows: Using Large Files to save physical memory | Good afternoon, We have implemented a C++ cKeyArray class to test whether we can use the Large File API to save physical memory. During Centos Linux testing, we found that the Linux File API was just as fast as using the heap for random access processing. Here are the numbers: for a 2,700,000 row SQL database where th... | Your memory-mapped solution should be as much as 10x faster than the file solution even in Linux. That is the speed I experience in my test cases.
Each file access system call takes hundreds of CPU cycles to complete. Time which your program could be using to do real work.
One explanation for why the speeds are similar... |
5,251,496 | 5,251,675 | Compilation error in explicitly instantiated template methods | I've two different template classes. One of them has a member function that returns a pointer to an object of the other template class.
Currently, I'm not able to compile the code below and any suggestions are really welcome.
main.cpp
#include <stdio.h>
#include <stdlib.h>
#include <foo.h>
#include <bar.h>
int main(i... | The compiler can't deduce the template arguments -- it doesn't know whether you want to call CFoo<float>::doSomething<float>(int), CFoo<float>::doSomething<unsigned int>(int), or whatever. So, you have to explicitly tell it what the template arguments are:
// Explicitly call the function with BAR_TYPE=float
pBar = pFo... |
5,251,814 | 5,251,853 | C++ type of argument to ifstream::open() | What type must I make my file name to use it as an argument to ifstream.open()?
int main(int argc, char *argv[]) {
string x,y,file;
string file = argv[1];
ifstream in;
in.open(file);
in >> x;
in >> y;
...
With this code, I get the following error:
main.cpp|20|error: no matching function f... | The constructor takes a const char* (http://www.cplusplus.com/reference/iostream/ifstream/ifstream/) so you should do it like this:
in.open(argv[1]);
or if you really want to use the file string variable, then
in.open(file.c_str());
|
5,251,866 | 5,251,910 | Java program using JNI cannot find dependant shared objects outside of Eclipse | I have a program that is running inside eclipse right now and uses a JNI call to a shared object I created as a wrapper for another shared object on the system. This works just fine when I run it from inside eclipse however when I run it from the command line with the following command the shared object that the wrapp... | Have you checked the value of the LD_LIBRARY_PATH environment variable?
|
5,251,906 | 5,251,954 | How to calculate when a diminished value reaches a certain point? | I'm sure ive had this in school before, but i cant remember what is this thing called as.
I have arbitrary number and i need to know how many times i can multiply it by 0.9 (or any other value 0-1) until theres less than x left from the original number.
in a loop format it would look like:
num = 4654;
mult = 0.9;
limit... | Note that
num * (0.9)^k <= limit
is the inequality you wish to satisfy for some integer k, and you seek the smallest such k. Then
(0.9)^k <= limit / num
and
k * log(0.9) <= log(limit / num)
so that
k >= log(limit / num) / log(0.9)
where the inequality reverses because log(0.9) < 0. Thus, take the smallest integer k... |
5,252,034 | 5,252,050 | Cast a pointer to char to a double C++ | How can i cast a pointer to char to a double ?
I am using command line arguments and one of the argument is a double but in the program is it passed as a char*.
I tried using static_cast and reinterpret_cast but with no effect.
| Pure C++ solution:
#include <sstream>
// ...
std::stringstream ss;
ss << your_char_pointer;
ss >> your_double;
Boost solution:
#include <boost/lexical_cast.hpp>
// ...
your_double = boost::lexical_cast<double>(your_char_pointer);
|
5,252,039 | 5,252,294 | Test if fixed set is equal without branching | I have a set of integers (x, y, z) and a function that takes 3 integers (u, v, w). How can I test if (x,y,z) == (u,v,w)? The naive way is:
bool match = (x == u || x == v || x == w) && (y == u || y == v || y == w) && (z == u || z == v || z == w);
Does anyone know of some smart bit operations/arithmetic to do the same ... | In this case, you can replace the logical operations by bitwise operations to eliminate the branching:
bool match = (x == u | x == v | x == w)
& (y == u | y == v | y == w)
& (z == u | z == v | z == w);
However, you would have to measure the performance effect to see if this is faster or slower.
|
5,252,234 | 5,252,377 | working with char binary brings unexpected results | I have file where from I reading the first char - meaning the first 8 bits. That is exactly what I want. My code:
char content;
char * pcontent = &content;
src_f.read(pcontent, 1);
cout << (int)content << endl; //prints -62
cout << (unsigned int)content << endl; //prints 4294967234
But: I do understand the -62. Integ... | When you cast the content variable to an (int) or (unsigned int), you're converting it to a data type that is 32 bits wide. So the byte that you're reading in (which appears to be equal to 11000010 in binary) turns into 11111111 11111111 11111111 11000010. When this is read as an int, it equals -62, when read as an uns... |
5,252,375 | 5,252,544 | Custom C++ assert macro | I stumbled upon an informative article: http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/
which pointed out a great number of problems that exist in my current suite of debugging macros.
The full code for the final version of the macro is given near the end of the article if you follow the link.
The ... | In C and C++ standard library, assert is a macro that is required to act as a function. A part of that requirement is that users must be able to use it in expressions. For example, with standard assert I can do
int sum = (assert(a > 0), a) + (assert(b < 0), b);
which is functionally the same as
assert(a > 0 && b < 0)
... |
5,252,408 | 5,252,587 | C++ avoiding code duplication for const and non-const visitation | I have a class that should call a visitor method for every member variable. Something like this:
class A{
int a, b, c;
public:
void accept(Visitor &visitor){
visitor.visit(a);
visitor.visit(b);
visitor.visit(c);
}
};
How can I get void accept() const method with the same code witho... | You could create a class static template helper function that will deduce the constness based on the type of the this pointer you provide to it. Like this:
class A{
int a, b, c;
public:
void accept(Visitor &visitor){
acceptImpl(*this, visitor);
}
void accept(Visitor &visitor) const{
ac... |
5,252,612 | 5,252,645 | Replace space with an underscore | I am trying to write something that will replace all the spaces in a string with an underscore.
What I have so far.
string space2underscore(string text)
{
for(int i = 0; i < text.length(); i++)
{
if(text[i] == ' ')
text[i] = '_';
}
return text;
}
For the most part this would work, i... | The problem is that cin >> word is only going to read in the first word. If you want to operate on a whole like at a time, you should use std::getline.
For example:
std::string s;
std::getline(std::cin, s);
s = space2underscore(s);
std::cout << s << std::endl;
Also, you may want to check that you actually were able to... |
5,252,672 | 6,672,387 | scaling factor for CUFFT | I wrote a simple test program, where I was doing Complex to Complex FT's and I just generated some data 1..50 and stuck it in for the real and imaginary part for each index of the array.
When I do an operation like this IFFT(FFT(A)) = A
to test them out, I am getting different results for each library.
FFTW, I have to ... | This ended up being a problem with the way the absolute values of the complex number was being calculated. in the std::complex library, it was computing the distance of the vector.
|
5,253,002 | 5,253,239 | C++ Template specialization on a non-concrete type (another template class!) | I'm porting some code to use smart pointers in some places, and I ran into an issue with specialization. Specializing a template function on a concrete type is very straightforward, but what if I want to specialize a specific method on another templatized class (in my case, std::auto_ptr)? I can't seem to find the ri... | You cannot partially specialize a single member of a class template. (You can partially specialize the whole class template, with identical definitions except for that one member, but that's usually not fun.)
Instead, you can use overloaded function templates:
namespace ntSomeContainerImpl {
template <typename T>
... |
5,253,169 | 5,253,226 | Why can't I perform a std::copy on a vector of std::shared_ptr's in C++0x? | I've written a path class in my program for handling heirarchical path structures. I decided to use std::shared_ptr as the standard return type for the whole class since I'm getting rather fond it.
What surprised me is that I was unable to use std::copy or the normal vector.insert(v.begin(), v.end()) to copy elements ... | You're trying to make a back_inserter to the pointer to the vector, rather than the vector itself. Change back_inserter(ret) to back_inserter(*ret) (if you really feel the need to dynamically allocate vectors like that).
insert is failing because you're missing an argument:
ret->insert(ret->begin(), children->begin(),... |
5,253,418 | 5,253,444 | Do individual instances of C++ std::string use the same allocator? | One thing I've always wondered about is if the instances of std::string that I use in my C++ code use the same allocator or do they have their own separate memory pools?
Obviously sharing a single memory pool across multiple, frequently created and destroyed strings is more efficient. Can anyone confirm or deny this fo... | By default, they all use std::allocator, which uses standard memory routines to get free heap blocks. There is no pooling involved on this layer.
(However, most heap implementations use a dedicated low-fragmentation heap to serve small allocations, and strings are most likely to fall into this category. But this is im... |
5,253,461 | 5,253,617 | PHP packing some data | c++ struct:
struct Data {
unsigned char a;
unsigned char b;
unsigned char c;
UCHAR result;
short Number;
char Id[10];
int Admin;
int Blocked;
char Proj[13];
};
I maked this with php:
pack("C4sc10iic13", /** **/);
but it's not correct. I think
| Assuming UCHAR means unsigned char, your format string could be "CCCCsc10iic13". This is very similar to yours, only splitting out a b c and result into four Cs instead of a C4.
Perhaps you can also tell us exactly what's wrong?
|
5,253,661 | 5,253,728 | Remove pair duplicates from a std::set C++ | Hello I have a std::set of pair that contains the following elements:
set<pair<string, int> > mapElem;
apples 1
apples 2
at 1
eating 1
eating 2
football 1
going 1
today 1
today 2
today 3
today 4
today 5
tommy 1
tommy 2
I need to find a way to remove the duplicates and to remain only the ones with the highest second p... | map<string, int> aMap(mapElem.begin(), mapElem.end());
set<pair<string, int> > Temp(aMap.begin(), aMap.end());
mapElem.swap(Temp);
Without map:
set<pair<string, int> >::iterator nextit = mapElem.begin();
while (nextit != mapElem.end()) {
set<pair<string, int> >::iterator it = nextit++;
if (nextit != mapElem.end())... |
5,253,703 | 5,253,975 | Where do private variables live on the stack in C++ | I'm trying to overflow a buffer in C++ that is a private variable. Where does it live on the stack? Is this possible?
Something like
class aClass{
private:
char buffer[SIZE];
public:
}
| Er... Your question sounds like "What color is blue sky?". And the answer is, apparently, "blue".
When a variable is allocated "on the stack" it lives on the stack. There's no more detailed explanation to it. "On the stack" is the answer to "where?" question. Stack memory is uniform. There's no more detailed "where" th... |
5,253,705 | 5,253,755 | C++ Vector of Maps using an iterator how to | How can I populate a vector of map along with a rowID , or an iterator for each row of a valuepair Set
Like for example
typedef std::map<string, string> mapDB;
mapDB mapDB_colVal;
typedef mapDB::iterator mapDB_iter ;
vector<pair<int,mapDB> > mapDB_vec;
//populate mapDB_colVal 1st row
mapDB_colVal["X"]="APPLE";
mapDB_c... | mapDB_vec db;
//populate mapDB_colVal 1st row
mapDB_colVal["X"]="APPLE";
mapDB_colVal["Y"]="RED";
db.push_back(make_pair(some_row_id, mapDB_colVal));
//populate mapDB_colVal 2nd row
mapDB_colVal["X"]="PEAR";
mapDB_colval["Y"]="RED";
db.push_back(make_pair(some_other_row_id, mapDB_colVal));
I'm not sure what row IDs ... |
5,254,046 | 5,254,066 | Creating a Zip file programmatically C++ | I am trying to find a lib that will allow me to produce a zip file. I have a list of files that I want to place into the archive. The first suggestion I had was to use boost with zlib, however that turned out to be a dead end. I also looked at zziplib, however its a read only lib.
If anyone has any experience with doin... | Check out Zip Utils.
WARNING: This code has known bugs. It doesn't deal with non-ASCII filenames correctly. It doesn't deal with passwords correctly.
|
5,254,184 | 5,254,208 | Which is better: NULL or false? | I've been programming with SDL for a while, and I decide to make a header file to simplify my coding. Now I have a question; if I pass a function parameter I don't want, should I do
test(NULL);
from the Windows API I include or
test(false);
I use C++, NOT C.
| It completely depends on what the function parameter type is. If it's a pointer, and the documentation says that it's valid, then you can pass the C++ NULL (which is just 0 in reality).
Examples:
// Bad; strlen expects a pointer to a real, existing C-string buffer
std::cout << strlen(NULL);
/**
* Function that does s... |
5,254,559 | 5,254,682 | Consistency of two C FILE* streams on a single file | I need to implement a simple "spill to disk" layer for large volume of data coming off a network socket. I was hoping to have two C FILE* streams, one used by a background thread writing to the file, one used by a front end thread reading it.
The two streams are so one thread can be writing at one offset, while the ot... | This definitely will not give you the semantics you want. If you disabled buffering, it might be reasonable to expect it to work, but I still don't think there are any guarantees. Stdio/FILE is really not the right tool for specialized IO needs like this.
The POSIX way to do what you want is with file descriptors and t... |
5,254,560 | 5,254,592 | Fastest pre-packaged key-value pair search | I'd like to implement the following data structure in c++ (pseudo code):
Map<Integer, Integer> // Key->Value pairs
Map.put(1,6);
Map.put(2,5);
Map.put(6,89);
Map.put(7,23);
... etc ...
Map.get(2) .... returns 5
In other words, given pairs of integers, where one of them is a look-up key, what is the fastest librar... | Use an unordered_map (hashmap) or map (binary tree) - Likely unordered_map will be faster. Also, if your key value is limited to 10000, a vector<int> will guarantee constant-time lookup - Use a "magic" value for vector elements that should be "not present".
unordered_map is a part of TR1 and c++0x - it is not standard ... |
5,254,934 | 5,255,356 | Roman to decimal conversion | What do you think about this code? Is it the best way? Any improvement?
Roman.h
#ifndef ROMAN_H
#define ROMAN_H
#include <string>
#include <map>
typedef unsigned long int UL_I;
typedef std::map< std::string, UL_I, std::less< std::string > > Map;
class Roman_Number
{
public:
//Constructor
Roman_Number( std::stri... | How about this? http://codepad.org/mJ05BldC
#include <stdio.h>
int main( void ) {
const char* s = "MCDXLIV";
int x = 0; // result
int j,m=0; // max used digit
const char* p=s, *q; while(*p) ++p;
for( --p; p>=s; p-- ) for( q="IVXLCDM",j=0; *q; q++,j++ ) if( *p==*q )
x += ((j>=m)?m=j,1:-1) * (1+j%4/2*9) *... |
5,254,951 | 5,254,958 | How to put two backslash in C++ | i need to create a function that will accept a directory path. But in order for the compiler to read backslash in i need to create a function that will make a one backslash into 2 backslash.. so far this are my codes:
string stripPath(string path)
{
char newpath[99999];
//char *pathlong;
... | In this line:
if(newpath[i] = '\\')
replace = with ==.
In this line:
newpath[i] += '\\';
This is supposed to add a \ into the string (I think that's what you want), but it actually does some funky char math on the current character. So instead of inserting a character, you are corrupting the data.
Try this instead:
... |
5,254,991 | 5,255,021 | Is it possible to inherit from boost::function? | I'd like to know if it's possible to inherit from boost::function.
Basically, for ease of use, what I'd like to
is have a type "Delegate" which is basically a boost::function.
It's just for ease of use in some code I'm writing.
I at one point typedef'd boost::function to Delegate, but typedef'ing in my experience pla... | Deriving from a class does not automatically 'inherit' the base class constructors for the derived class. You will need to create all required constructors there.
|
5,255,104 | 5,255,288 | ASCII character problem on mac. Can't print the black square(which is char(219)) | When I'm trying to do this code in C++
cout << char(219);
the output on my mac is question mark ?
However, on PC it gives me a black square.
Does anyone have any idea why on mac there is only 128 characters, when it should be 256?
Thanks for your help.
| There's no such thing as ASCII character 219. ASCII only goes up to 127. chars 128-255 are defined in different ways in different character encodings for different languages and different OSs.
MacRoman defines it as €.
IBM code page 437 (used at the Windows command prompt) defines it as █.
Windows code page 1252 (us... |
5,255,309 | 5,255,330 | Should I write OpenGL program by using C or C++? Really confused | Should I write OpenGL program by using C or C++? Really confused.
| You can use either. The OpenGL API is in C and C++ is backward compatible with C. Just choose your favourite language.
|
5,255,372 | 5,525,335 | How to Implement Tab Completion | I'm trying to figure out how to implement tab completion for subcommands in a C++ application. I would like it to function much like Git's tab completion. I'm trolling through Git's source, but it's not jumping out at me.
I've searched for ways to implement tab completion and haven't found a straight-forward answer, so... | The question was answered in the comments.
Is tab completion a feature of the particular shell the application is being executed from?
yes
What are the basics I need to know about getting my application to support tab completion (particularly in C++)?
basically learn more about bash-completion
|
5,255,474 | 5,257,086 | Fast Fourier Transform | I need to multiply two polynomials each having small integral coefficients. I need a fast FFT routine in C/C++ which can convolve them. I have seen several libraries but they seem to be too large spread over multiple files. What is important is I need code which is not too long and can be very easily used and compiled ... | For a straightforward and easy to use FFT implementation try KissFFT. If you need absolute maximum performance though, and don't mind a little complexity, then it has to be FFTW.
|
5,255,515 | 5,255,947 | template parameter to boost multi index container | I need to create a generic class containing multiindex container as a storage. when I compile, it gives error as below where I have defined nth index view.
error: non-template ‘nth_index’ used as template
/**
* connection manager
*/
template < typename T, typename C >
class conn_mgr: boost::noncopyable {
public:
... | Use this syntax instead for your nested typedefs:
typedef typename conn_table_t::template nth_index<0>::type conn_table_by_id_type;
The typename keyword is used here as a qualifier to let the compiler know that conn_table_t::template nth_index<0>::type is a type. This special use of typename is only necessary within t... |
5,255,652 | 5,256,176 | C++ std::list as static member variable -- concurrency issues? | I wrote a class in charge of keeping track of error messages, which uses a static std::list to keep track of the messages. I subclass most other classes from this, to give them the ability to write to a common error log. At program close the error log is written to a file. This is a multithreaded application however... |
I wrote a class in charge of keeping track of error messages, which uses a static std::list to keep track of the messages.
it's not declared as static -- which is it?
EDIT: saw that was a typo, and that it should have been declared static. however, the suggestion at the end of the response may help you attain the bes... |
5,255,777 | 5,255,839 | What if I write return statement in constructor? | What if I write return statement in constructor? Is it standard conformant?
struct A
{
A() { return; }
};
The above code compiles fine, without any error at ideone. But the following code doesn't:
struct A
{
A() { return 100; }
};
It gives this error at ideone:
error: returning a value from a constructor... | Yes, using return statements in constructors is perfectly standard.
Constructors are functions that do not return a value. The family of functions that do not return a value consists of: void functions, constructors and destructors. It is stated in 6.6.3/2 in the C++ standard. The very same 6.6.3/2 states that it is i... |
5,256,028 | 5,256,053 | is boost::detail::atomic_count thread safe? | I'm incrementing/decrementing boost::detail::atomic_count in multiple threads.
Wonder if this practice is ok or if I need a lock around it(then I could just use regular int variable)?
Thank you.
| The entire purpose of an atomic variable is to be lock-free* and thread-safe.
So yes, it's perfectly safe; no, you don't need a lock.
*That is, the "lock" is done at hardware level. Are you using something without understanding it first? :)
|
5,256,066 | 5,256,536 | Are boost multi_index extracted keys cached? | I am using boost::multi_index with a data type I'd like to index based on its size. However, the size() member function of this data type is expensive to execute. Does multi_index cache the values it gets from its key extractors?
For example, if I created a multi_index container with an ordered index with a member func... | Well, the documentation for member function indexers says they call the referenced member function: http://www.boost.org/doc/libs/1_46_0/libs/multi_index/doc/reference/key_extraction.html#key_extractors
But when in doubt, profile:
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/mem_fun.hpp>
#incl... |
5,256,089 | 5,256,190 | how to solve following problem in C++? | I have one template function which will take a pointer type and i have instantiated it before calling.
i have written function with its dummy implementation as follows:
template<T>fun_name( const T *p )
{
//written functionality which will give me class name that i will store into string Variable
e.g. i got output ... | I think this :
template<typename T> // template<class T> is equally valid!
void fun_name( const T *p )
{
T::static_function_name(p);
}
is enough!
Two more errors is fixed in the above code:
Mention the keyword typename in template<T> in your code. You can also write template<class T> which is equally valid.
Ment... |
5,256,313 | 5,256,426 | C/C++ macro string concatenation | #define STR1 "s"
#define STR2 "1"
#define STR3 STR1 ## STR2
Is it possible to concatenate STR1 and STR2, to "s1"?
You can do this by passing args to another Macro function. But is there a direct way?
| If they're both strings you can just do:
#define STR3 STR1 STR2
This then expands to:
#define STR3 "s" "1"
and in the C language, separating two strings with space as in "s" "1" is exactly equivalent to having a single string "s1".
|
5,256,329 | 5,256,481 | converting uchar in c++ | How do I convert a uchar to an int?
| If uchar is typedef of unsigned char, then it's simple:
unsigned char c = 'A';
int i = c; //automatic conversion uchar into int!
Casting (i.e int i = (int)c) is overkill.
|
5,256,383 | 5,261,706 | Adding vectors within typedef map<set,vectors> | I've a data structure as follows
typedef vector<double> v_t;
typedef set<int> s_t;
typedef map<s_t, v_t> m_t;
Lets say the map m1 that has following values :
< <1>,<1,1,1,1> >
< <2>,<2,2,2,2> >
< <3>,<3,3,3,3> >
< <4>,<4,4,4,4> >
and I've a separate vector v1 that has values like
<1,3,4>
Now what I want to do is to... | I presume your code works now thanks to xitx's answer.
I couldn't find significant problems in your code particularly.
Incidentally, iterator doesn't need to be specified for insert member function
of set and map.
For your information, the following code worked when I tested:
int main() {
m_t m1, mtot;
s_t s;
s.c... |
5,256,449 | 5,260,390 | Where does the mysterious 200 connection come from? | Hey guys, i'm a newbie to async-programming, this is probably a stupid question, but it indeed drove me crazy!!
Here's the code (it just modified a bit from boost.asio's sample):
server.cpp:
class tcp_server
{
public:
tcp_server(boost::asio::io_service& io_service)
: acceptor_(io_service, tcp::endpoint(tcp:... | I've changed server.cpp a bit. First reconfigured acceptor_ on constructor. Removed while loop, added acceptor_.close();
#include <boost/asio/io_service.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
using namespace boost::asio;
using namespace boost::asio::ip;
class tcp_server
{
public:
tcp_server(bo... |
5,256,527 | 5,256,589 | Swapping blocks of elements in an array | I am working on C++.. am in a need to swap two blocks of elements in an array..
Say, {1,2,3,4,5,6} is my input array.. block {4,5} should be moved to beginning and the output array should be like {4,5,1,2,3,6}.. all i have is the start index and end index of the block {4,5}.. for doing this i am using a temp array, cop... | There is a standard algorithm designed specifically for this task called std::rotate():
#include <algorithm>
#include <cstdio>
int main()
{
int inputArray[] = {1, 2, 3, 4, 5, 6};
::printf("Before: ");
for(int i = 0; i < 6; ++i)
{
::printf("%d ", inputArray[i]);
}
::printf("\n");
in... |
5,256,663 | 5,256,727 | make: c: command not found | I am attempting to run my make file however i am getting the following two errors:
make: c: command not found
and
make: o: command not found
I am attempting to do this inside of cygwin. I have g++ and make installed on it, however when I run the make file I receive these errors.
Any ideas?
The makefile:
all: MergeSort ... | You need to remove the $ from the $g++ lines. It's trying to expand some variable that doesn't exist, and is swallowing up the "$g++ -" from your commands.
The syntax for using a variable is:
$(CXX) -c main.cpp
In this case, CXX is the path to the C++ compiler, which is defined for you. You can change it by adding t... |
5,256,715 | 5,256,753 | Can we access typedef'ed types via an instance? | I wondered,
for(std::map<int, double, std::greater<int> >::iterator it = mymap.begin(); it != mymap.end(); ++it)
{
//do stuff
}
Why am I not able to write this as:
for(mymap::iterator it = mymap.begin(); it != mymap.end(); ++it)
{
//do stuff
}
Of course, typedeffing the map would make the first code less verb... | :: is a scope resolution operator that expects type name or namespace name on the left-hand side. It doesn't accept object names on the left-hand side. Allowing this would probably overcomplicate a lot of things in the language.
In fact, if one would to allow something like this, one'd probably attach this functionalit... |
5,256,848 | 5,256,866 | Nontype template parameter | I'm having trouble with nontype(int variable) template parameter.
Why can't I pass a constant int variable to a function and let the function instantiate the template?
template<int size>
class MyTemplate
{
// do something with size
};
void run(const int j)
{
MyTemplate<j> b; // not fine
}
void main()
{
const i... | Because non-type template parameters require values at compile-time. Remember that templates are a compile-time mechanism; templates do not exist in the final executable. Also remember that functions and the passing of arguments to functions are runtime mechanisms. The value of the j parameter in run() will not be know... |
5,257,049 | 5,257,150 | What is the most elegant way to write a text/binary file with c++? | I found some good results on reading e.g.: Read txt with iterators and preallocation, or read into containers. So I wondered how would I write most elegant a std::string into a file?
Edit: When reading I can preallocate space for the string via seek and tellg, since I know the size of the string, how could I tell the f... | Here's a tiny example on how to output a std::string, but you should really read up on fstream
#include <iostream>
#include <fstream>
#include <string>
int main(int argc, char *argv[])
{
std::string s("writemeout");
std::ofstream outfile("output.txt");
if(!outfile.is_open()) {
std::cerr << "Couldn't open 'o... |
5,257,190 | 5,257,257 | Are Exceptions still undesirable in Realtime environment? | A couple of years ago I was taught, that in real-time applications such as Embedded Systems or (Non-Linux-)Kernel-development C++-Exceptions are undesirable. (Maybe that lesson was from before gcc-2.95). But I also know, that Exception Handling has become better.
So, are C++-Exceptions in the context of real-time appl... | Exceptions are now well-handled, and the strategies used to implement them make them in fact faster than testing return code, because their cost (in terms of speed) is virtually null, as long as you do not throw any.
However they do cost: in code-size. Exceptions usually work hand in hand with RTTI, and unfortunately R... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.