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,658,975 | 5,659,233 | C++ get Processor ID | This thread is ok.
How to get Processor and Motherboard Id?
I wanted to get processor ID using C++ code not using WMI or any third party lib.
OR anything on a computer that turns out to be unique.
One thing is Ethernet ID but which is again removable on some machines. This I want to use mostly for licensing purpose.... | I had a similar problem lately and I did the following. First I gained some unique system identification values:
GetVolumeInformation for HDD serial number
GetComputerName (this of course is not unique, but our system was using the computer names to identify clients on a LAN, so it was good for me)
__cpuid (and specif... |
5,659,064 | 6,288,358 | Conditional compile-time inclusion/exclusion of code based on template argument(s)? | Consider the following class, with the inner struct Y being used as a type, eg. in templates, later on:
template<int I>
class X{
template<class T1>
struct Y{};
template<class T1, class T2>
struct Y{};
};
Now, this example will obviously not compile, with the error that the second X<I>::Y has already been defi... | There are two problems here:
enable_if works with partial specialization, not primary templates.
The number of externally-visible arguments is determined by the primary template, of which there may be only one.
Answer 1.
As you suggested in chat, a linked list of templates can emulate the variadic parameter pack.
tem... |
5,659,099 | 5,659,127 | How to turn boost::shared_ptr<> into a reference (&)? | So I have a class that uses references (&) with functions like
void request(tcp::socket& socket);
I am starting migrating all my code to boost::shared_ptr<tcp::socket> but I would really like to know how to turn my shared_ptrs into references so to be capable to make my code evolve function by function and not in on... | First, they're not called links, but references. :)
Second, the boost::shared_ptr can just be dereferenced like normal pointer:
boost::shared_ptr<tcp::socket> p(new tcp::socket());
// can be done in two steps (dereference, pass)
tcp::socket& socket_ref = *p;
request(socket_ref);
// or one step
request(*p);
// ^ --... |
5,659,157 | 5,659,629 | Why different behavior for "TYPE* const" pointers? | Below code is dealing with a TYPE* const pointer.
struct D {
void Check ()
{
D* const p = new D; // 2nd test is "p = 0;"
cout<<"p = "<<p<<endl;
(D*&)p = new D;
cout<<"p = "<<p<<endl; // prints 0, "p = 0;" at declaration
}
};
int main ()
{
D o;
o.Check();
}
My questions are,
If you initializ... |
As others have said, this is undefined behaviour since it attempts to modify a const object. If you initialise it with zero then the compiler might treat it as a compile-time constant, and ignore any attempt to modify it. Or it might do something entirely different.
this is not an ordinary variable of type TYPE * cons... |
5,659,166 | 5,659,632 | Is it possible to call derived object's virtual method when down-casted from base class? | Given the following class structure:
class Base
{
virtual void outputMessage() { cout << "Base message!"; }
};
class Derived : public Base
{
virtual void outputMessage() { cout << "Derived message!"; }
}
.. and this code snippet:
Base baseObj;
Derived* convertedObj = (Derived*) &baseObj;
convertedObj->outputM... | No Standard-compliant solution
What you're trying to do isn't possible using behaviours guaranteed by the C++ Standard.
If you really MUST do this as a short-term measure to assist your migration, don't depend on it in production, and can adequately verify the behaviour, you could experiment as illustrated below.
Discu... |
5,659,420 | 5,660,254 | Setup VisualC++ to use OpenGL 4.1? | I'm trying to setup VC++ to compile code with OpenGL 4.1 functionality. I downloaded the 3 header files from from opengl.org; put them in the correct paths and include them - but keep getting errors like this:
error C3861: 'wglSwapIntervalEXT': identifier not found
I have the latest video drivers. OpenGL says the p... | One of the big pains of using OpenGL on Windows is that the Windows SDK only ships with OpenGL 1.1. There's probably a really good technical (and non-political) reason for this, but the fact remains, if you want to do anything with OpenGL on Windows, you're on your own.
What you need then, is something to bring the Win... |
5,659,659 | 5,659,724 | How write good round_double function in c++? | I'm trying to write good round_double function which will round double in specified precision:
1.
double round_double(double num, int prec)
{
for (int i = 0; i < abs(prec); ++i)
if(prec > 0)
num *= 10.0;
else
num /= 10.0;
double result = (long long)floor(num + 0.5);
f... | Don't cast to long long that is forcing a conversion to an integer with limited range, beyond what 10^13 requires (well 19 for 64-bit with no whole number part). Just calling floor should be enough.
double round_double(double num, int prec)
{
double tmp = pow(10.0, prec);
double result = floor(num * tmp + 0.5)... |
5,659,738 | 5,659,802 | C++ variable no longer exists | #include <exception>
#include <iostream>
#include <cstdio>
using namespace std;
class BaseException : exception {
public:
BaseException(const char* message) : message(message) {}
const char* getMessage() {
return message;
}
private:
const char* message;
};
void wrong() {
unsigned short in... | //why commented below is not works
char tmp[13 + sizeof(argumentCallCounter)];
It would not work because tmp is local to the function, and it not more exists once you exit from the function, but you're still trying to access it from main().
I would suggest you to use std::string in BaseException and everywhere else.
I... |
5,659,744 | 5,659,844 | binary tree -print the elements according to the level | This question was asked to me in an interview:
lets say we have above binary tree,how can i produce an output like below
2 7 5 2 6 9 5 11 4
i answered like may be we can have a level count variable and print all the elements sequentially by checking the level count variable of each node.
probably i was wrong.
can an... | You need to do a breadth first traversal of the tree. Here it is described as follows:
Breadth-first traversal: Depth-first
is not the only way to go through the
elements of a tree. Another way is to
go through them level-by-level.
For example, each element exists at a
certain level (or depth) in the... |
5,659,875 | 5,660,025 | Custom Layout in Qt Designer | Is there anyway that we can have Custom Layouts e.g. as defined at
https://doc.qt.io/archives/qt-4.7/examples-layouts.html
inside the Qt Designer ?
What would be the process to add such custom layouts in the Qt Designer? Can anyone guide about the steps involved for such custom enhancement in Qt Designer.
| You can't create custom layout right inside QtDesigner. Instead you can write your layout as a plugin for QtDesigner. After this you can open QtDesigner and just drop your own layout to the form as any other widget in the Qt collection.
See this quide to find out how to write your own plugin for Qt. It's not so difficu... |
5,659,994 | 5,660,182 | Qt - Some questions about a header file | I have some questions about this header file from the C++ GUI Programming with Qt 4 book:
#ifndef GOTOCELLDIALOG_H //Check if GOTOCELLDIALOG_H has not been defined previously
#define GOTOCELLDIALOG_H
#include <QDialog>
#include "ui_gotocelldialog.h"
class GoToCellDialog: public QDialog,
public Ui::GoToCellDialog {
... | 1) This is called a header guard. It makes repeated inclusion of that header idempotent, i.e.
#include "gotocelldialog.h"
#include "gotocelldialog.h"
does the same as
#include "gotocelldialog.h"
This may look weird. In practice, this happens indirectly. Just look at how often "qobject.h" gets included in a single fil... |
5,660,103 | 5,660,190 | Qt - What do we mean by those code snippets | I just have those questions about those code sinppets from the C++ GUI Programming with Qt 4 book:
GoToCellDialog::GoToCellDialog(QWidget *parent):QDialog(parent)
Does that mean we are inheriting QDialog(parent)? Or, what exactly does this mean?
setupUi(this);
Here, this code snippet is part of the gotocelldialog.cpp... | GoToCellDialog::GoToCellDialog(QWidget *parent) : QDialog(parent)
: signifies an initializer list. And it meant, parent is being passed as a parameter to QDialog constructor. I assume GoToCellDialog is derived from QDialog and so sending parent to it's constructor. So, before even body of GoToCellDialog is executed, Q... |
5,660,138 | 5,660,261 | recursion & returning boolean values | bool binsearch(string phrase, vector<string> words, int from, int to, int &test)
{
while (tf == "y") //tf is a global variable
{
int mid = (to+from)/2;
if (words[mid] == phrase) {tf = "t"; return true;}
if (mid == test) {tf = "f"; return false;}
if (words[mid] > phrase) {return b... | I don't understand your binary search either, and using global variables in addition to recursion leads to programs which are very hard to understand. It's better to go back the call stack again and "unwind" it properly. Look at the following example (untested):
bool binsearch(const string& phrase, const vector<string>... |
5,660,213 | 5,660,983 | Parallelization of neighborhood point deletion | I am implementing the Good Features To Track/Shi-Tomasi corner detection algorithm on CUDA and need to find a way to parallelize the following part of the algorithm:
I start with an array of points obtained from an image sorted according to a certain intensity value (an eigenvalue of a previous calculation).
Startin... | I think the article Accelerated Corner-Detector Algorithms describes the way to solve this problem.
|
5,660,239 | 5,660,323 | Where to create session instances? | So I am creating C++ HTTP emulating via TCP server. I will have simple authentification service which will be created in C++. I will have sessions. I wonder which form shall I give them - real files on server or lines in SQL Lite db I use for my server? Or just keep them in RAM? Which way is better for performance / sa... | It all depends what you want to do:
keep them in sqlite is safer than file (you're sure it's either written or not, no half status). Moreover, it's either to fetch your session with a query. In that sense, it's safer
keep them in RAM will be better in terms of performance, but all sessions will be lost when you restar... |
5,660,385 | 5,660,671 | Select underlying objects | Greetings!
I've made a program that lets you draw shapes. All shapes are contained in a vector. What I need help with is; when several shapes are stacked on top of each other, I want to cycle through them, top to bottom, if the user clicks repeatedly. I'm thinking something along the lines of:
Store every object under... | A popular approach to this is to assign each item a z-order. Items with higher z-order hide items with lower z-order if they overlap. In your case, you would just have to find all items below the cursor and rotate their z-orders when the user clicks.
|
5,660,527 | 5,660,565 | How do I return a char array from a function? | I've tried the following:
char[10] testfunc()
{
char[10] str;
return str;
}
| Best as an out parameter:
void testfunc(char* outStr){
char str[10];
for(int i=0; i < 10; ++i){
outStr[i] = str[i];
}
}
Called with
int main(){
char myStr[10];
testfunc(myStr);
// myStr is now filled
}
|
5,660,696 | 5,660,764 | Idiomatic "guaranteed-unique" identifiers in C++ | Is there an idiomatic C++ way to reserve and recycle identifiers that are guaranteed to be unique? My requirements are:
Assuming there exists an ID not currently reserved, reserve_id(void) returns me that ID.
In an unbroken sequence of reserve_id() calls, no single identifier will be returned twice
There exists a func... | I think you've already solved this problem for most practical purposes by finding Boost::Uuid, with the exception of your requirement to recycle identifiers already generated.
From the documentation you linked to in the question:
When UUIDs are generated by one of the
defined mechanisms, they are either
guaranteed... |
5,660,851 | 5,660,918 | Executing base function before continuing in derived function | I'm trying to solve a problem where I have some classes in which I need to do some common work and then a bunch of problem specific work and when this is finished do some more processing common to all these classes.
I have a Base and Derived class that both have a function called Execute. When I call the derived vers... | Use a pure virtual function from base..
class Base
{
public:
void Execute();
private:
virtual void _exec() = 0;
};
Base::Execute() {
// do some common pre work
// do derived specific work
_exec();
// do some more common work...
}
class Derived : public Base
{
private:
void _exec() {
// do... |
5,660,938 | 5,661,391 | How to detect if my service is running in a TSE session? | I have written a service that should behave in a special way when running on a TSE server, in session 0.
My lookups on the Internet gave me the following function:
GetSystemMetrics(SM_REMOTESESSION)
Which indeed returns TRUE when my service is running in an user session on the TSE server. However, it still returns FAL... | A quick hack is to see if the CLIENTNAME and SESSIONNAME environment variables are set.
The catch is that it might not be available when launched in a separate process on the server, but since you are on W2K8 you should be fine.
|
5,660,958 | 5,666,673 | coupling - C++ web or GUI desktop apps | How to handle coupling in advanced C++ applications?
Can we use finished code for web application, written (for e.g.) with Witty, and make console application with it? ...or change it to desktop application with GUI made with Qt?
yes / no and why?
how to make it most possible and easy?
| It depends on how your application was developed. Have you used design patterns and other techniques like MVC in the web application? If so, I think you can develop console application without doing many changes. If you haven´t, you will have to refactor some code.
|
5,661,122 | 5,661,145 | getline(cin, var) not working! | For some strange reason, the getline() function is not working as it should. I have my program loop via recursion (return main();). The first time the following code is run, it's fine.
cout << "Enter a phrase: ";
string user;
getline(cin, user);
However, after the recursion is invoked, the program skips the step t... | call cin.clear() to clear any flags before looping around.
EDIT: Thanks to @Xeo for pointing out, should also call cin.ignore() to discard the new line character - which could still be in the buffer...
|
5,661,218 | 5,661,271 | Is is necessary to have the 'const' in declaring char const *ptr = "some characters"? | Since they both point to characters which can not be modified. What is the benefit of having the const in the first one? Is it just to tell the compiler to watch out for any code that may do something like ptr[1] = 'a'
char const *ptr = "some characters"
char *ptr = "some characters"
| Yes, so that when you try to modify the contents through the pointer you will get a compiler error instead of nasty surprises at the run time.
|
5,661,241 | 5,700,362 | Importing C++ DLL into C# Smart Device Application | I am asking this question after I looked up tons of blogs and webpages and tried almost everything people explained.
I have no problem with importing C++ Win32 DLL into C# Windows Application. And it was actually straight forward.
But what I am trying to do is importing C++ DLL into C# "Smart Device Application," espec... | Sorry, I was being really stupid.
The reason why the application could not load the DLL file was because I was running debug on a mobile device. And it caused a path problem.
So I manually copied the DLL file and application's EXE file to the mobile device and ran the program. It worked perfectly fine.
Hans (commenter)... |
5,661,302 | 5,681,511 | Do I need a cvReleaseImage if image is returned? | I'm working with OpenCV 2.2 and I'm wondering if I have to release the memory I allocated for an image if the image is returned. I have method1 (see below) that is called from the main program several times. It returns an IplImage that was created inside the method.
Where do I have to release the image created in the ... | You can allocate memory within the function. Once you returned the image in the calling function after using dst you can call cvReleaseImage( &dst ) to clear the memory
|
5,661,380 | 5,661,691 | Idea for keep information about visited states | I making now 15-puzzle solver (in c++), but instead of only 15-puzzle, my program must to solve also 3x4 puzzles, 8x8 puzzles, etc... - > X x Y puzzles. I must somehow keep information about visited states, my first idea was to make tree, for example:
Puzzles:
State 1
1 2
3 0
State 2
1 3
0 2
I keep in my t... | I'd represent a single state as a BigInteger number (a c++ implementation available here, or if you'd like to implement your own here is a thread on that, too).
Assuming you have a puzzle with (X,Y) dimensions, you'd create a number using base = X*Y, and the the digits of this number would represent the puzzle pieces f... |
5,661,637 | 5,662,580 | Default parameter for partial specialization | What syntax I want to achieve on user side:
double a(1.), b(2.), deps(.1);
bool res1 = compare<double>()(a, b); // works with default eps
bool res2 = compare<double, &deps>()(a, b); // works with explicitly provided eps
float c(1.), d(1.). feps(.1);
bool res3 = compare<float>()(c, d); // don't have default eps... | I don't know why you think that this make sense
compare<double, deps>
You cannot make this work: Template arguments cannot be values of type double (they can be an lvalue of type double, but your template requires the address of a double, so that's off).
You can use function templates to make your syntax work
extern ... |
5,661,642 | 5,661,710 | C++: case-insensitive first-n-characters string comparison | My question is similar to this, but I have two strings (as char *) and the task is to replace strnicmp function (avaible only for MS VC) with something like boost::iequals.
Note strnicmp is not stricmp - it only compares first n characters.
Is there any solution simplier than this:
void foo(const char *s1, const char ... | If it's really necessary, write your own function:
bool mystrnicmp(char const* s1, char const* s2, int n){
for(int i=0; i < n; ++i){
unsigned char c1 = static_cast<unsigned char>(s1[i]);
unsigned char c2 = static_cast<unsigned char>(s2[i]);
if(tolower(c1) != tolower(c2))
return false;
if(c1 == '... |
5,661,831 | 5,685,702 | Handling COM events in C++ (ATL, MFC or pure C++) for Java interop | I'm currently trying to build a C++ library (DLL file) that interfaces with a COM component, to make it usable in Java. The idea was that I'd build a very small C++ DLL with a class that "wraps" around the COM component, and then export it using SWIG. I got pretty far by using an #import statement:
#import "ComponentNa... | I actually got this working myself using the Unified Event Model. Some notes from my experience in getting it working:
You need to initialise ATL otherwise a null pointer error occurs when hooking up events. If you don't want to use ATL in your project (like I didn't - My project is plain C++), something like this in ... |
5,662,035 | 5,662,082 | How can I address a COM object identified by a given IUnknown* from another process? | I wrote two small C++ applications, one of which is an ActiveX container embedding some ActiveX control. This container application knows the IUnknown* referencing the ActiveX control.
The other application is a client which shall interact with the ActiveX control in the former application. However, I don't know how to... | You may want to look at RPC in general, and COM Proxies.
A proxy resides in the address space of the calling process and acts as a surrogate for the remote object. From the perspective of the calling object, the proxy is the object. Typically, the proxy's role is to package the interface parameters for calls to method... |
5,662,078 | 5,662,124 | Including new header file to standard library in C++ | I wrote a simple C++ program to parse an XML string, called sample.cpp. The program includes a header file, tinyxml.h. When I compiled the program on a unix machine I got the error:
tinyxml.h: No such file or directory
How can we add new header files to the standard library and make them compile? Can anyone please h... | You need to tell your compiler where to find the header file. This depends on the compiler, but is typically done by specifying -I<directory> on the command line.
|
5,662,206 | 5,662,469 | How do I parse an expression with nested parenthesis with boost.Spirit? | I need to parse 1-line expressions containing key/value pairs and key/subexpression pairs, like:
123=a 456=b 789=(a b c) 111=((1=a 2=b 3=c) (1=x 2=y 3=z) (123=(x y z))) 666=evil
To make the parser simpler, I'm willing to do the parsing in several steps, separating the first-level tags (here 123, 456, 789, 111 and 666,... | You could write it as:
qi::rule<std::string::iterator, std::pair<std::string, std::string>()> pair =
key >> -(
'=' >> ( '(' >> raw[query] >> ')' | value )
)
;
which will store all embedded queries as values (strings) associated with the key. This will drop the parenthesis from the store... |
5,662,719 | 5,662,867 | C++: Comparing pointers of base and derived classes | I'd like some information about best practices when comparing pointers in cases such as this one:
class Base {
};
class Derived
: public Base {
};
Derived* d = new Derived;
Base* b = dynamic_cast<Base*>(d);
// When comparing the two pointers should I cast them
// to the same type or does it not even matter?
bool... | If you want to compare arbitrary class hierarchies, the safe bet is to make them polymorphic and use dynamic_cast
class Base {
virtual ~Base() { }
};
class Derived
: public Base {
};
Derived* d = new Derived;
Base* b = dynamic_cast<Base*>(d);
// When comparing the two pointers should I cast them
// to the same... |
5,662,723 | 5,662,982 | Typename lookup of return parameter | I was recently asked by a student about a compile issue. The answer was quite simple but right now I am struggling about the reason.
A simple example:
#include <iostream>
#include <vector>
struct MyStruct
{
typedef std::vector<int> MyIntVector;
MyIntVector CopyVector(MyIntVector const& vector);
};
MyStruct:... | The structure of the grammar is such that the return type is independant of what is declared and it is possible to declare (but not define) several things with the same type. This is valid C++:
int f(int), g(int);
so having the precise scope of the declared objects influencing the lookup for the type would be problem... |
5,662,797 | 5,663,511 | Double dispatch without knowing the full hierarchy | I would like to implement the following thing in C++:
I would like to have a bunch of child classes of a single class with the ability to call a function that takes a pair of objects of any of these types. There is supposed to be a generic implementation that is called for mixed types or the base type and specialised i... | Since the derived classes only need to detect if the parameter type matches the object type, you can just use a straightforward check.
virtual void foo( base *argument_base ) {
if ( derived *argument = dynamic_cast< derived * >( argument_base ) ) {
argument->something = pair_match_foo;
} else {
... |
5,662,910 | 5,663,023 | Simple array in array in C++ | I'm collecting a set of colors in separate arrays. After then i want to store all of them in an array that contains these arrays, so i can iterate through all colors at once. i want to do it like this:
const float COLOR_GREEN[3] = {0.00f, 1.00f, 0.01f};
const float COLOR_LIGHT_PURPLE[3] = {0.99f, 0.00f, 0.99f};
co... | You can change this line to:
const float* COLOR_LIST[15]
|
5,662,938 | 5,663,006 | Return parameter can't be accepted in c++ template | I am writing a template for binary tree and don't understand why I can't return Node* from one of my functions in that template.
Code:
template<class T>
class Binary_Tree{
private:
struct Node{
T* data;
Node *left,*right;
Node(T* dat, Node* l, Node* r) : data(dat),left(l=0),right(r=0) {}... | By definition, your node is private, so why would you want to return in a public method a private type ?
Moreover, sometime, compiler have hard time with templates, sometime, you need to let them know if a specific label is a variable or a type. You can use typename key word for that.
Additionally, you can have your no... |
5,663,057 | 5,663,139 | Qt - initializing the form | When we call setupUi(), we are initializing the form.
What does initializing the form mean? What happens if we don't call it?
Thanks.
| When "setupUi()" is called, all the UI elements that the user put on the form are created. Essentially, UIC tool gets information of what UI elements you put on the form in Qt Designer and generates the code like this for you so you don't need to do that manually:
QPushButton *button1 = new QPushButton(parent);
button1... |
5,663,076 | 5,663,325 | Shared_Ptr of socket creation - what is wrong? | So I try:
boost::shared_ptr<tcp::socket> socket =
boost::make_shared<tcp::socket>(io_service);
As described here. But It bring me an error:
Compiler tells me that it can not turn (
error C2664:
boost::asio::basic_stream_socket<Protocol>::basic_stream_socket(
boost::asio::io_service &))
'boost... | You need to pass the io_service as a reference when using make_shared.
boost::shared_ptr<tcp::socket> socket =
boost::make_shared<tcp::socket>(boost::ref(io_service));
|
5,663,083 | 5,663,224 | Linking Fortran and C++ binaries using gcc | I can use gcc to make calls between C and C++ or between C and Fortran by using g++ or gfortran, respectively. But if I try to make procedure calls between C++ and Fortran I get errors when compiling with either g++ or gfortran because neither knows about the other's required libraries.
How can I link a project that u... | You're looking for
g++ main.o print_hi.o -o main -lgfortran to link in the standard Fortran libraries.
You can also use gfortran by passing -lstdc++.
|
5,663,097 | 5,663,180 | GCC -lm -lz -lrt options - what are they about? | I know that these are some common/basic libraries, but what do they mean exactly?
For example, I know, that -lm is some math library, but is this the standard math library or what?
-lz for compression? What compression?
And I don't have any idea what -lrt is.
What are these things?
math library. Is it the same that w... |
-lz - is zlib, http://zlib.net/
-lm - is the math library as you've worked out (implementation defined AFAIK)
-lrt- provides POSIX realtime extensions: http://www.s-gms.ms.edus.si/cgi-bin/man-cgi?librt+3LIB
|
5,663,158 | 5,663,286 | How to define project wide constants or how to make my own class' memberfunction accept const objects in c++ | In my C++ project I've got a number of constants that I want to access from different classes . I put them all into a .h file that I named constants.h (I am not sure if this is the best idea, but it helped me keeping things sorted)
Now I have the problem, that if I include that in more than one cpp file, I get LNK2005 ... | Object with external linkage must be defined once. In
v3d vect1(1, 2, 3.14);
vect1 has external linkage. So you'd have to use
extern V3d vect1;
in the .h and then
v3d vect1(1, 2, 3.14);
in one .cpp. There is a special rules which makes
const int myint = 3;
have internal linkage if it is never used as a lvalue, ... |
5,663,239 | 14,736,374 | Use the C++ STL in Enterprise Architect | How is it possible to use parts of the C++ STL in Enterprise Architect?
It would be nice to be able to specify certain class attributes as std::string or use std::auto_ptr (or even std::tr1::shared_ptr) as types.
Another interesting thing would be how one is able to integrate container-types like std::vector and std::m... | I have taught how STL containers look like to EA, I guess it can be extended to stl pointers too:
Forward engineering:
You can define collection classes for different multiplicities globally in the language settings, or for a specific class of your project (this will define how it is "contained" in other classes) this... |
5,663,399 | 5,686,304 | Some design issues with C++ | I have the following dilemma here: I have a few classes, let's say A, B, C and D. A has a public interface, and a has-a relationship with B (like A is having a member variable of type B) and one of the methods of A is returning this B object, B is just a class who exposes some methods, C is another class which exposes ... | Most of the information you provide should be recognizable in the following class
diagram(plantuml input). I hope that answers the first question.
@startuml
class A
A o--> B
A : + method()
A : + B& getB()
A : - B m_B
A --> "getC" D
class B
B : + method()
B --> "getC" D
class C
C : + method()
class D <<Singleton>>... |
5,663,407 | 5,686,836 | Incorrect interop signature causing memory leak | A 3rd party com module being used from c# via interop generated interface is leaking memory
The 3rd party c++ method signature is:
somemethod(....., long** param3, long** param4)
The generated interop method is:
somemethod(...., IntPtr param3, IntPtr param4)
The last 2 params are assigned arrays by the umanaged dll, ... | Found 'a' way to get expected functionality, not sure how sound the solution is. Following works without leaking
long* arr1 = null;
long* arr2 = null;
IntPtr parr1 = new IntPtr(&arr1);
IntPtr parr2 = new IntPtr(&arr2);
somemethod(....., parr1, parr2);
Marshal.CoTaskMemFree(new IntPtr(arr1));
Marshal.CoTaskMemFree(ne... |
5,663,601 | 5,663,743 | What is the difference between false and FALSE? | In many programs, I see statements with the identifiers FALSE and false. Is there any difference between them in the context of C++?
Also in some programs, I saw bool and somewhere BOOL. What is the difference between both of these?
Can anyone explain the difference between these identifiers to me? Thanks.
| If you've included windows.h, then FALSE is #defined as 0. TRUE is #defined as 1. It is not a Boolean type, it's an integer type. Windows also defined the type BOOL, which is actually an integer type designed to accomodate the values TRUE and FALSE.
The relevant sections of code in windows.h look something like this:
#... |
5,663,695 | 5,663,753 | Sorting an array according to other array | I have an array with arrays of two elements. Now I would like to sort all values ending at zero (e.g. arr[3][0], arr[1][0]) to be sorted from low to high.
Then I would like to have the values ending at 1 (e.g. arr[2][1], arr[1][1]) to also be sorted, but not on its own order, but in the same order as the first array.
H... | Just implement your own search algorithm (use bubble sort or whatever you think might be most efficient) and do the comparison/swapping similar to the following pseudo code:
if(a[i][0] > a[j][0])
{
t[0] = a[i][0];
t[1] = a[i][1];
a[i][0] = a[j][0];
a[i][1] = a[j][1];
a[j][0] = t[0];
a[j][1] = t[... |
5,663,837 | 8,226,736 | Customize QScrollBar intersection using stylesheet Qt | I’ve already customize my horizontal and vertical scrollbars using a stylesheet no problem.
But there still an annoying tiny area which remains blank :
The intersection of an horizontal and vertical bar. A small rectangle.
How could I change its color ? (Using stylesheets )
Thank you !
Qt 4.7.1 on Mac OSX Snow Leopard
... | I realise this is an old question, but I found a better solution.
QAbstractScrollArea::corner {
background: somecolor;
}
Or, to hide it, use:
background: transparent;
|
5,664,049 | 5,668,632 | Site like cplusplus.com for C++11 | One simple question: does anybody know a site like cplusplus.com (that has functions and headers nicely organized, includes examples(that is very important to me)) and that it is up to date(C++11).
I ask because I'm unable to find any site like that. Also I can't understand the c++ standard PDF, when it comes to readin... | I surveyed the msdn documentation Ashot refers to. I thought it would be interesting to note which headers are not standard in this list (are extensions), and which C++11 headers are currently missing. Here's the results:
<algorithm>
<allocators> // not standard
<array>
<atomic> // missing
<bitset>
<cassert>
<c... |
5,664,199 | 5,664,260 | What's a better way to store information than by using static ints? C++ | I'm keeping track of a player's "job" by setting his job to a number, and incrementing it by one if he changes job, and determining which job he currently is by whether the number is even or odd. (Only two jobs right now). However, I know there are better ways of doing this, and soon I'll need to implement for a third ... | Don't use static variables to save anything like that inside a class. Use a member variable instead.
IMO the easiest way to do something like that and make it extensible is using a enum:
enum PlayerJob
JOB_NONE = 0,
JOB_GEOLOGIST,
JOB_LANDMAN,
...
NUM_JOBS // this element is optional but can be usef... |
5,664,224 | 5,664,353 | Logging code execution in C++ | Having used gprof and callgrind many times, I have reached the (obvious) conclusion that I cannot use them efficiently when dealing with large (as in a CAD program that loads a whole car) programs. I was thinking that maybe, I could use some C/C++ MACRO magic and somehow build a simple (but nice) logging mechanism. For... | Well you could do some C++ magic to embed a logging object. something like
class CDebug
{
CDebug() { ... log somehow ... }
~CDebug() { ... log somehow ... }
};
in your functions then you simply write
void foo()
{
CDebug dbg;
...
you could add some debug info
dbg.heythishappened()
...
} // not dt... |
5,664,338 | 5,664,496 | [UNIX] : Do I need to add all libraries in my project's makefile, that are used from a library, used in my project? | Ha, this sounds more complicated, than it actually is. Here's what I mean:
Suppose I write an application, that uses threads. In this application, I don't use the pthreads directly, but I use a wrapper, that uses pthreads. So, in this wrapper's makefile, -lpthread must be included. And the question - do I need to inc... | This is where you do a mistake:
So, in this wrapper's makefile,
-lpthread must be included
A static library created by the ar tool is just a collection of object files in a special file format that is recognised later by the linker. This collection of code isn't linked to any library. Specifying -lpthread when comp... |
5,664,546 | 5,664,657 | templated function pointer, is this possible? | template<typename T>
std::vector<unsigned>
Traverse
(
unsigned start_node,
std::priority_queue
<
std::pair< unsigned, unsigned >,
std::vector< std::pair<unsigned, unsigned> >,
bool(*T)(const unsigned&, const unsigned&)
> &pQueue
) const;
The above code basically doesnt compile. I think its syntax... | Try this:
template<typename T>
std::vector<unsigned>
Traverse
(
unsigned start_node,
std::priority_queue
<
std::pair< unsigned, unsigned >,
std::vector< std::pair<unsigned, unsigned> >,
T
> &pQueue
) const;
|
5,664,856 | 5,666,922 | Boost-spirit-karma and boost-variant "concepts" related to auto generators | I need to deserialize a std::vector<boost::variant<..>> with decoration supplied by other objects.
One of the things the "decoration" enables is a empty entry in the vector. I have hit a brick wall in my real implementation. However, I have managed to shrink wrap it. Code that compiles :
#include <string>
#include <boo... | I'd suggest to use spirit::unused_type for that purpose as it already is 'known' to Spirit and it has an operator<<() predefined (but any other type will do) - not that you really need that operator for Karma in the first place.
In addition, you have to provide a specialization for create_generator (as you suspected):... |
5,664,883 | 5,665,056 | Setting a value to an enum in same namespace but different class? C++ | EDIT
Thanks to comments under the question, I realized that you have to declare an enum in the header file also. >.< Why does nothing on the internet about enums mention this?
Now the compiler is recognizing Geologist.
My enum is within namespace Star in a class called GameModeState but I need to check the current enum... | Does it not recognize Geologist in the scope of your program? (When you mouse over does intellisense pop up and show you that Geologist is an enum type equal to 1) or does it have a squigly underneath it (indicating it does not recognize the type?)
This could be a scoping issue (although based on your information it do... |
5,665,058 | 5,666,124 | Error when using set_union and set_intersection | I have two sets and I'm trying to do a union (I get the same error when doing an intersection). Here is the error:
error C3892: 'std::_Tree_const_iterator<_Mytree>::operator *' : you cannot assign to a variable that is const
Code snippet(if I comment out the line with the --> then the code compiles and my work around... | This is C++, not Java [edit: or .NET]. You almost certainly want to replace (for example):
set<Line *> * newSet = new set<Line *>();
with just:
set<Line *> newSet;
...or, better still, probably just:
set<Line> newSet;
Although it's impossible to say for certain based on the code you've posted, there's a pretty fair ... |
5,665,221 | 5,665,324 | Typo with "cout < myint". Why does it work? | I have this code and I searched for hours why it fails to print my income
int const income = 0;
std::cout << "I'm sorry, your income is: " < income;
Until I found I missed to write << but wrote <. Why doesn't the compiler detect this and error out? I'm not sure why comparing cout makes sense?
| integral constant 0 is also a null pointer constant - it can be compared to the result of ostream's operator void *. Note that it'll fail if the constant has any value but 0.
|
5,665,231 | 5,665,377 | Most efficient way to escape XML/HTML in C++ string? | I can't believe this question hasn't been asked before. I have a string that needs to be inserted into an HTML file but it may contain special HTML characters. I want to replace these with the appropriate HTML representation.
The code below works but is pretty verbose and ugly. Performance is not critical for my app... | Instead of just replacing in the original string, you can do copying with on-the-fly replacement which avoids having to move characters in the string. This will have much better complexity and cache behavior, so I'd expect a huge improvement. Or you can use boost::spirit::xml encode or http://code.google.com/p/pugixml/... |
5,665,350 | 5,665,422 | Switching between enum values : C++ | This should hopefully be an easy question. I haven't dealt much with enums, so I don't fully understand how they work. In my program I'm trying to store a player's job in an enum. I need the functionality that the job can be changed. I'm trying to use a switch statement, but it isn't changing the player's job.
Code:
//... | Your logic is wrong. The switch(job) statement brings you into your case statement. In the
case Landman
You immediately return Landman (because you set job to Landman before executing your switch statement, it will ALWAYS return Landman the way you have it coded), which returns you from this function completely. I... |
5,665,471 | 5,685,606 | Avoiding declaring private functions in class header files (C++) | (In C++) I have a class whose structure is declared in a header file. That header file is included in lots of source files, such that when I edit it I need to recompile lots of files.
The class has a set of private functions which are only called in one source file. Currently they are declared in the class structure in... | There is no way to declare member functions of a class outside the main class declaration. So, if you want to declare, outside of the class in question, functions that can access member variables of a particular instance of the class, then I see no alternative but to pass that instance to the function. Furthermore, if ... |
5,665,489 | 5,665,529 | how to save this vector | I want to know how I can define vector variables to save output of this code in vector?
/*what should be here?*/=agent.GetInfoState().GetPositionInfo().GetCloseTeammateToTeammate(2);
GetcloseTeammateToTeammate is defined as:
const std::vector<Unum> & GetCloseTeammateToTeammate(Unum i)
{
Assert(i > 0); return Get... | I must be missing something here. Is it not simply this:
const std::vector<Unum> &my_vector = agent.GetInfoState().GetPositionInfo().GetCloseTeammateToTeammate(2);
|
5,665,563 | 5,695,655 | C++: How to ship a single executable without mingwm10.dll | I'm creating a small cross platform program with C++/wxWidgets. By using static linking I managed to get only one .exe file for Windows in the end. However it still requires a small (18 KB) mingwm10.dll
Although I can just distribute my app with this dll, I'd prefer to have it "inside" the .exe... Is it possible?
Thank... | If you use the configure script to compile wxWidgets, add --disable-threads. This will set wxUSE_THREADS to 0, wxThread class and all the code that depends on threads will not be compiled. Automatically mingwm10.dll will not be linked.
|
5,665,593 | 5,666,538 | C++ Read/Write to textfile issue | I need to write numbers and text in a text file, for an unknown reason, the writing works, the reading does not, the problem is reading the text as in the following example:
fstream ff,ff2;
int a,b;
ff.open("simtestagain.txt",ios::out);
CString mycstring = _T("Name with spaces");
char mycharbuffer[255]; //desti... | The extraction operator does not consume the whitespace, so getline is just reading the whitespace that is left over on your first line. Try adding this before your call to getline:
ff2.ignore(255, '\n');
|
5,665,611 | 5,665,658 | Why does this code produce a warning referring to the comma operator? | When answering this question, I came across this code...
#include <iostream>
int main()
{
int const income = 0;
std::cout << "I'm sorry your income is: " < income; // this is line 6
}
...which contains a typo. The second (intended) << operator on line 6 has been accidentally written as a <.
That aside, co... | I think they just forgot to change the warning text
int main() {
1, 2;
}
prog.cpp:2: warning: left-hand operand of comma has no effect
prog.cpp:2: warning: right-hand operand of comma has no effect
The expr, expr operator evaluates the left operand, then evaluates the right operand and yields the result of the rig... |
5,665,676 | 5,666,308 | Client Server C++ Windows Application | Suppose I have 3 computers each collecting data and storing that data in files on the hard drive. I would like those computers to send those files to a 4th computer. What is the simplest way to accomplish this?
| The simplest way I can think of would be to have the 4th computer advertise a shared network drive, and then have the 3 computers mount that drive as a pseudo-local drive (N:\ or whatever). Then all the 3 computers have to do is write or copy the files onto n:\whatever_folder. No network programming required.
|
5,665,707 | 5,665,750 | How do you compile WinCrypt.h under Visual C++? | I have a bog-standard Visual Studio Express Visual C++ environment, installed on a bog-standard Windows 7 box. I'd like to simply compile "#include "WinCrypt.h" (from the Windows SDK) without error. Can someone post the prereq set of includes (and perhaps VS settings) to accomplish this?
| Don't you only have to #include <Windows.h> then #include <Wincrypt.h>?
Edit: yes that is the case. I just tested it and the only requirements to #include Wincrypt are Windows.h and an entry point (main function) to your program.
|
5,665,717 | 5,665,783 | How do you call a c# method in c++? | here and here they do talk about what to do, but i seem to be unable to find my c# project in c++.
I have added the c# project as a reference in the c++ project but whenever i try to use the method i need, it can't find the namespace. i have added it by right clicking the c++ project and going for 'reference' then adde... | You need to add a #using directive to the code. For example, if your C# dll were named Decrypt.dll, add this to the top of your C++ compiland:
#using "Decrypt.dll"
You also need to make sure the C++ code that calls a managed method is also compiled as managed using the /clr compiler option.
Also, I believe you need... |
5,665,733 | 5,665,864 | C++ Do I Understand Polymorphism Correctly? | Bar and Box are derived classes of Foo and Foo has a virtual function F() and Bar and Box both have function F(). From what I understand, polymorphism correctly allows Bar.F() instead of Box.F() or Box.F() instead of Bar.F() to override Foo.F() using some runtime routine without knowing whether your object is a Bar or ... | Nearly right - consider this inheritance tree:
Foo
/ \
Bar Box
If you now make a pointer like this:
Bar* barry = new Box();
You'll get a nice compiler error, since a Box can't be converted to a Bar. :)
So it's only Foo<->Bar and Foo<->Box, never Bar<->Box.
Next, when boxxy is a Box pointer, it will ... |
5,666,321 | 5,666,342 | What is assignment via curly braces called? and can it be controlled? | What is this called?
Vec3 foo = {1,2,3};
Can it be controlled via an operator or some such? As in can I specify how this should act?
For instance if I had some complicated class could I use this to assign variables? (Just an exercise in curiosity).
| That is not assignment. That is initialization.
Such initialization is allowed for aggregate only, that includes POD class. POD means Plain Old Data type.
Example,
//this struct is an aggregate (POD class)
struct point3D
{
int x;
int y;
int z;
};
//since point3D is an aggregate, so we can initialize it as
poi... |
5,666,394 | 5,667,159 | Is MPL pos an undocumented metafunction? | There is the following example code in the BOOST MPL documentation of the find algorithm:
typedef vector<char,int,unsigned,long,unsigned long> types;
typedef find<types,unsigned>::type iter;
...
BOOST_MPL_ASSERT_RELATION( iter::pos::value, ==, 2 );
However, I cannot find the documentation for the iterator's pos metafu... | Metafunctions look like fn< iter >::value. That is simply a member of the iterator type.
Inituitively, I would say that member is specific to iterators resulting from find or functions like it. In any case, as you say, it is undocumented. Do not assume that every iterator has a pos member.
The distance metafunction sho... |
5,666,443 | 5,666,739 | How should I format my .dat file so that a 3D vector plot can be made? | I'm working this programming task for college where we have to write a c++ program that calculates the magnetic field vector for certain coils in 3D space.
I've managed to write this program and I think I've got it working pretty well.
I want to add in a special thinh though (it's my exam paper, so it has to be extra... | I made this simple example to show you how to draw a vector field. The output would be something like this pic:
The data example I used to plot this was:
# Px Py Pz Bx By Bz
0 0 0 0.8 0.8 0.45
0 0 1 0.5 0.7 0.35
0 0 2 0.7 0.5 0.25
0 1 0 ... |
5,666,678 | 5,667,771 | Odd behavior with ostringstream | I was trying to think of a clever way to concatenate various things into a single string argument for a function without having to use an ostringstream explicitly. I thought of:
#define OSS(...) \
dynamic_cast<std::ostringstream const&>(std::ostringstream() << __VA_ARGS__).str()
However, given:
void f( string const... | A better thread-safe solution without involving the cumbersome macro.
The original call to function is this:
f( OSS( '{' << s << '}' ) );
How about if the call is just this:
f(stringbuilder() << '{' << s << '}' );
where stringbuilder is implemented as:
struct stringbuilder
{
std::ostringstream ss;
template<ty... |
5,666,717 | 7,199,398 | median 3 quick sort implementation | my median 3 implementation is not working fine here. i have to choose 3 numbers randomly for medium here is my code please help me.
#include"stdafx.h"
#include <iostream>
#include<algorithm>
using namespace std;
#define size 10
int i;
void show(int* array, int n);
int partition(int* array... | Your code was way too complex for this simple algorithm, check code below:
void QuickSortMedian(int a[],int start,int end) {
int q;
count++;
if (end-start<2) return;
q=MedianOfThreePartition(a,start,end);
QuickSortMedian(a,start,q);
QuickSortMedian(a,q,end);
}
int MedianOfThreePartition(int a[]... |
5,667,001 | 5,667,059 | Dereferencing syntax in copy constructor for class that contains other objects | Suppose the class MyClass has constructor:
MyClass::MyClass( ... ) {
var = new OtherClass( ... );
}
and suppose the class OtherClass has copy constructor:
OtherClass::OtherClass(const OtherClass &obj) {
for (int i = 0; i < array_size; ++i) {
array[i] = obj.array[i];
}
}
Is the below a recommended ... | No, that doesn't really make sense. What makes sense is this:
MyClass::MyClass(const MyClass &obj) {
var = new OtherClass(*obj.var);
}
Or rather:
MyClass::MyClass(const MyClass &obj)
:var(new OtherClass(*obj.var))
{}
|
5,667,367 | 5,681,880 | How can you force DirectX to restore your previous render state? | I have a program that draws text and draws a primitive triangle. Both functions work independently. However, when I call them in a row my triangle does not draw and I then receive this error:
D3D10: ERROR: ID3D10Device::Draw: Input Assembler - Vertex Shader linkage error: Signatures between stages are incompatible. The... | I figured this out. The way you do this is by calling a:
pSprite->begin(D3DX10_SPRITE_SAVE_STATE);
//your text drawtext method stuff here
pSprite->end();
Note that you'll need to initialize the sprite object. You can do this with a D3DX10CreateSprite function, which is very similar to the createtext function.
http://m... |
5,667,484 | 5,667,553 | How to iterate over a container in a thread-safe way? | I have a container (C++) on which I need to operate in two ways, from different threads: 1) Add and remove elements, and 2) iterate through its members. Clearly, remove element while iteration is happening = disaster. The code looks something like this:
class A
{
public:
...
void AddItem(const T& item, int inde... | sounds like a reader/writer lock is needed. Basically, the idea is that you may have 1 or more readers OR a single writer. Never can you have a read and write lock at the same time.
EDIT: An example of usage which I think fits your design involves making a small change. Add an "iterate" function to the class which owns... |
5,667,830 | 5,667,994 | DOMDocument C++ memory management | Question about DOM* class createXXX methods in C++. Do I have to do anything special to free memory returned from DOM* createXXX methods?
For example (the transcodes were removed for simplification and the associated releases for the vars associated with the transcode operations, I know about those):
pImplement = DOMI... | From memory of my experience using DOM classes, you don't have to delete anything that you append to the DOM tree. For example, you append the child secondElement to the element firstElement. When the latter gets freed, it will also free secondElement. However, I see two things here that will leak. First, you don't ins... |
5,668,000 | 5,668,288 | Corrupt stack problem in C/C++ program | I am running a C/C++ program in linux servers to serve videos. The program's(say named Plugin) core functionality is to convert videos and we fork a separate Plugin process for each video request. But I am having a weird problem for which sometimes server load average gets unexpectedly high. What I see from top command... | Attaching the debugger changes the behavior of the process so you won't get reliable investigation results most probably. Corrupted stack message from the debugger can mean that the particular debugger does not understand text info from the binary.
I would recommend running pstack several time subsequently on the probl... |
5,668,006 | 5,668,038 | How to store an unknown number of elements in an array C++ | Sorry if the title is not clear but I ll explain now my problem. I am new in C++.
I have created a class in C++. Instances of that class are the input of the program and they have to be stored in an array to perform the calculations. The problem is that the number of instances of that class that have to be defined by t... | The typical C++ solution is to use a vector.
vector<MyClass> v;
v.push_back(first_instance); //add an already instantiated object to the end of the vector
v.push_back(second_instance);
v.push_back(third_instance);
You won't have to worry about memory management and you are able to access the vector like you would a n... |
5,668,032 | 5,668,060 | Automatic heap cleanup during stack destruction | int* f()
{
int *p = new int[10];
return p;
}
int main()
{
int *p = f();
//using p;
return 0;
}
Is it true that during stack destruction when function return it's value some compilers (common ones like VS or gcc were implied when I was told that) could try to automatically free memory pointed by lo... | Only Local variables are destroyed-released.
In your case p is "destroyed" (released) , but what what p points to, is not "destroyed" (released using delete[]).
Yes you can, and should/must use a delete[] on your main. But this does not imply using raw pointers in C++. You might find this e-book interesting : Link-Alf-... |
5,668,847 | 5,668,890 | Is there an equvalent to Dim/var in C++? | I'm new to C++ and i have a case where vb.nets Dim or C#s var would help me greatly.
i googled around and i found no questions for this? (although search terms with var or dim and C++ seemed to stray easy)
is there an equivalent for this?
| Not in the current standard.
However, the new version that is probably due this year (most likely called C++11, but it's also still often referred to as C++0x) has auto that does that same thing as var.
It's already supported by recent versions of all big compilers.
For example:
auto MyValue = SomeFunction(); // The co... |
5,668,952 | 5,669,020 | static char array behaving unexpectedly across classes | I know this will have a easy answer but am stumped. I've simplified the code as much as possible to get to the point.
I have a simple header file, call it a.h
which has the below and nothing more (it acts as a global settings file for all files in my project that choose to include it)
#ifndef A_H
#define A_H
namespace... | the static keyword links the name into each translation unit it is included in, so each .cpp file basically has its own version of name.
What you want to do is put the name you want to share in one .cpp file (without the static and declare it with extern linkage in the .h file.
so that's:
a.cpp
namespace settings {
... |
5,669,119 | 5,669,246 | Should we avoid repetitive code in C++ in order to be "Pythonic", and how? | I am in larval stage with Python and pre-egg stage in C++, but i am trying to do my best, specially with the "Don't Repeat Yourself" principle.
I have a multichannel raw file-format to open, with a main ascii header with fields representable as strings and integers (always coded as chars padded with white spaces). The ... | I'd say there's no such thing as Pythonic C++ code. The DRY principle applies in both languages, but much of what is considered "Pythonic" is simply the shortest, sweetest way of expressing logic in Python, using Python-specific constructs. Idiomatic C++ is quite different.
lambda, for example, is sometimes not conside... |
5,669,161 | 5,765,800 | Which serialization for sending protobuf via sockets in C++? | Which kind of serialization is the most meaningful when sending serialized protobuf data via socket in C++? I use boost sockets.
Until now, I sent std::strings via sockets. I have the option to serialize the protobuf objects into a string and send this string via socket.
Is this slow or slower compared to the other ser... | No. All the serialization methods generate identical output using an identical algorithm. The only savings you are going to have is in time memcpy-ing the data and perhaps the amount of memory used. For all reasonably sized protocol buffers, this is negligible.
In general, you should pick the serialization method th... |
5,669,222 | 5,670,731 | Can someone please verify if RedBlack Tree successor is written correctly? | pair<K,V> *RedBlackTree<K,V,Compare>::successor(K key) {
Node *found = findNode(key, root);
Node *p;
Node *ch;
Node *x;
Node *y;
if(found->right != sentinel)
return new pair<K,V>(found->right->key, found->right->value);
y = found->parent;
/* if it does not have a left child,
... | This code is incorrect. Consider the following tree:
b
/ \
a f
/ \
d g
/ \
c e
The in-order successor of b is c. Your function thinks the in-order successor is f. To find the in-order successor you have to handle several cases; this example tree has an instance of each case that needs to be ha... |
5,669,813 | 5,669,827 | assignment operator return a reference to *this in C++ | I read about this from "Effective c++" ,this is Col.10.
It say it's a good way to have assignment operators return a reference to *this.
I wrote a code snippet to test this idea. I overridden the assignment operator here.And tested it. Everything is fine.
But when I remove that operator overriding, everything is the sa... | If you remove completely the operator= method, a default operator= will be created by the compiler, which implements shallow copy1 and returns a reference to *this.
Incidentally, when you write
mywidget = mywidget2 = mywidget3;
you're actually calling this default operator=, since your overloaded operator is designed ... |
5,669,904 | 5,669,911 | C++ default arguments in function overload evaluated once or each time? | I have a question on defaults for overload functions in an object.
If I have a function signature as follows will the default value be evaluated only once or each time?
class X
{
public:
f(const RWDate& d=RWDate::now());
}
// when calling f() do I get the current time each time?
X z;
z.f();
// is the default valu... | The default arguments are substituted at the call site, so z.f() is transformed into
z.f(RWDate::now())
Thus, the default argument is evaluated each time the function is called and the default argument is used.
|
5,669,937 | 5,669,977 | c++ exporting and using dll function | I can't quite figure out where there is a mistake. I am creating a DLL and then using it in a C++ console program (Windows 7, VS2008). But I get LNK2019 unresolved external symbol when trying to use the DLL functions.
First the export:
#ifndef __MyFuncWin32Header_h
#define __MyFuncWin32Header_h
#ifdef MyFuncLib_EXPORT... | You're exporting a class member function void MyFuncLibInterface::myFunc(std::string param); but trying to import a free function void myFunc(std::string param);
Make sure you #define MyFuncLib_EXPORTS in the DLL project. Make sure you #include "MyFuncLibInterface.h" in the console app without defining MyFuncLib_EXPORT... |
5,670,038 | 5,670,058 | Cannot seem to come up with right parameter for _set_se_translator | I am trying to implement _set_se_translator. I tried to write a function with the following signature (from my .cpp file - of course, I have a similar signature in my .h file):
void CIntersonBScan::trans_func(unsigned int u, EXCEPTION_POINTERS* pExp)
I then pass this function as a parameter to _set_se_translator by ... | typedef void (__cdecl *_se_translator_function)(unsigned int, struct _EXCEPTION_POINTERS*);
This must be a free function, or a static member function - it cannot be a non-static member function (because these have a hidden implicit this parameter - and cannot match _se_translator_function).
|
5,670,135 | 5,670,186 | How do I use iostream cin properly? | This may at first seem like an odd question, but when a cin request is made, if it receives the wrong type it still continues but the status of cin changes.
How do I loop until cin is OK, e.g. when I ask for a number it "accepts" a string if no extra code is given e.g. a loop?
Finally when I use cin multiple times in ... | example:
int value;
while(!(cin >> value))
{
cin.clear();
cin.ignore(); // eat one character
}
while(!(cin >> value))
{
cin.clear();
cin.ignore(10000,'\n'); // eat the rest of the line
}
|
5,670,144 | 5,670,198 | Global static variable not initialized before overloaded global new() call in C++ | In one project I have globally overloaded operator new/delete to make use of a private heap. The code that does this goes like (in file Allocator.cpp):
static HeapManager heapManager;
void * operator new (size_t size)
{
void * p = heapManager.AllocateFromHeap(size);
if (p == 0) // did malloc succeed?
... | Hide it in a function:
HeapManager& getHeapManager()
{
static HeapManager single;
return single;
}
// ...
void * operator new ( ... )
{
void* p = getHeapmanager().AllocateFromHeap( size );
...
This way it'll be created only when function is called.
|
5,670,207 | 5,670,262 | Is the double 0.0 always represented exactly in portable C? | Can the following code be expected to work in all environments that have an ANSI-compliant C compiler?
double n = 0;
assert(n == 0);
What about C++?
| You're not asking if 0.0 is always represented exactly.
In the statement assert(n == 0), 0 is converted to double before the comparison occurs. Thus, the assert can only be triggered if converting 0 from int to double is not reproducible. This is a much weaker restriction than what you're asking about, and will almos... |
5,670,221 | 5,670,259 | binary representation of a float | why this two call to toBinary function compute the same output (at least under VS2010) ?
#include <iostream>
#include <bitset>
#include <limits>
using namespace std;
template<class T> bitset<sizeof(T)*CHAR_BIT> toBinary(const T num)
{
bitset<sizeof(T)*CHAR_BIT> mybits;
const char * const p = reinterpret_cast<... | That epsilon is relative to 1; here, instead, you are summing it to 8.9, which is more than 8 (2^3) times bigger than 1. This means that that epsilon would change a binary digit that is three digits to the right of the rightest digit stored in that double.
If you want to notice something change, you have to add at abou... |
5,670,324 | 5,670,773 | how to draw pool table pockets opengl c++ | hey
i am creating a pool table simulator in opengl written in c++
i have the basic table drawn but now i need to add some pockets
i want the pockets to be a basic curve like a C shape
im not quite sure how to do this
i have experimented with trianglefan but iv had no luck
can anyone help please?
also i must add this is... | Do you have access to glu.lib?
http://en.wikipedia.org/wiki/OpenGL_Utility_Library
http://www.opengl.org/resources/faq/technical/glu.htm
That would easily make cylinders or NURBS curves for the pockets. Sample use of it is here: http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=18
There is also lots of code fro... |
5,670,459 | 5,670,481 | signal in C++: using a member function | I have this problem with signal():
This code compiles fine:
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
void terminate( int param )
{
printf ( "Terminating program...\n" );
exit( 1 );
}
int main()
{
signal( SIGTERM, terminate );
return 0;
}
The following code, however, throws this error:
... | You need to declare your terminate() function as static:
class GOOBER {
// ...
static void terminate(int param);
};
This is because that as a non-static member function, the terminate() function expects to be passed the (hidden) this parameter to point to some instance of the object. Since the signal mechanism... |
5,670,585 | 5,671,432 | Why does my DirectInput8 stack overflow? | The overall program is too complex to display here. Basically, just pay attention to the green highlights in my recent git commit. I am very new to DirectInput, so I expect I've made several errors. I have very carefully studied the MSDN documentation, so I promise I'm not just throwing this out there and stamping FIX ... | Your code seems to be okay (according to this tutorial, which I have used in the past). The use of several stack-based arrays is questionable, but shouldn't be too much of an issue (unless you start having lots of concurrent getEvent calls running).
However, your best bet would be to stop using DirectInput and start us... |
5,670,746 | 5,671,204 | QTcpServer: Send HTTP/1.0 200 OK to connected client | I set up a QTcpServer to listen to a Shoutcast stream. The newConnection()-signal gets fired as it should:
connect(tcpServer, SIGNAL(newConnection()), this, SLOT(handleClientComm()));
void IcecastServer::handleClientComm(){
QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
qDebug() << clientCo... | You must extract QTcpSocket object from QTcpServer with nextPendingConnection() call when the newConnection() signal was emitted. And then you must call writeData() on the extracted QTcpSocket object.
The key here is that Listening socket (QTcpServer) is only responsible for creating Connection Sockets (or QTcpSocket) ... |
5,670,765 | 5,676,034 | Cannot deserialize protobuf data from C++ in Java | My problem is to serialize protobuf data in C++ and deserialize the data in Java probably.
Here is the code I use to the hints given by dcn:
With this I create the protobuf data in C++ and write it to an ostream which is send via socket.
Name name;
name.set_name("platzhirsch");
boost::asio::streambuf b;
std::ostream ... | I don't know what received is in your Java code, but your problem may be due to some charset conversion. Note also that protobuf does not delimit the messages when serializing.
Therefore you should use raw data to transmit the messages (byte array or directly (de)serialize from/to streams).
If you intent to send many... |
5,670,888 | 5,670,912 | Why is this struct sort crashing my program? | void sortAlphabetically(int listLength, contactInfo* arrayOfStructs)
{
contactType temp;
for (int i = 0; i < listLength; i++)
{
if (strcmp(arrayOfStructs[i].contactName, arrayOfStructs[i+1].contactName) > 0)
{
temp = arrayOfStructs[i]; //swapping entire struct
... | The following expression is invalid when i == (listLength-1) (assuming that listLength is a count of the number of elements in arrayOfStructs):
arrayOfStructs[i+1]
|
5,670,904 | 5,671,310 | Stack overflow when debugging but not in release | I've got the following code below which parses a text file and indexes the words and lines:
bool Database::addFromFileToListAndIndex(string path, BSTIndex* & index, list<Line *> & myList)
{
bool result = false;
ifstream txtFile;
txtFile.open(path, ifstream::in);
char line[200];
Line * ln;
//if p... | A stack overflow indicates that you've run out of stack space (probably obvious, but just in case). Typical causes are non-terminating or excessive recursion, or very large stack object duplication. Funnily enough it might be either in this case.
It's likely that in Release your compiler is doing tail call optimization... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.