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 |
|---|---|---|---|---|
3,694,630 | 3,694,711 | C++: const reference, before vs after type-specifier | What is the difference between the arguments in:
int foo1(const Fred &arg) {
...
}
and
int foo2(Fred const &arg) {
...
}
?
I don't see this case covered in the parashift FAQ.
| No difference as const is read right-to-left with respect to the &, so both represent a reference to an immutable Fred instance.
Fred& const would mean the reference itself is immutable, which is redundant; when dealing with const pointers both Fred const* and Fred* const are valid but different.
It's a matter of styl... |
3,694,899 | 3,694,923 | C++ template and inline | When I'm writing a simple (non-template) class, if the function implementation is provided "right in place", it's automatically treated as inline.
class A {
void InlinedFunction() { int a = 0; }
// ^^^^ the same as 'inline void InlinedFunction'
}
What about this rule when talking about template-based classes?
te... | Templated functions as far as I know are automatically inline. However, the reality is that most modern compilers regularly ignore the inline qualifier. The compiler's optimizing heuristics will most likely do a far better job of choosing which functions to inline than a human programmer.
|
3,694,902 | 3,704,319 | How to fire a JavaScript event via C++ in QWebView | please note that I'm a complete beginner to Qt development.
I have a QWebView with a QObject added to the JavaScript window object.
How do I fire a JS event on that object?
view->page()->mainFrame()->addToJavaScriptWindowObject(objName,obj);
I want to be able to listen to events using addEventListener.
window.objName.... | You cannot do that. Only nodes in a DOM tree can fire events and the object you're injecting is not a node. I suggest you consider using the signal-slot mechanism instead. You can connect a slot in JS to a signal that you'll be emitting in your C++ code:
window.objectName.signalName.connect(slot);
slot is just an JS f... |
3,694,987 | 3,695,001 | C++ visual studio inline | When building projects in Visual Studio (I'm using 2008 SP1) there is an optimizing option
called Enable link-time code generation. As far as I understand, this allows specific inlining techniques to be used and that sounds pretty cool.
Still, using this option dramatically increases the size of static libraries built.... | How are we supposed to know? You're the one suffering the slower link times.
If you can live with the slower builds, then it speeds up your code, which is good.
If you want faster builds, you lose out on optimizations, making your code run slower.
Is it worth it? That depends on you and nothing else. How patient are yo... |
3,695,147 | 3,695,284 | Consequences of only using stack in C++ | Lets say I know a guy who is new to C++. He does not pass around pointers (rightly so) but he refuses to pass by reference. He uses pass by value always. Reason being that he feels that "passing objects by reference is a sign of a broken design".
The program is a small graphics program and most of the passing in questi... | Subtyping-polymorphism is a case where passing by value wouldn't work because you would slice the derived class to its base class. Maybe to some, using subtyping-polymorphism is bad design?
|
3,695,174 | 3,731,643 | Visual Studio 2010's strange "warning LNK4042" | I've just been beaten (rather hardly) on the head by some non-trivial warning from Visual Studio 2010 (C++).
The compilation gave the following output:
1 Debug\is.obj : warning LNK4042: object specified more than once; extras ignored
1 Debug\make.obj : warning LNK4042: object specified more than once; extras ignored... | Just wanted to cross post what I believe to be the answer, if you open the properties for the entire project, and the change the value under C/C++ -> Output Files -> "Object File Name" to be the following:
$(IntDir)/%(RelativeDir)/
Under VS 2010, I believe this will disambiguate all of the object files (as I believe wi... |
3,695,278 | 3,695,426 | Doubting about the Threads window of visual studio |
As you can see above , there are 4 win32 threads at exactly the same location, how to understand it?
UPDATE
7C92E4BE mov dword ptr [esp],eax
7C92E4C1 mov dword ptr [esp+4],0
7C92E4C9 mov dword ptr [esp+8],0
7C92E4D1 mov dword ptr [esp+10h],0
7C92E4D9 push esp
7C92E4DA ... | The debugger shows the next ring3 processor instruction that is going to be executed. In this case the thread has called sysenter, which makes a ring0 system call to the operating system's kernel. This kernel system call is waiting for something to happen before returning control back to the calling code. Once that som... |
3,695,287 | 3,828,543 | Speed Up linking speed / Fast linking on linux | I am building webkit ( 2 Million lines of code) after every ten minutes to see the output of my change in it, and linking of webkit on my Machine requires to process 600-700 MB of object files which are there on my hard-disk. That takes around 1.5 minutes. I want to speedup this linking process.
Is there any chance tha... | I solved this problem by using tempfs and gold linker.
1). tmpfs: mount directory which contains all the object files as tmpfs.
2). gold linker: using gold linker will make linking 5-6 times fast, with tmpfs advantage speedup will be 7-8 times than normal linking. use following command on ubuntu and your normal linker ... |
3,695,335 | 3,695,454 | C++: compilation error - "no .eh_frame_hdr table will be created" | I'm supposed to use a data analysis program for a physics experiment. I can't get it to compile though.
The code is old, not really compatible with current GCC-versions from what I can find. To make things a bit more time-comsuming, I got the code from a guy who had modified all the makefiles to make it compile on Mac.... | Looks like you have forgotten the -shared command line option when you generate the libCommandLineInterface.so file. That would explain those multiple definition errors. If the linker thinks that the file it is generating is an executable (instead of a dynamic library), then it would link in the startup code, etc. When... |
3,695,399 | 3,695,449 | Namespace in definition and implementation | If one has a header file, let's say "test.h" including
namespace test
{
enum ids
{
a = 1,
b = 2,
c = 3,
d = 30
};
char *names[50];
};
and a source file, "test.cc" basically only including
test::names[test::a] = "yum yum";
test::names[test::c] = "pum pum";
// ...
Wouldn't it make m... | You can specify the namespace in test.cc as well. To do this, you would do something like:
#include "test.h"
namespace test
{
...
names[a] = "yum yum";
names[c] = "pum pum";
...
}
You could alternately use using as in:
#include "test.h"
using test;
...
names[a] = "yum yum";
names[c] = "pum pum"... |
3,695,400 | 3,695,697 | Is it possible to create a thread that doesn't exit even when main thread exits in windows using c/c++? |
Like in the above graph,all other threads will automatically exit once the main thread is dead.
Is it possible to create a thread that never dies?
| You can, but you probably shouldn't; it will just end up confusing people. Here is a good explanation of how this works with Win32 and the CRT.
|
3,695,411 | 3,695,451 | function vs variable declaration in C++ | This code works:
std::ifstream f(mapFilename.c_str());
std::string s = std::string(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());
ParseGameState(s);
Whereby mapFilename is an std::string and void ParseGameState(const std::string&);.
And this does not:
std::ifstream f(mapFilename.c_str());
std::s... | This is C++'s "most vexing parse." A quick Google for that should turn up lots of hits with lots of details. The basic answer is that yes, the compiler is treating it as a function declaration -- and C++ requires that it do so. There's nothing wrong with your compiler (at least in this respect).
If it's any comfort, yo... |
3,695,591 | 3,695,620 | Parsing INI-like configuration files | I'm writing an INI-like configuration file and I want to know the best way to parse it in C/C++. I'm writing it on POSIX, so I'll be using # instead of ;. Which doesn't matter. I just want to know, is there some kind of tutorial, article on parsing things or something.
| There are lots of tutorials and articles on parsing, but what you're dealing with is so trivial that most of them will probably be overkill.
Given how often this has been done before, I'd start by looking at some of the existing code that already implements almost what you want.
|
3,695,730 | 3,696,018 | Invoking a boost::function through boost::function_base | I have an unordered_map of functions that should be called on an object when an XML file is parsed.
I have found that boost::function has a base class named boost::function_base, however as expected I cannot invoke it because I don't have the signuture of the function.
Since all of those functions are setter functions,... | Use a boost::variant is the best way to go. How could you possibly invoke a function with an unknown parameter type, anyway?
|
3,695,758 | 3,695,921 | Declaring a huge dynamic array with tiny cells [C++] | I have this project I'm working on. The following conditions apply
In this project I need to create one huge array (hopefully I will be able to create one as big as ~7.13e+17, but this target is still up ahead.)
Each cell inside the array can contain one of the three values: 0,1,2
I'm using C++ as my language.
I trie... |
Is there any way to create an array using long long to determine the number of cells in the array and have every cell of size int?
There is no reason the type of the array has to be the same as the type of the variable used to specify the size. So use long long for the variable that specifies the size and then int fo... |
3,695,760 | 3,696,048 | GLU Tesselator says: "Need combine callback" But I defined a callback | I registered a CALLBACK using:
gluTessCallback(tess, GLU_TESS_COMBINE, (GLvoid(*)()) &scbCombine);
Where scbCombine is a function directly in the same .cpp file:
void CALLBACK scbCombine(const double newVertex[3], const double *neighborVertex[4], const float neighborWeight[4], double **outData)
{
instanceMDC->cbCo... | The problem was the zero, I had to do this:
*outData = new double; // memory-leak, but not as I did it really.
|
3,696,084 | 3,762,478 | SWIG - Problem with namespaces | I'm having trouble getting the following simple example to work with SWIG 1.3.40 (and I also tried 1.3.31). The Foo structure comes through as a Python module as long as I don't wrap it in a namespace, but as soon as I do I get a compilation error in the generated test_wrap.c.
test.h:
#ifndef __TEST_H__
#define __TEST... | In your test.i file, add a "using namespace ns" line after the #include. Without that, your swig wrapper code won't know to look for Foo in the "ns" namespace.
|
3,696,275 | 3,696,332 | C++ OOP basics (assigning an object as a member) | I'm a PHP developer trying to write some C++.
I'm having trouble with assigning an object as an another object's property. In PHP, I'd write this:
class A {
public $b;
}
class B {
}
$a = new A;
$a->b = new B;
How do I do that in C++? I got this so far:
class A {
B b;
public:
void setB(&B);
};
class B {
... | A couple changes will make it compile:
1. class B needs to be declared before A so that it can be used in class A
2. The declaration setB(&B) needs a minor change to setB(B&)
class B {
};
class A {
B b;
public:
void setB(B&);
};
void A::setB(B &b)
{
this->b = b;
};
int main ()
{
A * a = new A();
B *... |
3,696,286 | 3,696,311 | Can one access the template parameter outside of a template without a typedef? | A simple example:
template<typename _X> // this template parameter should be usable outside!
struct Small {
typedef _X X; // this is tedious!
X foo;
};
template<typename SomeSmall>
struct Big {
typedef typename SomeSmall::X X; // want to use X here!
SomeSmall bar;
X toe;
};
Is there a way to access the... | Depending on what you're doing, template template parameters might be a better option:
// "typename X" is a template type parameter. It accepts a type.
// "template <typename> class SomeSmall" is a template template parameter.
// It accepts a template that accepts a single type parameter.
template<typename X, template ... |
3,696,326 | 3,696,427 | How can the allowed range of an integer be restricted with compile time errors? | I would like to create a type that is an integer value, but with a restricted range.
Attempting to create an instance of this type with a value outside the allowable range should cause a compile time error.
I have found examples that allow compile time errors to be triggered when an enumeration value outside those spec... | Yes but it's clunky:
// Defining as template but the main class can have the range hard-coded
template <int Min, int Max>
class limited_int {
private:
limited_int(int i) : value_(i) {}
int value_;
public:
template <int Val> // This needs to be a template for compile time errors
static limited_int make_... |
3,696,379 | 3,696,388 | C++ Why won't my sample program create the output file? | I'm writing a small/beta testing program that will be put to use in my much bigger program for a project. It requests the user for an input file name (IE data.txt) and creates an output file named filename.out (IE data.out). I've tried a simple outFile << "text here"; to try it out but it doesn't create output file. I... | Because you're trying to open the file for reading:
outFile.open(outputFile.c_str(), ios::in);
Use ios::out instead.
|
3,696,393 | 3,696,483 | OpenGL Smooth Polygon | I am trying to make this a smooth polygon using OpenGL, but it is not doing anything. Can someone please explain what I am doing wrong?
glColor4ub(r, g, b, a);
glEnable(GL_POLYGON_SMOOTH);
glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);
glBegin(GL_QUADS);
glVertex2i(x, y);
glVertex2i(x1, y1);
glVe... | This method to smooth rendering is way out of date. It would be better to use multisampling with the GL_ARB_multisample extension.
|
3,696,613 | 3,696,617 | Platform-independent detection of arrow key press in C++ | In a C++ console program, I've found how to detect and arrow key on Windows, and I've found a lot of other stuff that had nothing to do with the question (despite what I thought were good search terms), but I want to know if there is a platform-independent way to detect an arrow key press. A decent second place for th... | There's no cross platform way to do it because it's not defined by either C or C++ standards (though there may be libraries which abstract away the differences when compiled on different platforms).
I believe the library you are looking for on POSIX boxes is curses, but I've never used it myself -- I could be wrong.
Ke... |
3,696,616 | 3,696,969 | Split an image into 64x64 chunks | I'm just wondering how I would go about splitting a pixel array (R,G,B,A,R,G,B,A,R,G,B,A,etc.) into 64x64 chunks. I've tried several methods myself but they all seem really over-complex and a bit too messy.
I have the following variables (obviously filled with information):
int nWidth, nHeight;
unsigned char *pImage;
... | Just define a MIN() macro to determine the minimum of two expressions, and then it's easy:
void ProcessChunk(unsigned char *pImage, int x, int y, int width, int height);
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define CHUNKSIZE 64
void ProcessImage(unsigned char *pImage, int nWidth, int nHeight)
{
int x, y;... |
3,696,801 | 3,696,841 | Questions about inline performance | I had some questions about using inline on functions in C and C++. I have been told to use it on small functions that I use frequently but I want to understand exactly how it works. Here is just a snippet of an example.
static inline point3D createPoint3D(float x, float y, float z){
point3D newPosition;
newPositi... |
It's more like an outdated optimization from the '70s or (at most) '80s. Nearly any competent compiler can select functions for inline expansion without any help from you beyond enabling the optimization to start with.
What it's supposed to do is eliminate the overhead of calling the function. This is mostly important... |
3,696,902 | 3,696,908 | Difference between 2.0 and 2.0f (explicit float vs double literals) | I had some questions about putting f next to literal values. I know it defines it as a float but do I really need it?
Is this 2.0f * 2.0f any faster or compiled any different than 2.0 * 2.0? Is a statement like float a = 2.0; compiled differently than float a = 2.0f;?
| Sometimes you need it to explicitly have type float, like in the following case
float f = ...;
float r = std::max(f, 42.0); // won't work; (float, double).
float r = std::max(f, 42.0f); // works: both have same type
|
3,696,961 | 3,696,976 | Methods for avoiding common typo bugs | So I just spent the last few hours pouring over code trying to figure out the source of a bug only to find that my error was none other than the obviously wrong but compiler accepted:
if (a = b)
where it should have been
if (a == b)
What do you guys do to safeguard against these frustrating errors? What other common... | Most compilers provide options to give warnings in these situations. These are typically called "lint" warnings after the name of an early program to provide them for C source code (in the early days C compilers didn't have them built in, but they mostly do now). You might check to see you're enabling all warnings your... |
3,697,076 | 3,697,103 | Creating a Tree from a List of Rectangles | This may be a silly question, but nothing comes to mind straight away. Given a list R of 2D rectangles (x, y, w, h) arranged so that any given rectangle is either fully inside or fully outside any other, what's the most efficient way to determine the immediately enclosing rectangle p of each rectangle in R? Currently I... |
Sort by (x+y).
Starting at the beginning of the sorted list, grab a rectangle Q.
Compute (x+y+w+h) for that rectangle.
For each rectangle R in part of the list that follows rectangle Q, and has x+y for R <= (x+y+w+h) of Q, check to see if R is within the bounds of Q. If it is, set Q as the parent of R, overwriting any... |
3,697,127 | 3,697,227 | Mysterious heisenbug? | So I'm making a snake game with teleports and the usual mice. I had a loop running like this:
while(snake.alive() && miceEaten < micePerLevel)
{
displayInfo(lives, score, level, micePerLevel - miceEaten);
//some code
if(miceEaten())
{
//update score...
}
//more stuff...
}
The problem wi... | Build your assignment operator like this:
You should always return *this (even if they were equal). But they never would since you were creating a local copy (so this was not your error).
Location& Location::operator = (Location const& other)
{
// Does it really matter if you assign to self?
x = other.x;
y ... |
3,697,203 | 3,748,185 | Visual Studio Add-in development - Get directory path within a C++ project | i'm currently trying to build an add-in which is similar to VSNewFile. So it's just a simple extension which provides a faster way to create new files. The problem with VSNewFile is that it doesn't work for C++ projects and i need it for that.
Here is my problem:
I'm unable to retrieve the absolute path of a select... | Maybe this will help anyone else who got the same problem:
http://social.msdn.microsoft.com/forums/en-US/vsx/thread/bd738463-ba24-4880-beea-f3ec110d981e
// Subscribe to the SVsShellMonitorSelection service somewhere:
public void mySetupMethod()
{
IVsMonitorSelection monitorSelection =
(IVsMonitorSelec... |
3,697,255 | 3,715,388 | Is there any API for creating custom server roles in Windows Server 2008? | Subject is self-explaining
| I don't believe there is. The Server Roles in windows are used for adding additional Windows components onto the core operating system. To get any other, third party, components onto a server, you're going to run an installation of some kind. And typically, during such an installation, you'll choose which components of... |
3,697,329 | 3,697,342 | question on assignment with boost::shared_ptr (vs. the reset() function) | Sorry if this is explicitly answered somewhere, but I'm a little confused by the boost documentation and articles I've read online.
I see that I can use the reset() function to release the memory within a shared_ptr (assuming the reference count goes to zero), e.g.,
shared_ptr<int> x(new int(0));
x.reset(new int(1));
... | The documentation is fairly clear:
shared_ptr & operator=(shared_ptr const & r); // never throws
Effects: Equivalent to shared_ptr(r).swap(*this).
So it just swaps ownership with the temporary object you create. The temporary then expires, decreasing the reference count. (And deallocating if zero.)
The purpose of t... |
3,697,514 | 3,697,538 | How to "inflate" or "grow" a rectangle in Qt? | Does Qt have a built-in way to inflate or grow a rectangle? Like .NET's Rectangle.Inflate or Java's Rectangle.grow... or do I have to implement my own? I've looked through the docs and couldn't find one but maybe I'm missing something.
| There seems to be an adjust function that comes closest to what you want. You could easily use it to "inflate" a rectangle:
rect.adjust(-dx, -dy, dx, dy);
where dx and dy are the amounts you want to inflate in the x and y directions.
|
3,697,686 | 3,697,737 | Why is auto_ptr being deprecated? | I heard auto_ptr is being deprecated in C++11. What is the reason for this?
Also I would like to know the difference between auto_ptr and shared_ptr.
| The direct replacement for auto_ptr (or the closest thing to one anyway) is unique_ptr. As far as the "problem" goes, it's pretty simple: auto_ptr transfers ownership when it's assigned. unique_ptr also transfers ownership, but thanks to codification of move semantics and the magic of rvalue references, it can do so co... |
3,697,750 | 3,698,767 | `Base *b = new Base;` vs `Base *b = new Base();` without defining my own constructor | If I don't define my own constructor is there any difference between Base *b = new Base; vs Base *b = new Base(); ?
| Initialization is kind of a PITA to follow in the standard... Nevertheless, the two already existing answers are incorrect in what they miss, and that makes them affirm that there is no difference.
There is a huge difference between calling new T and new T() in classes where there is no user defined constructor. In the... |
3,697,984 | 3,698,004 | How to Reboot Programmatically? | How can I reboot in c++? Is there any provision in WinSDK? What kind of rights should my program(process) have to do so?
| There is the ExitWindowsEx Function that can do this. You need to pass the EWX_REBOOT (0x00000002) flag to restart the system.
Important note here (quote from MSDN):
The ExitWindowsEx function returns as soon as it has initiated the shutdown process. The shutdown or logoff then proceeds asynchronously. The function is... |
3,697,996 | 3,698,016 | Problem with operator overloading | What is the problem with this code ? this code is giving me lots of syntax errors. Also I would like to know why functors are used in C++.
class f
{
public:
int operator(int a) {return a;}
} obj;
int main()
{
cout << obj(0) << endl;
}
| You're missing an extra pair of parenthesis when declaring operator(). The name of the function is operator(), and it still needs the list of parameters after it. Thus it should look like:
int operator()(int a) {return a;}
Function objects (a.k.a. functors) like this are typically used where you'd use a pointer to a... |
3,698,043 | 3,698,179 | Static variables in C++ | I would like to know what is the difference between static variables in a header file vs declared in a class. When static variable is declared in a header file is its scope limited to .h file or across all units. Also generally static variable is initialized in .cpp file when declared in a class right? So that does mea... | Excuse me when I answer your questions out-of-order, it makes it easier to understand this way.
When static variable is declared in a header file is its scope limited to .h file or across all units.
There is no such thing as a "header file scope". The header file gets included into source files. The translation unit ... |
3,698,084 | 3,698,117 | prefer windows or unix line ending for code? | I writing code that should compiled and run on both Windows and unix like Linux. I know about difference between line endings, but question is which to prefer for my code? Does it matter? I want it to be consistent - say all my code uses LF only, or is it better CRLF only? Are there critaria for comparing?
If it matter... | Use a version control system that's smart enough to ignore line-endings on check-in, and use the correct value for the platform on check-out.
|
3,698,321 | 3,701,129 | g++ linker: force static linking if static library exists? | I've a program which links to many libraries. g++, by default, prefers to link to shared libraries, even if the corresponding archive exists.
How can I change this preference to prefer static archives over dynamic libraries, if a static archive exists?
Note, I used -static option, but it tries to find static archive fo... | g++ -Wl,-Bstatic -lz -lfoo -Wl,-Bdynamic -lbar -Wl,--as-needed
Will link zlib and libfoo as static, and libbar as dynamic . --as-needed will drop any unused dynamic library.
|
3,698,336 | 3,698,356 | c++ redefine a class | I would like to redefine a class in c++ (non clr). Here's the reason
class BabyClass
{
public:
string Name;
int getSiblings(MainClass &mclass)
{
int c = mclass.size();
for(int i=c;i>0;--i)
{
if(mclass.at(i).Name != Name)
... | Try this arrangement which forward declares MainClass.
class MainClass;
class BabyClass
{
public:
string Name;
int getSiblings(MainClass &mclass);
};
class MainClass
{
public:
vector<BabyClass> babies;
};
int BabyClass::getSiblings(MainClass &mclass)
{
// your code which uses mclass
return 0;
}
... |
3,698,402 | 3,698,473 | How to correctly parse incoming HTTP requests | i've created an C++ application using WinSck, which has a small (handles just a few features which i need) http server implemented. This is used to communicate with the outside world using http requests. It works, but sometimes the requests are not handled correctly, because the parsing fails. Now i'm quite sure that t... | You could try looking at their code to see how they handle a HTTP message.
Or you could look at the spec, there's message length fields you should use. Only buggy browsers send additional CRLFs at the end, apparently.
|
3,698,446 | 3,698,475 | Initilizing value for a const data | Following code is in my c++ class
static const QString ALARM_ERROR_IMAGE ;
i want to initilize
ALARM_ERROR_IMAGE = "error.png";
Is it possible to initilize error.png to static const QString ALARM_ERROR_IMAGE
Want to keep it inside class
| Static variable of a class have to be defined explicitly in the namespace scope only once (irrespective of wheter they are further cv qualified or not).
In the .cpp file (e.g in <ClassName>.cpp), in the global namespace (assuming your class is in global namespace), define it as follows (assuming an appropriate construc... |
3,698,459 | 3,717,627 | Objective-C++ and .cpp files in Xcode | I'm trying to make a simple Objective-C++ applicaiton. All of my code is compiling fine, including the use of C++ in Objective-C classes, until I try and add a C++ class to the mix. I've created a simple C++ class:
Test.h
class Test {
};
and included this file in a Objective-C class (with a .mm extension) and I get... | helixed's answer will not help, your class will be just skiped by preprocessor if __cplusplus undefined.
Most of all you trying to include C++ class from *.m file, try to rename it to *.mm.
This solve the same problem on my side.
|
3,698,498 | 3,699,421 | How to prevent COM Server EXE to open Command Prompt window | my question may be simple for you, but I have no experience about it. So, the problem is that I have a COM server and it is started from the context of another EXE, and I need to prevent this COM Server application to open a command prompt window, thanks in advance for your help.
| If you have to source code for the server, change the linker's /MACHINE option. Project + Properties, Linker, System, SubSystem setting. And replace the main() function with WinMain().
If you don't have to source code then you could use
Editbin yourserver.exe /subsystem:Windows
from the Visual Studio Command prompt.... |
3,698,546 | 3,699,045 | Can a contiguous allocation boundary be forced in a C++ template? | Simple example:
template <class P> class MyT
{
struct Item
{
public:
Item() {}
P *pData;
Item *next;
};
Item *head;
public:
...adding etc..
P* operator [](int index)
{
See question below:
}
};
Can I somehow make sure that the 'Item's are allocated in s... | Depends what you mean by "etc", in "adding, etc".
If "etc" includes, "removing", then you have the obvious problem that if you remove something in the middle of your list, then to maintain the indexing you have to shift everything after it downwards, which means updating all the next pointers.
I think perhaps you have ... |
3,698,665 | 3,698,761 | How to keep static const variable as a member of a class | I want to keep a static const variable as a member of class.
Is it possible to keep and how can i initilize that variable.
Some body helped by saying this
QString <ClassName>::ALARM_ERROR_IMAGE = "error.png";
Initilizing value for a const data
I tried like this
in CPP class i write
static QString ALARM_WARNING_IM... | Here is the basic idea:
struct myclass{
//myclass() : x(2){} // Not OK for both x and d
//myclass(){x = 2;} // Not OK for both x and d
static const int x = 2; // OK, but definition still required in namespace scope
// static integral data members only can be initialized
... |
3,698,718 | 3,698,752 | What are Google Test, Death Tests | I saw the documentation of that feature is seem pretty major since it's in Google Test overview features and detailed in:
https://github.com/google/googletest/blob/master/docs/advanced.md#death-tests
They look like standard assert() but they're part of Google Test, so a xUnit testing framework. Therefore, I wonder what... | The assertion is there to confirm that a function would bring about program termination if it were executed in the current process (the details explains that the death test is invoked from a subprocess which allows the tests to continue despite the death). This is useful because some code may guarantee program termina... |
3,698,831 | 3,699,108 | can a class have virtual data members? | class Base{
public:
void counter();
....
}
class Dervied: public Base{
public:
....
}
void main()
{
Base *ptr=new Derived;
ptr->counter();
}
To identify that the base class pointer is pointing to derived class and using a derived member function, we make ... | virtual is a Function specifier...
From standard docs,
7.1.2 Function specifiers
Function-specifiers can be used only in function declarations.
function-specifier:
inline
virtual
explicit
So there is nothing called Virtual data member.
Hope it helps...
|
3,698,847 | 3,698,889 | C++ thread safe doubly linked list | I need the above data structure for an application I'm writing. I wondered if there is a library that already implements it or if I have to write it myself?
I don't really want to reinvent the wheel if it is not necessary.
I need this structure to be able to add and remove items using multiple threads without having t... | Link to a related research: Is a lock (wait) free doubly linked list possible?
As you are not requesting a lock-free container, I am not marking this as an exact duplicate.
Note: while the interface and performance characteristics looks like a double linked list, internally those structures are very complex, based on h... |
3,699,062 | 3,699,145 | C++ volatile and operator overloading for CUDA application | I have a class A that I overload its operator=. However it is required that I need to do something like this:
volatile A x;
A y;
x = y;
which raised an error while compiling
error: no operator "=" matches these operands
operand types are: volatile A = A
If I removed volatile, it's compilable. Is there anyway t... | Assuming the volatile qualification is necessary, you'll have to add a volatile assignment operator to A (A& A::operator=(const A&) volatile).
const_cast<A&>(x) = y will make it compile, but will technically cause undefined behaviour, and will certainly remove the guarantees that volatile gives.
|
3,699,152 | 3,699,215 | What is the fastest portable way to copy an array in C++ | This question has been bothering me for some time. The possibilities I am considering are
memcpy
std::copy
cblas_dcopy
Does anyone have any clue on what the pros and cons are with these three? Other suggestions are also welcome.
| In C++ you should use std::copy by default unless you have good reasons to do otherwise. The reason is that C++ classes define their own copy semantics via the copy constructor and copy assignment operator, and of the operations listed, only std::copy respects those conventions.
memcpy() uses raw, byte-wise copy of da... |
3,699,163 | 3,699,293 | Pull out 2 numbers from a char string? | I'm trying to write a method to set 2 variables to the numbers in a char string. The string would look something like:
[-][1][ ][ ][ ][ ][2][.][0][4]
Where the numbers -1 and 2.04 could be extracted. I know the method signature could look something like this:
sscanf(array[i],"%d%f",&someint,&somedouble)
But I'm hones... | This should do your job:
int x;
float y;
const char* ss = "-1 2.04";
istringstream iss(ss);
iss >> x >> y;
|
3,699,169 | 3,699,364 | Windows active code page | I have a certain library (IBM's WebSphere MQ) which I'm using, with an API that is suppose to return a remote servers character set.
After some debugging, it seems as though the return value of this function call returns the active code page of my machine. I saw this by looking at the return value of the function call... | CHCP returns the OEM codepage (OEMCP). The API is Get/SetConsoleCP.
You can set the C++ locale to ".OCP" to match this locale.
|
3,699,266 | 3,699,730 | What is the official way to call a function (C/C++) in ab. every 1/100 sec on Linux? | I have an asynchronous dataflow system written in C++. In dataflow architecture, the application is a set of component instances, which are initialized at startup, then they communicate each other with pre-defined messages. There is a component type called Pulsar, which provides "clock signal message" to other componen... | To be honest, I think having to have a "pulsar" in what claims to be an asynchronous dataflow system is a design flaw. Either it is asynchronous or it has a synchronizing clock event.
If you have a component that needs a delay, have it request one, through boost::asio::deadline_timer.async_wait or any of the lower leve... |
3,699,314 | 3,699,325 | Why are function declarations returning bool not compiling in my C++ project? | I'm using Visual Studio 2008 Express Edition to compile the following code in a header file:
bool is_active(widget *w);
widget is defined earlier as,
typedef void widget;
The compiler complains with the error:
>c:\projects\engine\engine\engine.h(451) : error C2061: syntax error : identifier 'is_active'
1>c:\projects\... | Most likely, something above this line has a syntax error. Did you forget }s or ; after a class declaration ?
Also make sure you are using C++ and not C. C doesn't have a bool type. If you're using C, then use an int instead.
|
3,699,336 | 3,699,414 | C++: Dynamically access class properties | I'm wondering if it is possible to access a property of a class dynamically without knowing the name of the property accessed at run-time.
To give you a better understanding of what I'm aiming at, this php code should demonstrate what I want to do:
<?php
$object = new object();
$property = get_name_out_of_textfile();
e... | Basically, you need to create an extra function, ala:
std::string get(const std::string& field, const std::string& value_representation)
{
std::ostringstream oss;
if (field == "a")
oss << a;
else if (field == "b")
oss << b;
else
throw Not_Happy("whada ya want");
return oss.st... |
3,699,663 | 3,699,777 | Good design to build a whole program as a FSM? | I have built a parser using a FSM/Pushdown Automaton approach like here (and it works, well!): C++ FSM design and ownership
It allows me to exit gracefully and output a helpful error message to the user when something goes wrong at the parser stage.
I have been wondering about a good way to get that done in the rest of... | What you are doing is a bit like building a (simple) virtual machine in your programme. An FSM tends to be a good fit for some restricted problems such as lexing and parsing, and as you've probably noted, you can get quite a bit of logging and error management 'for free'.
However, if you try to apply the FSM pattern t... |
3,699,735 | 3,700,108 | C++ library for time zone handling | I'm looking for a simple C++ library that allows me to convert timezone descriptions like "America/New_York" into an offset to GMT.
I'm looking for a lightweight library to add to an existing project.
| Never used it but I think boost date time can do this:
boost::date_time - local_time database
|
3,699,797 | 3,700,038 | Should I return an iterator or a pointer to an element in a STL container? | I am developing an engine for porting existing code to a different platform. The existing code has been developed using a third party API, and my engine will redefine those third party API functions in terms of my new platform.
The following definitions come from the API:
typedef unsigned long shape_handle;
shape_h... | The answer depends on your representation:
for std::list, use an iterator (not a pointer), because an iterator allows you to remove the element without walking the whole list.
for std::map or boost::unordered_map, use the Key (of course)
Your design would be much strong if you used an associative container, because a... |
3,699,801 | 3,700,181 | How to Widget inside another widget in QT? | hi how to add widget inside widget
i created main widget, and for the main widget headerbar come from another widget.
here the code below
main.cpp
#include <QApplication>
#include "mainwindow.h"
int main(int argl,char *argv[])
{
QApplication test(argl,argv);
mainWindow *window=new mainWindow();
window->se... | While you use layout, you have never created and assigned an instance to it:
QGridLayout *layout; // no initialization here
headerBar *Header = new headerBar(this);
layout->addWidget(Header,0,0); // layout is uninitialized and probably garbage
You should create it first before using it:
QGridLayout *layout = new QGrid... |
3,700,468 | 3,700,518 | Force virtual destructors? C++ | I didn't see the answer to this in the C++ Faq lite:
How do I define a base class so every class inheriting it is required to define a destructor?
I tried running this program
struct VDtor { virtual ~VDtor()=0; };
struct Test:VDtor { virtual ~Test(){} };
int main() { delete new Test; return 0; }
http://codepad.org/w... | It is "possible" in some sense (if your goal was that the derived class stays abstract otherwise). But it won't give the result you would like: Because the compiler will create a destructor itself implicitly if the programmer hasn't done so.
It's therefor not possible to force the derived class' author to explicitly d... |
3,700,536 | 3,700,697 | Get interrupt counters like /proc/interrupts from code? | I may miss the obvious, but how/is it possible to retrieve interrupt counters for a specific interrupt without manually parsing /proc/interrupts from inside a C/C++ program?
Thanks in advance!
Best regards, Martin
| /proc/interrupts and /proc/stat obtain their data by calling the kernel function kstat_irqs_cpu(). The only way to read it without opening the files in /proc is, I think, writing your own kernel driver which would call the same function and return the results via ioctl() or some other way.
|
3,700,634 | 3,700,714 | How to rewrite the function below with ATL? | HRESULT EnumerateVideoInputFilters(void** gottaFilter)
{
// Once again, code stolen from the DX9 SDK.
// Create the System Device Enumerator.
ICreateDevEnum *pSysDevEnum = NULL;
HRESULT hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL,
CLSCTX_INPROC_SERVER, IID_ICrea... | General idea is that you use CComPtr and other similar things like CComBSTR, CComVariant, CComQIPtr:
ISomeInterface* pointer = 0;
HRESULT hr = whatever->Obtain( &pointer );
if( SUCCEDED( hr ) ) {
hr = pointer-DoSomething();
pointer->Release();
}
return hr;
becomes:
CComPtr<ISomeInterface> pointer;
HRESULT hr =... |
3,700,772 | 3,700,811 | How to compare BSTR against a string in c/c++? | wprintf(L"Selecting Audio Input Device: %s\n",
varName.bstrVal);
if(0 == strcmp(varName.bstrVal, "IP Camera [JPEG/MJPEG]"))...
The above reports :
error C2664: 'strcmp' : cannot convert parameter 1 from 'BSTR' to 'const char *'
| You have to use wcscmp instead:
if(0 == wcscmp(varName.bstrVal, L"IP Camera [JPEG/MJPEG]"))
{
}
Here is a description of the BSTR data type, it has a length prefix and a real string part which is just an array of WCHAR characters. It also has 2 NULL terminators.
The only thing to look out for is that the BSTR data ty... |
3,700,868 | 3,701,006 | The standard Namespace problem | Hii ,
I am relatively new to programming C++ . I do know that the functions cout , cin etc... are defined in the standard name space . But we also include iostream header file for running the program .
So , is it like
namespace std
{
declaration of cout
declaration of cin
..... some other d... |
I do know that the functions cout ,
cin etc... are defined in the standard
name space.
These are not really functions, but global instances of basic_ostream and basic_istream.
But we also include iostream header file for running the program.
You rather include headers so you can compile your source (the compile... |
3,700,976 | 3,700,986 | How to judge whether a project is a c or c++ project? | wprintf(L"Selecting Audio Input Device: %s\n",
varName.bstrVal);
if(0 == wcscmp(varName.bstrVal, L"IP Camera [JPEG/MJPEG]"))
{
...
}
hr = CoCreateInstance(CLSID_SampleGrabber, NULL, CLSCTX_INPROC_SERVER,
IID_IBaseFilter, (void **)&pGrabberF);
The above is from ... | It simply depends how you compile it.
Some code will compile as both, it's considered C++ code if it gets compiled by a C++ compiler.
C is NOT an exact subset of C++ by the way.
Often you can deduce with a fast glance simply by the file's extension, although it's possible to put C code in a .cc extension or .cpp exte... |
3,701,025 | 3,701,195 | What are real significant cases when memcpy() is faster than memmove()? | The key difference between memcpy() and memmove() is that memmove() will work fine when source and destination overlap. When buffers surely don't overlap memcpy() is preferable since it's potentially faster.
What bothers me is this potentially. Is it a microoptimization or are there real significant examples when memcp... | At best, calling memcpy rather than memmove will save a pointer comparison and a conditional branch. For a large copy, this is completely insignificant. If you are doing many small copies, then it might be worth measuring the difference; that is the only way you can tell whether it's significant or not.
It is definitel... |
3,701,158 | 3,701,262 | Where to put global domain specific constants (and how)? | I have a C++ code that's a physics simulation tool.
I would like to store some physical constants, conversion factor between different sets of units, and also some more application specific constants (such as definition like enum Planes {X=0, Y=1}) and I would like to be able to access them from everywhere in my code.... | Namespace constants are the way to go in most cases.
If I use that method, do I have to make it a header file and include it everywhere ?
Yes, or not everywhere but only where it's really USED.
If I understand correctly the variables in the namespace at global scope have static linkage, but no external linkage. Then... |
3,701,229 | 3,701,993 | Renaming a C++ thread when running under Visual Studio 2010 extension package | I'm using the following code (from MSDN) to rename a C++ thread:
#include <windows.h>
const DWORD MS_VC_EXCEPTION=0x406D1388;
#pragma pack(push,8)
typedef struct tagTHREADNAME_INFO
{
DWORD dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1=cal... | I'm not certain whether this is the cause of your problem but according to this MSDN documentation the SetThreadName function only applies to native code. Judging from the exception you're seeing you're compiling with the /clr option so you should probably use the managed code equivalent of this. Follow the link under ... |
3,701,521 | 3,701,805 | Converting single-threaded legacy code with global variables to multithreaded code using thread-local storage | I have a code-base of legacy C/C++ code, which contains lots of functions that access global static variables, and are therefore not thread-safe. I'm looking for advice on how to convert this code to make it thread safe. It occurs to me that one way to do it would be to convert the static variables into thread-local va... | The problem with using TLS is that you force thread affinity onto your clients, and they have to be aware of this and write their code to handle it accordingly. So if they have a worker thread that does the heavy lifting then they will have to marshal ALL calls to your library onto that worker thread, even for simple ... |
3,701,567 | 3,701,613 | c++ vector of strings - issue with pointers | I'm trying to write a method that gets a vector of strings and returns a pointer to a random element. Can you please tell what is the problem with the following code?
string* getRandomOption(vector<string> currOptions){
vector<string>::iterator it;
it=currOptions.begin();
string* res;
int nOptions = c... | Why return a pointer? Keep it simple!
std::string random_option(const std::vector<std::string>& options)
{
return options[rand() % options.size()];
}
And since this works for any type, not only strings, I would prefer a generic solution:
template <typename T>
T random_element(const std::vector<T>& options)
{
r... |
3,701,808 | 3,710,178 | cuda app on part of the cards | I've got a Nvidia Tesla s2050; a host with a nvidia quadro card.CentOS 5.5 with CUDA 3.1
When i run cuda app, i wanna use 4 Tesla c-2050, but not including quadro on host in order not to lagging the whole performance while split the job by 5 equally.any way to implement this?
| I'm assuming you have four processes and four devices, although your question suggests you have five processes and four devices, which means that manual scheduling may be preferable (with the Tesla devices in "shared" mode).
The easiest is to use nvidia-smi to specify that the Quadro device is "compute prohibited". You... |
3,701,903 | 3,702,020 | Initialisation of static vector | I wonder if there is the "nicer" way of initialising a static vector than below?
class Foo
{
static std::vector<int> MyVector;
Foo()
{
if (MyVector.empty())
{
MyVector.push_back(4);
MyVector.push_back(17);
MyVector.push_back(20);
}
}
}
It's an... | Typically, I have a class for constructing containers that I use (like this one from boost), such that you can do:
const list<int> primes = list_of(2)(3)(5)(7)(11);
That way, you can make the static const as well, to avoid accidental modifications.
For a static, you could define this in the .cc file:
// Foo.h
class F... |
3,702,179 | 3,702,322 | How to return a complex return value? | Currently I am writing some assembly language procedures. As some convention says, when I want to return some value to the caller, say an integer, I should return it in the EAX register. Now I am wondering what if I want to return a float, a double, an enum, or even a complex struct. How to return these type of values?... | It is all up to you, if the caller is your code. If the caller is not under your control, you have to either follow their existing convention or develop your own convention together.
For example, on x86 platform when floating-point arithmetic is processed by FPU instructions, the result of a function is returned as the... |
3,702,307 | 3,702,392 | When should assert() be used? | In developing a large C++ programming project with many developers, we have run into issues with inappropriate use of assert() in the code which results in poor quality where the assertion does indeed occur and the product crashes.
The question is what are good principles to apply to use assert() appropriately? When i... | Use Exceptions for error condition which come from the outside (outside the method or outside the program) like parameter checking and missing/defective external ressources like files or connections or user input.
Use Assertions to indicate an internal defects like programming errors, conditions that shouldn't occur, e... |
3,702,449 | 3,702,580 | Return statement that works but doesn't make much sense | I have the following function:
int mult(int y, int z)
{
if (z == 0)
return 0;
else if (z % 2 == 1)
return mult(2 * y, z / 2) + y;
else
return mult(2 * y, z / 2);
}
What I need to do is prove its correctness by induction. Now the trouble I'm having is that even though I know it works since I ran it I... | step-by-step analisis
final result: 100
mult(10, 10)
{
makes 100
mult(20, 5)
{
makes 100
mult(40, 2) + 20
{
makes 80
mult(80, 1)
{
makes 80
mult(160, 0) + 80
{
... |
3,702,541 | 3,702,636 | [Memory allocation problem]Unhandled exception: Microsoft C++ exception: std::bad_alloc at memory location | I am using visual studio 2008 for developing. My program needs to deal with a huge amount of memory. The error happens when my program try to allocate a 512M float array. Code is the following:
int size = 512*512*512;
float *buffer = new float[size];
Before this allocation, the program already consumed around 554M mem... | Your array requires too much contiguous memory. Your program has a bit less of 2 gigabytes of virtual memory available but that address space is broken up by chunks of code, data and various heaps. Memory is allocated from the free space between those chunks. On a 32-bit operating system you can get ~650 MB when you... |
3,702,542 | 3,702,572 | C++ compiler differences | What's the difference on the VC++.net complier (cl.exe /EHsc) and the GCC compiler, compiling, let's say this program:
#include <iostream>
using namespace std;
int main(){
unsigned int test;
cin >> test;
cout << test;
return 0;
}
I know that the vc++ compiler compiles to an exe, and gcc is compiling to the linux ... | GCC means the GNU Compiler Collection, it is the front end for a collection of compilers and linkers. When compiling C++ it will usually call g++.
As for g++ vs VC++, they are completely different compilers so there are a ton of differences.
For example they will optimize code in different ways, they may have minor sy... |
3,702,637 | 3,705,315 | Starting default application for a file on Linux | I'm working on a Firefox NPAPI plugin + XPCOM component. I've run into a dilemma: Given a file downloaded from the Internet (say a PDF or PNG) how do I start the default helper application to display that file on Linux using C/C++?
Currently I'm using the system function call to invoke the gnome-open command and passin... | The xdg-open command is the standard way to open a file or URL in the user's preferred application.
It should work correctly in different desktop environments.
|
3,702,665 | 3,702,702 | How can I get the system language in C/C++? | How can I get the system language in C/C++? Like en_US or en_GB.
| On a POSIX system, it looks like setlocale(LC_CTYPE, NULL); would return the current locale.
|
3,702,695 | 3,702,772 | Linux Installing Library (ICU) Question | I'm a relative noob to installing libraries. My system currently has an older version of the ICU library (3.8) and I want to go the latest (4.4).
Following the steps in the ICU readme.html, everything goes fine (echo $? produces all 0 for every step). And I see the libary was installed to /usr/local/lib. However the cu... | 1) Stuff directly in /usr belongs to your distribution and should not be modified except via its package manager. Stuff in /usr/local belongs to the local installation, and is for you to manage as you see fit. Thus, it is correct to put a local installation of a newer libICU in /usr/local/lib.
2) You can do this by a... |
3,702,731 | 3,702,789 | How to mock a function with the signature `object ()` | I want to mock a method with the declaration A::B X(void). The definition is something as follows.
class A {
class B;
virtual B X() = 0;
};
class A::B {
public:
auto_ptr<int> something;
};
My mock class, following this, is quite standard.
class mA : public A
{
public:
MOCK_METHOD0(X, A::B());
};
... | It is hard to tell without the definitions of A and B. sounds like it is trying to construct a B from a temporary and failing because it can't bind the temporary to a non-const reference.
For example, your copy constructor might be defined as:
class A {
public:
class B {
public:
// This should be const, with... |
3,702,776 | 3,702,784 | Is C really faster than C++? | At begning I used to believe, since C++ is superset of C, there should'nt be a reason for C++ being slower than C but many people on SO dont think so https://stackoverflow.com/questions/2245196/c-urban-myths/2245221#2245221.
Is it true that C++ is slower than C? If not, why to use C anyway?
| C++ is not a superset of C.
Programs can be made in both languages which are equally as efficient, or equally as bad.
The argument probably comes from that in any higher level language, you will have more higher level features available to you and you will likely use them. If you re-implemented these features in the... |
3,702,903 | 3,702,965 | Portable branch prediction hints | Is there any portable way of doing branch prediction hints? Consider the following example:
if (unlikely_condition) {
/* ..A.. */
} else {
/* ..B.. */
}
Is this any different than doing:
if (!unlikely_condition) {
/* ..B.. */
} else {
/* ..A.. */
}
Or is the only way to use compiler specif... | The canonical way to do static branch prediction is that if is predicted not-branched (i.e. every if clause is executed, not else), and loops and backward-gotos are taken. So, don't put the common case in else if you expect static prediction to be significant. Getting around an untaken loop isn't as easy; I've never tr... |
3,702,984 | 3,708,649 | Pre Z buffer pass with OpenGL? | How exactly can I do a Z buffer prepass with openGL.
I'v tried this:
glcolormask(0,0,0,0); //disable color buffer
//draw scene
glcolormask(1,1,1,1); //reenable color buffer
//draw scene
//flip buffers
But it doesn't work. after doing this I do not see anything. What is the better way to do this?
Thanks
| // clear everything
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// z-prepass
glEnable(GL_DEPTH_TEST); // We want depth test !
glDepthFunc(GL_LESS); // We want to get the nearest pixels
glcolormask(0,0,0,0); // Disable color, it's useless, we only want depth.
glDepthMask(GL_TRUE); // Ask z writing
... |
3,702,988 | 4,037,660 | Complete example of wxwidgets custom event passing string data | I am receiving messages from the network on a non-GUI thread and need to use wxEvtHandler::AddPendingEvent to tell the GUI to update accordingly. I also need to pass data to my GUI code so that it can act apropriately.
I believe I have to create a custom event, but haven't found a straightforward implementation. This c... | If you are receiving messages from a different thread, then you explicitily can not use AddPendingEvent. You must instead use wxEvtHandler::QueueEvent.
Second, there are a couple of good examples for creating custom event classes: the old way, the new way.
With the old way, you can also use the Connect method and leav... |
3,703,068 | 3,703,107 | Defining a Static 2-dimension Array with Inline Function | I setup a class with:
class Example {
static const float array[3][8];
};
and implemented
inline const float below_center(const float pos) {
return pos - (size / 2); // size is a const float
}
inline const float above_center(const float pos) {
return pos + (size / 2);
}
inline const float *set_pos(const f... | You can't do like that. Use macros:
#define BELOW_CENTER(pos) ((pos) - (size / 2))
#define ABOVE_CENTER(pos) ((pos) + (size / 2))
#define SET_POS(x, y) { \
BELOW_CENTER(x), BELOW_CENTER(y), \
BELOW_CENTER(x), ABOVE_CENTER(y), \
ABOVE_CENTER(x), BELOW_CENTER(y), \
ABOVE_CENTER(x), ABOVE_CE... |
3,703,170 | 3,703,335 | How to create a data structure with run time limits | I need to implement a data structure that supports insertion deletion and search in
O(log(n)) and extracting a special object in O(1).
My Data structure needs to hold vehicles sorted by their ID and every vehicle has a field which represents the time until the next service.
I need to extract the vehicles that needed t... | A hash table will support insertion, deletion, and search in much better than O(log(n)). That's assuming that you never have to re-hash everything when you grow the table. The difficult part would be locating the "next" vehicle in O(1) time.
Depending on the implementation, a min heap will give you between O(1) and O... |
3,703,302 | 3,703,356 | C++ vector, return vs. parameter |
Possible Duplicate:
how to “return an object” in C++
I am wondering if there is a difference between the three following approaches:
void FillVector_1(vector<int>& v) {
v.push_back(1); // lots of push_backs!
}
vector<int> FillVector_2() {
vector<int> v;
v.push_back(1); // lots of push_backs!
return ... | The biggest difference is that the first way appends to existing contents, whereas the other two fill an empty vector. :)
I think the keyword you are looking for is return value optimization, which should be rather common (with G++ you'll have to turn it off specifically to prevent it from being applied). That is, if t... |
3,703,320 | 3,703,731 | Infinite Thread that may or may not run a CDialog each loop | I am working on a MFC project where I need a separate loop that will run continually or once every few seconds, and each time it may or may not need to run a Dialog to get some input from the user. I was thinking of using AfxBeginThread, but from what I have read about it, it doesn't really work with a continuous loop.... | Don't do it. You can't just rip dialogs off in worker threads. They can only be started in the main thread, because they need the message pump in order to function.
If all you want is a signal of some kind that fires every few seconds, then what you want is a timer. Set the timer for the timer period you want, and w... |
3,703,658 | 3,703,826 | Specifying one type for all arguments passed to variadic function or variadic template function w/out using array, vector, structs, etc? | This question is about guaranteeing all arguments are of the same type while exhibiting a reject-early behavior with a clean compiler error, not a template-gibberish error
I'm creating a function (possibly member function, not that it matters... maybe it does?) that needs to accept an unknown number of arguments, but I... | You can just accept the arguments by the variadic template and let typechecking check the validity later on when they are converted.
You can check convertibility on the function interface level though, to make use of overload resolution for rejecting outright wrong arguments for example, by using SFINAE
template<typen... |
3,703,907 | 3,704,146 | Reading and writing C struct from embedded lua | I'd like to embed lua to allow scripting in my C++ application. In particular, I have two structs which I'd like to pass as arguments to a given lua function. One will be read-only, the other will be read/write. Highly simplified examples of these structs follow:
struct inData
{
int x;
int y;
//many other f... | boring + boilerplate + multi-language = SWIG.
http://www.swig.org/Doc1.3/Lua.html#Lua_nn13
|
3,704,077 | 3,704,103 | static members and consts | class a
{
protected:
const int _ID;
public:
a::a(int id){};
a::top(int num);
};
class b : public a
{
static int ok;
b::b(int id):a(id){};
a::top(ok);
}
int main()
{
int t=5;
b opj=b(t);
}
first why i get this compile error that solved only when i remove the const
non-static const member ‘const int S... | Second first: b::ok has been declared, but not defined. Someplace, (preferably b.cpp), you need to add:
int b::ok;
As for your first problem, _ID is const, it value cannot be changed -- but, you never give it a value to start with. You have to assign it an initial value:
protected:
const int _ID = 1234;
... |
3,704,273 | 3,704,356 | C++ deque vs vector and C++ map vs Set | Can some one please tell me what is the difference between vector vs deque. I know the implementation of vector in C++ but not deque. Also interfaces of map and set seem similar to me. What is the difference between the two and when to use one.
| std::vector: A dynamic-array class. The internal memory allocation makes sure that it always creates an array. Useful when the size of the data is known and is known to not change too often. It is also good when you want to have random-access to elements.
std::deque: A double-ended queue that can act as a stack or queu... |
3,704,388 | 3,704,831 | C++ remove character from string | I am currently trying to implement deleting characters from a text field in C++. If the user hits Backspace, the following code is executed. There is currently no cursor, it should just remove the last character...
if (mText.length() > 0){
mText.erase( mText.length() - 1, 1);
// mText.resize(mText.length() - 1)... | I found my problem using gdb. I found the hidden \b escape sequence which was added to my string after I removed the last character. It actually stands for the backspace, but it was not interpreted. Thank you for your help!
"Roflcopt\b"
|
3,704,722 | 3,704,738 | Initializing class without default constructor | If I have a class A with only a copy constructor and a constructor with parameters int and int, and I place that class inside a class B:
class B
{
public:
B();
private
A a;
}
How would I initialize a inside B's constructor?
I've tried a(0, 0), a = A(0, 0), but not surprisingly neither worked, and I receive a
... | In B's constructor, you would do something like this:
B::B() : a(0, 0)
{
// ctor here
}
|
3,704,749 | 3,704,850 | Tokenization of a text file with frequency and line occurrence. Using C++ | once again I ask for help. I haven't coded anything for sometime!
Now I have a text file filled with random gibberish. I already have a basic idea on how I will count the number of occurrences per word.
What really stumps me is how I will determine what line the word is in. Gut instinct tells me to look for the newline... | Use a std::map<std::string, int> to count the word occurrences -- the int is the number of times it exists.
If you need like by line input, use std::getline(std::istream&, std::string&), like this:
std::vector<std::string> lines;
std::ifstream file(...) //Fill in accordingly.
std::string currentLine;
while(std::getlin... |
3,704,753 | 3,705,114 | Does the Poco C++ Library Support positional command line arguments? | I can see no way to support positional command line arguments with Poco's Poco::Util::Application class and related Poco::Util::OptionProcessor. Positional arguments are unnamed arguments on the command line, coming at the end after all other options, as such:
someprogram -b --what=121 filename.bin
In that example, fi... | I'm not familiar with Poco, but looking at the documentation, I suspect that the intended usage is to repeatedly call Poco::Util::OptionProcessor::process() on successive elements of argv until it returns false, and that would then signify the start of positional arguments and let you handle them however you wish.
|
3,705,000 | 3,712,309 | Do Explicit Instantiations of C++ Class Templates Instantiate Dependent Base Classes? | I figured an explicit instantiation request would automatically instantiate all base class members also, but I get a linker error: unresolved external symbol "public: void Base<int>::foo(int)" when building this code using Visual Studio 2008 or 2010.
Note that adding a call to foo() inside bar() forces the compiler to ... | The Standard says
The explicit instantiation of a class template specialization implies the instantiation of all of its members not previously explicitly specialized in the translation unit containing the explicit instantiation.
In other words, it does not mandate that base classes are explicitly instantiated in turn... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.