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,127,171 | 3,127,179 | How are circular #includes resolved? | In c lets say we have 2 files
1.h
#include<2.h>
blah blah
and we have
2.h
#include<1.h>
code
How is this resolved??
| Typically you protect your include file with an ifndef/define that corresponds to the file name. This doesn't prevent the file from being included again, but it does prevent the contents (inside the ifndef) from being used and triggering the recursive includes again.
#ifndef HEADER_1_h
#define HEADER_1_h
#include ... |
3,127,174 | 3,127,810 | Add a custom tool to toolchain to remove UTF-8 BOM before compile | My question is in the context of Code::Blocks and its tweaked version of MinGW, and Notepad++ .
I want to be able to include Unicode literals in my source, and I can, so long as I use UTF-8 and not use a BOM.
This works fine, up to a point, but it BOMs out (bad pun) whenever I reopen the file; it (not surprisingly) has... | I've fossicked around a bit more, and I've worked out a tentative solution. I'm not completely happy with it because it involves modifying the source, whereas I was actually looking for a piped solution, but it seems that g++.exe only accepts command line args (please correct me if I'm wrong).
My "solution" is a bit ro... |
3,127,182 | 3,132,417 | Qt: delegate to a single editor | What im trying to do is have a table which does not appear editable directly but can be edited in some widget outside the table. That is, the selected node can be edited here, and all nodes use the same editor because i want it to always be shown.
What I've tried is to subclass QItemDelegate and just return the instanc... | The QDataWidgetMapper class is exactly what you want, to edit the values of whatever record outside of the view in external controls.
Taken straight from the documentation, this is how you'd use it:
QDataWidgetMapper *mapper = new QDataWidgetMapper;
mapper->setModel(model);
mapper->addMapping(mySpinBox, 0);
mapper->add... |
3,127,191 | 3,127,204 | How to get MRU List data? | how can i get data prgogrammaticaly from windows registry MRU list? I am using vc++. For example windows xp search history is located in Software\Microsoft\Search Assistant\ACMru\5603. How can i get data from it?
EDIT:I still dont know howto do this, can you be more specific? So what steps do i need to do to have acess... | As for the Run MRU have a look at:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU
Document MRU is saved on filesystem as .lnk-files. Under Windows 7 it is:
%APPDATA%\Microsoft\Windows\Recent
Edit:
On this XP Machine I've got only one entry under the key
HKEY_CURRENT_USER\Software\Microsoft\... |
3,127,193 | 3,128,501 | Error with bc++ and glut | This code compiles fine in Vc++ but in borland c++ gives me this error.. The code has no syntax errors and works fine.. Seems like there is a problem with the header.. But these are the standard headers and library files
Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland
main.c:
Error E2337 c:\Borland\Bcc55\i... | The error is due to overloaded functions being treated like C-language functions. Because the language "C" has no overloading it can only have one function of a given name. Apparently GLUT has a function that has the same name as some other function in the program. This may be your own function (just check the glut.... |
3,127,210 | 3,127,526 | Qt - Get rid from .dll file missing errors | I have created a GUI which requires .dll files in order to work. Here the list of those:
mingwm10.dll libgcc_s_dw2-1.dll
QtCore4.dll QtGui4.dll
I have read that I should write
CONFIG += static
in .pro file. But it does not work. Could you help?
| You need a Qt installation that is built for static-linking for that CONFIG statement to work. The only way to gt a static Qt install is to download the source package and built it yourself.
Now, to deploy your dynamically linked Qt app, just copy those DLL files to the same folder as your built exe file. This may be e... |
3,127,228 | 3,127,786 | Qt - Esc should not close the dialog | How to make Esc key to minimize a dialog? By default it closes. Should I process KeyEvent or there is a better way?
| I think you may use this:
void MyDialog::keyPressEvent(QKeyEvent *e) {
if(e->key() != Qt::Key_Escape)
QDialog::keyPressEvent(e);
else {/* minimize */}
}
Also have a look at Events and Event Filters docs.
|
3,127,393 | 3,127,445 | Returning char* / Visual Studio debugger weirdness | We're getting some funny behavior in the Visual Studio debugger with the following.
I'm not sure if it's the code or some debugger weirdness (seen stuff like it before).
We are trying to return a pointer to an value in an array.
The weird behavior is that the value of x changes to equal y after func() is called a secon... | Are you debugging with a debug build? You often get surprising results like this if you debug a release build.
A debug build will force the compiler to put all variables on the stack, and keep them around for their entire scope, so you get the expected debug view. A release build might reuse the space for one variable ... |
3,127,454 | 3,127,482 | How do C++ class members get initialized if I don't do it explicitly? | Suppose I have a class with private memebers ptr, name, pname, rname, crname and age. What happens if I don't initialize them myself? Here is an example:
class Example {
private:
int *ptr;
string name;
string *pname;
string &rname;
const string &crname;
int age;
... | In lieu of explicit initialization, initialization of members in classes works identically to initialization of local variables in functions.
For objects, their default constructor is called. For example, for std::string, the default constructor sets it to an empty string. If the object's class does not have a default ... |
3,127,721 | 3,129,145 | Except OOP, why is C++ better than C? | Well that may sound like a troll question, but since C++ seems hard to fully master (and I never really knew STL was actually "part" of it), I wanted to know what are the disadvantages to use C instead of C++ when not relying much on OOP.
C++ can have a very much sophisticated syntax sometimes, which is kinda confusing... | Why C++ is better than C? Besides the obvious list of features, in my opinion the real answer is that there's no good reason to still use C instead of C++. Even if you don't use OOP, you can use it as a better C. Even if you use just once a unique feature of C++ in your program, C++ is already a winner.
On the other ha... |
3,127,727 | 3,131,600 | How to programmatically get windows search history? | How to get the windows search history and use it in my program? For example I write ".doc" in windows search bar. Now I want in my program to find out from somewhere, that I searched for ".doc" in my system (not web).
| I don't know if there's an API for it, but if you do a Windows search for an unlikely string, say "zxcvbnm", then search the registry for it, then on XP you can see it under one of the folders in:
HKEY_CURRENT_USER\Software\Microsoft\Search\ACMru
along with the rest of your recent search strings. I imagine this regist... |
3,127,966 | 3,128,008 | Multi-window program | I read many articles on the topic, a few of them were here, on stackoverflow, but none of them asked my question. I'll try to be specific.
I need to create an application (native WinAPI) with a main window (of window class "a"). When the user clicks a button there, a window of "b" class pops up. It might be modal or no... | At a guess, the window procedure for your second window is based on one for a main window, so when it receives a WM_DESTROY, it's calling PostQuitMessage. This is normal for the top-level window, because the user expects destroying it to mean exiting the application. For a child window (modal or otherwise) that's not t... |
3,128,087 | 3,128,101 | Move constructor/operator= | I'm trying to learn about new feature of C++ namely move constructor and assignment X::operator=(X&&) and I found interesting example but the only thing I quite not even understand but more dissagree is one line in move ctor and assignment operator (marked in the code below):
MemoryBlock(MemoryBlock&& other)
: _dat... | Because the "moved from" object is still going to be destructed eventually, so you have to leave it in a consistent state. Exactly how you do this depends on your object, of course, and in this case it apparently means nulling out the data pointer and setting the length to zero.
|
3,128,099 | 3,128,107 | c++ template seems to break access specifiers | The following code doesn't compile for obvious reasons, namely that Foo is trying to access a private member of Bar. However if you uncomment/comment the lines marked, making Foo a template, it does compile and outputs 42. What am I missing here? Why does this work? Seems to me it shouldn't.
Thanks for your help.
#incl... | If you are seeing this behavior, it is a compiler bug.
Both Comeau Online and Visual C++ 2010 reject the code as invalid because Bar::x is inaccessible. g++ 4.1.2 incorrectly accepts the invalid code (someone would need to test with a later version to see if it's been fixed; that's the only version I have on this lapt... |
3,128,248 | 3,128,257 | Namespace Aliasing in C++ | It is widely known that adding declarations/definitions to namespace std results in undefined behavior. The only exception to this rule is for template specializations.
What about the following "hack"?
#include <iostream>
namespace std_
{
void Foo()
{
std::clog << "Hello World!" << std::endl;
}
using name... | Redefining std as an alias is okay, as long as you are not in the global declarative region:
In a declarative region, a namespace-alias-definition can be used to redefine a namespace-alias declared in that declarative region to refer only to the namespace to which it already refers.
Since you define the alias in main... |
3,128,269 | 3,128,712 | Find array element by member value - what are "for" loop/std::map/Compare/for_each alternatives? | Example routine:
const Armature* SceneFile::findArmature(const Str& name){
for (int i = 0; i < (int)armatures.size(); i++)
if (name == armatures[i].name)
return &armatures[i];
return 0;
}
Routine's purpose is (obviously) to find a value within an array of elements, based on element's member... | If you have access to Boost or another tr1 implementation, you can use bind to do this:
const Armature * SceneFile::findArmature(const char * name) {
find_if(armatures.begin(), armatures.end(),
bind(_stricmp, name, bind(&string::c_str, bind(&Armature::name, _1))) == 0);
}
Caveat: I suspect many would admit that ... |
3,128,286 | 3,128,753 | install driver using c++ | I'm trying to install driver behind the user:
I've create DLL which call SetupCopyOEMInf using c++ then i call it from VB application:
C++ code:
PBOOL bRebootRequired = false;
PCTSTR szInfFileName = (PCTSTR) "c:\\temp\\ttt\\Driver\\slabvcp.inf";
if(!SetupCopyOEMInf(szInfFileName,NULL, SPOST_PATH, SP_COPY_REPLACEONLY, ... | PCTSTR szInfFileName = (PCTSTR) "c:\\temp\\ttt\\Driver\\slabvcp.inf";
A cast is not going to work, it will turn your 8-bit character string into Chinese. Fix:
PCTSTR szInfFileName = _T("c:\\temp\\ttt\\Driver\\slabvcp.inf");
|
3,128,295 | 3,128,591 | Questions about "this pointer adjustor" in C++ object layout | I am kind of confused by one question: Under what cirumstances does the MS VC++ compiler generate a this adjustor? Notice that the this adjustor is not necessarily in a thunk. Below is my test code.
class myIUnknown
{
public:
virtual void IUnknown_method1(void)=0;
virtual void IUnknown_method2(void)=0;
int ... | Perhaps it's easiest to start by thinking how single inheritance is (typically) implemented in C++. Consider a hierarchy that includes at least one virtual function:
struct Base {
int x;
virtual void f() {}
virtual ~Base() {}
};
struct Derived : Base {
int y;
virtual void f() {}
virtual ~Deri... |
3,128,339 | 3,128,355 | Modelling Typeclasses in C++ | Is it possible to implement Haskell typeclasses in C++? If yes, then how?
| There's a few papers on this, which might be useful as background reading:
C++ templates/traits versus Haskell type classes, Sunil Kothari , Martin Sulzmann
A Comparative Study of Language Support for Generic Programming, Ronald Garcia , Jaakko Järvi , Andrew Lumsdaine , Jeremy Siek , Jeremiah Willcock
|
3,128,346 | 3,128,404 | When all does comma operator not act as a comma operator? | If you see this code,
class A{
public:
A(int a):var(a){}
int var;
};
int f(A obj) {
return obj.var;
}
int main() {
//std::cout<<f(23); // output: 23
std::cout<<f(23, 23); // error: too many arguments to function 'int f(A)'
return 0;
}
f(23, 23) does not compile because the comma acts as a... | From a grammatical point of view, the parameters of a function call form an optional expression-list inside parentheses. An expression-list consists of one or more assignment-expression separated by a comma token. A comma can only signify a comma operator where an expression is expected.
The comma operator makes an exp... |
3,128,365 | 3,146,094 | SFML Input GetMouseX and GetMouseY not catching on to mouse movement | I'm programming a GUI in my app and I noticed that button presses weren't being registered very quickly. I did some lazy debugging (send coordinates of mouse to output) and I noticed that Input's GetMouseX and GetMouseY weren't responding nearly fast enough to when the mouse moved somewhere.
This small tidbit should be... | The problem was that I was only polling one event per frame rather than polling all of the events.
|
3,128,469 | 3,128,475 | Build a simple web server that I can run as a windows service | I'm a web developer so all my experience is with ruby, python, or PHP. However, I'm gonna do a little windows programming.
I want to build a light weight web server that can handle incoming requests and pass them on to a COM port. I want to be able to distribute it as an exe that will install the server as a windows se... | To be honest you will probably have the most fun doing this in C#. The learning curve will be smaller and the language and most of its features are your friend. The fact that you can set up a windows service in 2 minutes is also a plus.
|
3,128,534 | 3,129,003 | Observer design pattern and others | I'm starting to read about design patterns and trying to apply them to some coding. I've read about the observer pattern and think it would be a most useful one to make use of.
My two questions are these:
1) If I want my object to be both an observer and a subject, is it simply a question of making it inherit from bot... | Normally, the observer patterns is about applying a layered approach: a higher level object controls a lower level one and it is an observer, so it can react on changed status of the lower level object.
In your case, you want communication between peers and you want all objects to know each other, so observer doesn't a... |
3,128,635 | 3,130,121 | explosion sound thread in MFC game project is stopping the music that is playing | Mabye someone over here can explain to me what am I doing wrong. This is after reading a lot of articles over the net and doing what the articles say should work but it is not working for me.
I am developing a nice little game with a background music and an explosion sound. For the explosion I know I need to use thread... | I would suggest using XAudio2 from the latest DirectX sdk to play your audio. I will take a little more work & code, but the end result will be better because you will be able to load the sound file separately from playing it.
With 'PlaySound' you will notice a lag in the audio if you try to use it right after an eve... |
3,129,015 | 3,129,301 | C++ State machine affecting "HAS-A Parent" | I'm trying to implement a State Machine. The State Machine will have to have an impact on the object that "HAS" it as a member.
However, I obviously can't include the "StateMachine" in the "Game" class AND include the "Game" header in the "StateMachine" class.
How do I get around this problem?
| As your client class is a member rather than an inheriting daughter, you can not access any private state of the parent (which I'm sure you knew), so you have a limited number of choices:
Expose some state in the parent publicly and diddle that (but this is poor design and should be avoided)
Give the parent a public n... |
3,129,078 | 3,129,090 | Discriminating between typedefs to same type in c++ | I want functionality similar to the below:
typedef int A;
typedef int B;
struct foo
{
foo(A a) { /*specific to type A*/ }
foo(B b) { /*specific to type B*/ }
};
I use the typedefs in my program to denote logically different usage of the same type. So, I would like to create object of type foo differently for dif... | A boost strong typedef should do what you're looking for.
#include <boost/strong_typedef.hpp>
BOOST_STRONG_TYPEDEF(int, A);
BOOST_STRONG_TYPEDEF(int, B);
|
3,129,096 | 3,129,141 | What Design Pattern to use? | The problem to model is this:
A hierarchy of levels within an Army, starting with the national army in whole, through field armies, subunits, and eventually the individual men. Each level may involve links to one or more other classes such as General or Officer or whatever. The units within say a field army need to be ... | There is a model/design pattern for communicating events between disparate entities that may not know of eachothers existence before the communication happens. The pattern is called 'Publish/Subscribe'.
Each entity sends events it wants to publish to a broker and tells the broker about what kinds of events it would be... |
3,129,196 | 3,129,251 | data from a std::vector reference becomes corrupt after return from function call | I have a std::vector< tr1::shared_ptr<mapObject> > that I'm trying build from data contained in a compressed file. Here's the function I'm attempting to do that with:
using std::tr1::shared_ptr;
template<typename T>
void loadSharedPtrVector(std::vector< shared_ptr<T> >& vect, TCODZip& zip)
// the TCOD... | The problem is here:
T newT = T::loadType(type, zip);
Tptr.reset(&newT);
You give shared_ptr pointer to stack memory, which is reclaimed at function return and is no longer valid. Allocate that from the heap:
shared_ptr<T> Tptr( new T( T::loadType( type, zip )));
|
3,129,211 | 3,129,219 | Embedding v8 with Visual C++ 2010 | I'm trying to embed the v8 engine to my C++ application. I use Visual C++ 2010. I've built it successfully using this command:
scons env="INCLUDE:C:\Program Files\Microsoft SDKs\Windows\v7.0A\Include;C:\Program Files\Microsoft Visual Studio 10.0\VC\include,LIB:C:\Program Files\Microsoft SDKs\Windows\v7.0A\Lib;C:\Progra... | You need to link to WinSock (Ws2_32.lib).
|
3,129,270 | 3,430,213 | C++ Prime number task from the book | I'm a C++ beginner ;)
How good is the code below as a way of finding all prime numbers between 2-1000:
int i, j;
for (i=2; i<1000; i++) {
for (j=2; j<=(i/j); j++) {
if (! (i%j))
break;
if (j > (i/j))
cout << i << " is prime\n";
}
}
| The one simple answer to the whole bunch of text we posted up here is : Trial division!
If someone mentioned mathematical basis that this task was based on, we'd save plenty of time ;)
|
3,129,359 | 3,129,365 | Does destructor of a C++ class that throws an exception gets called? | Suppose I have a class like this:
#include <iostream>
using namespace std;
class Boda {
private:
char *ptr;
public:
Boda() {
ptr = new char [20];
}
~Boda() {
cout << "calling ~Boda\n";
delete [] ptr;
}
void ouch() {
... | If the exception is not caught anywhere, then the C++ runtime is free to go straight to terminating the program without doing any stack unwinding or calling any destructors.
However, if you add a try-catch block around the call to bad(), you will see the destructor for the the Boda object being called:
int main() {
... |
3,129,373 | 3,129,556 | Understanding Google V8's Architecture | I'm not sure I understand V8's architecture (yes, I've read its documentation).
In C# with the v8sharp wrapper I write something like this, for example:
namespace App
{
class Point
{
public Point() { }
public Point(double x, double y) {
this.X = x;
this.Y = y;
}
... | If you look here: http://code.google.com/apis/v8/embed.html they have a sample that is identical to yours under "Accessing Dynamic Variables"
|
3,129,375 | 3,129,432 | Subclass another application's control? | Is it possible to subclass another application's control so that my application could do something before the other application executes it's code and receiving the lParam and wParam? Ex: subclassing notepad's Edit control and when the user types, being able to know what the user typed? would SetWindowSubclass work if ... | Yes, that is easily possible, if your code is running in the application's process. You can do that with a DLL. You would simply use GetWindowLongPtr with GWLP_WNDPROC to get the application's window function, and use SetWindowLongPtr to set your own. In your window function you check for the message that you would lik... |
3,129,409 | 3,129,470 | Multi-Index Insert Failure Return (Boost) | I'm currently using Boost's multi-index to help keep track of how many times a packet passes through a system.
Each time a system touches the packet, its IP address is added to a string, separated by commas. I go through that string then, tokenize it and add each IP found to a multi-index. Since the IPs are set to be ... | Your call to insert returns a std::pair< iterator, bool >. The bool will be true only if the insert succeeded.
See http://www.boost.org/doc/libs/1_43_0/libs/multi_index/doc/reference/ord_indices.html#modifiers
|
3,129,419 | 3,129,532 | How to get boost::iostream to operate in a mode comparable to std::ios::binary? | I have the following question on boost::iostreams. If someone is familiar with writing filters, I would actually appreciate your advices / help.
I am writing a pair of multichar filters, that work with boost::iostream::filtering_stream as data compressor and decompressor.
I started from writing a compressor, picked up ... | Short answer for reading file as binary :
specify ios_base::binary when opening file stream.
MSDN Link
|
3,129,736 | 3,130,532 | Playback "clicking" noise | I am trying to write a program to play a small .wav file in C++. I have programmed it following the DirectX SDK documents to write and play on a secondary static buffer. It runs correctly except that at the end of the playback for any .wav file, there is a very noticeable "clicking" noise. I am certain that it's not a ... | We'd need to see both the WAV file in question and the code to load the WAV file into the sound buffer. But's here's a few guesses.
My first guess is that if we were to load the WAV file you have into an a visual audio editor we'd see the sound coming to an abrupt end instead of tapering off into silence. This would ... |
3,129,741 | 3,170,079 | __COUNTER__ equivalent on Xcode? | I am migrating a project from Linux to Xcode and I encountered a "version" problem..
I need a unique identifier at compile time for my dynamic stuff, on linux I was using the __ COUNTER__ preprocessor, but it seems that the gcc 4.2 used in Xcode doesn't know about __ COUNTER__ yet...
So, I was wondering what I could d... | @stinky472: I use a code close to what you wrote above...
My problem was that I was using a macro to declare the namespaces of a project, so by that, having the fullname of the class, like class c is in a::b::c.
What I did was changing my code to not rely on the namespaces itself, but add a new argument at the class ma... |
3,129,838 | 3,129,848 | Should Display Lists be cpu intensive? | My application is rendering about 100 display lists / second. While I do expect this to be intensive for the gpu, I don't see why it brings my cpu up to 80 - 90 %. Arn't display lists stored in the graphics card and not in system memory? What would I have to do to reduce this crazy cpu usage? My objects never change so... | If you are referring to these, then I suspect the bottleneck is going to be CPU related. All the decoding of such files is done on the CPU. Sure, each individual command might result in several commands to your graphics card, which will execute quickly, but the CPU is stuck doing decoding duty.
|
3,129,916 | 3,130,371 | What is wrong with this use of offsetof? | I'm compiling some c++ code in MinGW GCC 4.4.0, and getting warnings with the following form...
warning: invalid access to non-static data member '<membername>' of NULL object
warning: (perhaps the 'offsetof' macro was used incorrectly)
This problem seems familiar - something I've tried to resolve before and failed, ... | Oops...
The issue is with the c_Test struct being non-POD due to the T type being non-POD. Here's a quote from the GCC manual...
-Wno-invalid-offsetof (C++ and Objective-C++ only)
Suppress warnings from applying the
‘offsetof’ macro to a non-POD type.
According to the 1998 ISO C++
standard, applying ‘offsetof’ to ... |
3,130,059 | 3,130,073 | Member offset macro - need details | Please take a look at this macro. It is used in Symbian OS SDK, which compiler is based on GCC (< 4 version of it).
#ifndef _FOFF
#if __GNUC__ < 4
#define _FOFF(c,f) (((TInt)&(((c *)0x1000)->f))-0x1000)
#else
#define _FOFF(c,f) __builtin_offsetof(c,f)
#endif
#endif
I understand that it is calculating... | "If there was a member of struct c starting exactly at the (perfectly-aligned;-) address 0x1000, then at what address would the struct's member f be?" -- answer: the offset you're looking for, minus of course the hypothetical starting address 0x1000 for the struct... with the difference, AKA distance or offset, compute... |
3,130,169 | 3,130,397 | How to convert a hex float to a float in C/C++ using _mm_extract_ps SSE GCC instrinc function | I'm writing a SSE code to 2-D convolution but SSE documentation is very sparse.
I'm calculating dot-product with _mm_dp_ps and using _mm_extract_ps to get the dot-product result but _mm_extract_ps returns a hex float and I can't figure out how to convert this hex float to a regular float.
I could use __builtin_ia32_vec... | You should be able to use _MM_EXTRACT_FLOAT.
Incidentally it looks to me as if _mm_extract_ps and _MM_EXTRACT_FLOAT should be the other way around, i.e. _mm_extract_ps should return a float and _MM_EXTRACT_FLOAT should return the int representation, but what do I know.
|
3,130,407 | 3,130,688 | C++: wide characters outputting incorrectly? | My code is basically this:
wstring japan = L"日本";
wstring message = L"Welcome! Japan is ";
message += japan;
wprintf(message.c_str());
I'm wishing to use wide strings but I do not know how they're outputted, so I used wprintf. When I run something such as:
./widestr | hexdump
The hexidecimal codepoints create this:... | You need to define locale
#include <stdio.h>
#include <string>
#include <locale>
#include <iostream>
using namespace std;
int main()
{
std::locale::global(std::locale(""));
wstring japan = L"日本";
wstring message = L"Welcome! Japan is ";
me... |
3,130,408 | 3,130,557 | QString::fromWCharArray gives strange charracters | I have a string named aDrive = "H:/"
i want to convert this string into WCHAR so used like below
WCHAR Drive[4];
aDrive.toWCharArray ( Drive ) ;
when i printed it qDebug ()<<QString::fromWCharArray ( Drive );
it displays like "H:/???"
why i get the starnge charracters at the end..
Thank you for your time
| QString::toWCharArray() does not zero-terminate the array. Without an explicit array length with QString::fromWCharArray(), it will read wchars until a zero wchar is read. In this case, you'll have to add the zero wchar yourself at the end, or use explicit length parameter with QString::fromWCharArray().
As always, the... |
3,130,462 | 3,130,622 | OpenGL extensions causing linker problems | I'm trying to get the addresses for the VBO addon. In my stdafx.h I have the gl.h, glext.h and wglext.h
If I do:
glGenBuffersARB =
(PFNGLGENBUFFERSARBPROC)wglGetProcAddress("glGenBuffersARB");
glGenBuffersARB(0,0);
in stdafx.cpp, this will compile.
but if I try to use glGenBuffersARB(0,0); in any of my... |
_glGenBuffersARB already defined
You probably declared glGenBuffersARB as a global variable in a header (*.h) file, and forgot to add "extern".
what is the proper way of doing this so I can use the vbo extension anywhere in my code?
Use GLEE or GLEW.
|
3,130,490 | 3,130,502 | Deleting string object in C++ | I have a string object in my C++ program declared as follows:
string str;
I have copied some data into it and done some operations. Now I want to delete the str object from the memory. I am not able to use delete operator since str is not a pointer. How do I delete that object from the memory to reclaim the memory all... | You don't have to. When the string goes out of scope, it's destructor will be called automatically and the memory will be freed.
If you want to clear the string right now (without waiting until it goes out of scope) just use str.clear().
|
3,130,588 | 3,130,606 | C++ question: feature similar to Obj-C protocols? | I'm used to using Objective-C protocols in my code; they're incredible for a lot of things. However, in C++ I'm not sure how to accomplish the same thing. Here's an example:
Table view, which has a function setDelegate(Protocol *delegate)
Delegate of class Class, but implementing the protocol 'Protocol'
Delegate... | Basically, instead of "Protocol" think "base class with pure virtual functions", sometimes called an interface in other languages.
class Protocol
{
public:
virtual void Foo() = 0;
};
class Class : public Protocol
{
public:
void Foo() { }
};
class Class2 : public Protocol
{
public:
void Foo() { }
};
class... |
3,130,655 | 3,130,720 | Freeing memory for const char * variable in C++ | I have a variable declared as const char *. I have allocated memory for that using malloc(). After using it, I want to free that memory using free(). But I am not able to do that and it gives me error that "Attempting to write to protected memory". How do I free the memory allocated?
Thanks,
Rakesh.
| If you're getting that error then you're doing something wrong and you'll need to post the code so we can figure out what it is. For what it's worth, you can free a const char* as evidenced in the following code, which compiles and executes perfectly:
#include <cstdlib>
int main (void) {
const char *x = (const char... |
3,130,731 | 3,130,760 | MessageBox in Out-of-Process COM Server | When you have a console based client and a COM Server, can you call ::MessageBox(...) from the COM Server and expect it to work?
| Yes, you can, but in some cases the box will be shown on another desktop and effectively block the calling thread, so you better not try this other than for debugging purposes.
|
3,130,734 | 3,131,019 | Exception Safety in Qt | Wikipedia says that "A piece of code is said to be exception-safe, if run-time failures within the code will not produce ill effects, such as memory leaks, garbled stored data, or invalid output. Exception-safe code must satisfy invariants placed on the code even if exceptions occur."
And it seems that we need excepti... | C++ has a very powerful mechanism for excpetion-safety. Destructors are run for all variables that go out of scope due to an exception. This differs from languages like Java, where exception-safety requires the programmer to get the catch and finally clauses right.
The C++ behavior of calling destructors works seamless... |
3,130,927 | 3,132,434 | How to pass map into py? | I want to use c++ load py.
But one of parameters of a function is dict.
So, can I pass the map in C++ to dict in py?
| Your problem description is a little terse. If I understand correctly though, you'd like to embed a Python interpreter within a C++ application and, from C++, you want to be able to instruct the interpreter to load Python modules. If this is correct, then the answer is no. The Python C API expects a Python object whene... |
3,130,995 | 3,131,027 | How to move QSplitter? | Say I have a window, where there are 2 horizontal sppliters, and a button. How to move a splitter up/down by clicking on the button?
| Take a look at http://doc.qt.io/qt-4.8/qsplitter.html#setSizes. The main point is that there is no method to move the splitter explicitly, you can only achieve similar behaviour by resizing the widgets in the QSplitter themselves, which is easily accomplished by using QSplitter::setSizes.
I would do something like
QLis... |
3,131,055 | 3,131,248 | Deleting registry key values | In MSDN it says that RegEnumValue should not be used when calling function that change the registry keys being enumerated.
So does this also apply to deleting registry key values?
Like this code does:
if (RegOpenKeyEx(m_hkey,m_path.c_str(),0,KEY_ALL_ACCESS,&key) == ERROR_SUCCESS)
{
bool error=false;
idx=0;
while... | Your code does not work. When you delete index 0, the next item becomes index 0, and you do not delete that.
So yes, it applies to deleting key values.
|
3,131,123 | 3,132,089 | Boost.Test and Forking | I'm using Boost.Test for Unit testing and am currently running various mock servers in separate threads which get launched from within each test. In order to more accurately test my code the mock server's should really be in separate processes.
I was thinking about doing something along these lines:
MY_TEST()
if (for... | This doesn't really sound like unit-testing for what you want to achieve. Though I don't see why it would not be safe. You may have a race condition where your unit test connects to the MockServ if it isn't ready yet, but that is easily solvable.
I've never done something like this directly, but I have written unit tes... |
3,131,294 | 3,131,394 | Situation where mutexes are necessary? | Can someone help me out with example of a situation in which absence of mutexes "definetely" leads to incorrect result.
I need this so that I could test my mutex implementation.
--
Neeraj
| Consider any correct code that uses mutexes for synchronization. By removing the locking, you will introduce new (possibly incorrect) behaviors (executions) to the program. However, the new code will still contain all of the old behaviors, therefore there will always be at least one execution that will yield a correct ... |
3,131,298 | 3,131,343 | File Reading issue in c++ | I have the following program,
int iIndex=0;
char cPort[5]={"\0"};
char cFileChar;
fopen_s(&fFile,"c:\\Config\\FileName.txt","r");
if(fFile !=0)
{
cFileChar = getc(fFile);
while (cFileChar!= EOF)
{
cPort[iIndex]=cFileChar;
iIndex++;
cFileChar = getc(fFile);
}
iDIPort=atoi(cPort);
}
in the file I hav... | You write the 5 characters into the cPort array. That's OK. But then, you use cPort as a parameter to the atoi function. This function expects a C zero-terminated-string as argument. As your cPort variable has no space to store this zero-value-char to indicate the end of the string, your code depends on what is right a... |
3,131,478 | 3,131,722 | Duplicate literals and hard-coding | I see the follow pattern occurring quite frequently:
b->last = ngx_cpymem(b->last, "</pre><hr>", sizeof("</pre><hr>") - 1);
Notice that the literal string is used twice. The extract is from the nginx source-base.
The compiler should be able to merge these literals when it is encountered within the compilation unit. ... | Note that for the specific case of sizeof("</pre><hr>"), it is virtually certain that the string literal will never appear in the output file - the entire sizeof expression can be evaluated to the integer constant 11 at compile-time.
Notwithstanding, it is still a very common optimisation for compilers to merge identic... |
3,131,532 | 3,185,312 | IPv6 Zone index and scope_id | How does the zone index relate to the scope_id in the sockaddr_in6 structure?
The functionality appears to differ between platforms and I'd love to know how they relate. Windows for example has a SCOPE_ID structure (as well as just a 32-bit value). Mac OSX only has a 32-bit value. Obviously the 32-bit value is the w... | The index of zone and scope are the same and frequently interchanged, however the terms themselves are different.
Scope is used as in "global scope", "local scope", "universal scope" and refer to how unique a particular IPv6 address is. Every interface has a local scope which is unique to the immediate LAN segment, wh... |
3,131,715 | 3,131,781 | Understanding template classes in c++ - problem with new-operator | Dear all, I've been stuck with this problem now for a few days and my searches were not successful.
What I am trying to do:
I want a template reader class (VariableReader) to handle different types of variables (usually unsigned int and pointers to vector).
I started with
#ifndef READER_H_
#define READER_H_
#include <... | The C++ FAQ Lite section on How can I avoid linker errors with my template functions? shows two solutions:
Move the template class's methods into the .h file (or a file included by the .h file).
Instantiate the template in the .cpp file using template VariableReader<unsigned int>;.
|
3,131,991 | 3,132,035 | Iterating over 2-dimensional STL vector c++ | I'm currently trying to print out a history of movements for players in a game I am working on. At the end of each round every player has moved some amount in the positive or negative direction and this gets recorded as an int in the movement vector. Eventually I'm wanting to plot the directions moved vs time for each ... | You need to use a const_iterator if the vector is a const reference. Also, to output col you only need to dereference it once.
void output_movement(const std::vector< std::vector<int> > & movement){
std::vector< std::vector<int> >::const_iterator row;
std::vector<int>::const_iterator col;
for (row = moveme... |
3,132,491 | 3,132,550 | How can i optimize this dijkstra structure code? | This is the dijkstra structure i am using :(however the MAXV(which is maximum number of vertices is maximum at 500 and every time i try to change it to something more than this it generates and error when running )
-I want to use this way to represent a graph with 10000 vertices, does anyone know how to optimize it ?
#... | Use adjacency lists for storing the graph. Right now you're using an adjacency matrix, which means that you allocate MAXV*MAXV*sizeof(edge) bytes just for that. That's a lot when MAXV is 10 000, so you're probably getting a segmentation fault. Switching to adjacency lists will get rid of the error.
However, even with a... |
3,132,607 | 3,132,884 | Static class variable--use with constructors | I have a class with a static variable: null.
static Pointer<Value> Null;
Pointer is a class which uses reference count memory management.
However, I get an error: no matching function for call to Pointer::Pointer()
On the line:
Pointer<Value> Value::Null(new Value());
Thanks.
Excerpt of Pointer class:
template <typen... | I'm assuming your class is named Value.
// Header file
class Value
{
public:
...
static const Pointer<Value> Null;
};
// This should be in the cpp file.
const Pointer<Value> Value::Null(new Value);
|
3,132,608 | 3,132,682 | Multi-Threading on multi core architecture | When you have a situation where Thread A reads some global variable and Thread B writes to the same variable, now unless read/write is not atomic on a single core, you can do it without synchronizing, however what happens when running on a multi-core machine?
| Even on a single core, you cannot assume that an operation will be atomic. That may be the case where you're coding in assembler but, if you are coding in C++ as per your question, you do not know what it will compile down to.
You should rely on the synchronisation primitives at the level of abstraction that you're cod... |
3,132,811 | 3,133,057 | Borland Warning 8092 | Regarding the following C++ code,
LengthAlphabeticalSort lengthAlphabeticalSort;
outputList.sort(lengthAlphabeticalSort); // causes borland 8092 error, guaranteed stable_sort.
class LengthAlphabeticalSort
{
public:
bool operator() (std::string str1, std::string str2)
{
if(str1.length() ... | Well, the sort member function on a std::list does take a binary functor like yours, so from looking at your posted code, I'd say your compiler is wrong.
However, the error message you posted puzzles me:
random iterator required in function Worder::CommonWords(const Worder &) const
Why is it saying that a random itera... |
3,132,935 | 3,132,998 | how to get message of catch-all exception | If I want to write useful info to a file whenever i caught a catch-all exception, how to do it?
try
{
//call dll from other company
}
catch(...)
{
//how to write info to file here???????
}
| You can't get any information out of the ... catch block. That is why code usually handles exceptions like this:
try
{
// do stuff that may throw or fail
}
catch(const std::runtime_error& re)
{
// speciffic handling for runtime_error
std::cerr << "Runtime error: " << re.what() << std::endl;
}
catch(const st... |
3,133,132 | 3,133,187 | how to catch exception in C# which call a C++ dll | My C# called a method from a C++ dll, after the call returned, my application just gone without any message. want to add try catch to get the reason. how can I do it. Just a try-catch in the method call?
EDIT:
the [HandledProcessCorruptedStateExceptions] is not belong to C#?
| An interesting article on exception handling, also with respect to handling corrupted state exceptions:
CLR Inside Out: Handling Corrupted State Exceptions
However, I would assume that there is something wrong either in the way you are calling the native method or in the native method itself. It's best to fix the ori... |
3,133,286 | 3,133,314 | Header file throwing errors in one project, but not in another | I'm trying to integrate two projects, and to that end am including header files from one into the other. I'm using visual studio 2008 express.
The line
int E4407B_PPM(int &);
is throwing errors in the new project, but the original project compiles just fine.
The error I'm getting:
error C2143: syntax error : missing '... | You are probably building the second project (or at least the source file) as straight C. Make sure the file has a .cpp extension or that you are forcing a C++ compile (you can use the /TP compile option to do that).
Edit You can specify it for a single file: Right click on the file in the solution explorer and sele... |
3,134,060 | 5,247,114 | Is it possible to have a QMaemo5ListPickSelector which displays images as items? | I wanted to know if its possible to have a QMaemo5ListPickSelector but one which displays rectangular images as list items instead of text ? Is this possible ? If not, is there any other list-like object in Qt which can show images as items instead of text ?
| You can access list view using QMaemo5ListPickSelector::view() and set item delegate for this view using QAbstractItemView::setItemDelegate(). In delegate item's visual presentation is pretty much unlimited. See Star Delegate example to get into the details of delegate's implementation
http://doc.qt.nokia.com/qt-maemo/... |
3,134,099 | 3,268,045 | Exception thrown when exiting program (Ogre3d) | I am getting a weird exception when I exit the program. This has started since today morning and I am ready to pull my hair out. As soon as I exit the program, visual studio gives an exception and stops at line 731 in the file crt0dat.c (see attached screenshot)
I know this is very little to go on. I have tried several... | Thanks for everybody's help on this problem. I ended up re-installing windows (I tried uninstalling Visual Studio and re-installing it, but something went wrong while uninstalling VS [I followed Microsoft's instructions to the letter] and it would refuse to install again [the setup would crash]). I wish they would make... |
3,134,183 | 3,134,368 | Understanding the low-level mouse and keyboard hook (win32) | I'm trying to capture global mouse and keyboard input.
LRESULT CALLBACK MouseHookProc(int nCode, WPARAM wParam, LPARAM lParam) {
if (nCode >= 0) {
if (wParam == WM_RBUTTONDOWN) printf("right mouse down\n");
if (wParam == WM_RBUTTONUP) printf("right mouse up\n");
}
return CallNextHookEx(0, nCode, wParam, ... | The problem is your message loop, it burns 100% CPU cycles because you use PeekMessage(). Windows knows how to keep the hook alive even if you don't poll for messages, use GetMessage() to solve your problem. Using Sleep(1) will solve your problem too but is not necessary here.
Why must SetWindowsHookEx be used with a... |
3,134,310 | 3,139,726 | Use a model as a source for a QMenu | I created a model which list the existing configurations (let's say it lists "files", as this doesn't really matter here). So far, it works well when attached to a QListView.
Example:
--- ListView ---
- file #1 -
- file #2 -
- file #3 -
- file #4 -
----------------
Is it possible to use the same mo... | If your objective is just to update your menu actons with the item text that are available in the QAbstractListModel, then the answer is Yes.
Here is a way..
Individual item's index can be obtained by using the following function.
QModelIndex QAbstractListModel::index ( int row, int column = 0,
const QModelIndex & par... |
3,134,362 | 3,134,393 | Threading on both Windows and Linux | I have seen tutorials on the internet for making multithreaded applications in C++ on Windows, and other tutorials for doing the same on Linux, but not for both at the same time. Are there functions that would work even if they were compiled on either Linux or Windows?
| You would need to use a library which contains an implementation for both pthread on Linux and the Win32 threading library on Windows (CreateThread and friends).
Boost thread is a popular choice which abstracts the system away.
|
3,134,416 | 3,134,442 | Why should an API return 'void'? | When writing an API or reusable object, is there any technical reason why all method calls that return 'void' shouldn't just return 'this' (*this in C++)?
For example, using the string class, we can do this kind of thing:
string input= ...;
string.Join(input.TrimStart().TrimEnd().Split("|"), "-");
but we can't do this... | Methods that return void state more clearly that they have side effects. The ones that return the modified result are supposed to have no side effects, including modifying the original input. Making a method return void implies that it changes its input or some other internal state of the API.
|
3,134,458 | 3,134,505 | how to initialize a char array? | char * msg = new char[65546];
want to initialize to 0 for all of them. what is the best way to do this in C++?
| char * msg = new char[65546]();
It's known as value-initialisation, and was introduced in C++03. If you happen to find yourself trapped in a previous decade, then you'll need to use std::fill() (or memset() if you want to pretend it's C).
Note that this won't work for any value other than zero. I think C++0x will offe... |
3,134,532 | 3,134,701 | MySql Connector prepared statement only transfers 64 bytes | I am using the MySql Connector C++ to store a JPEG image from a file into the database. I am using the prepared statement. After execution of the prepared statement, only the first 64 bytes of the file are copied into the database.
My research of examples show that no iteration is necessary and the examples assume ... | The issue lies in the constructor of the image file:
std::ifstream blob_file(filename.c_str());
This should have the binary mode attribute:
std::ifstream blob_file(filename.c_str(), std::ios_base::binary);
The file, a JPEG image, is binary data.
Also, the hex dump at byte 65 shows 1a, which is the Windows OS en... |
3,134,718 | 3,134,744 | Define bitset size at initialization? | I want to make a bitset in C++. I did a bit of research. All examples I found where like this:
bitset<6> myBitset;
// do something with it
But I don't know the size of the bitset when I define the variable in my class:
#include <bitset>
class Test
{
public:
std::bitset *myBitset;
}
This won't compile...
And init... | Boost has a dynamic_bitset you can use.
Alternatively, you can use a vector<bool>, which (unfortunately) is specialized to act as a bitset. This causes a lot of confusion, and in general is considered a bad idea. But that's how it works, so if that's what you need, you might as well use it, I suppose.
|
3,134,738 | 3,134,809 | Indexing hash tables | I am just starting to learn hashtables, and so far, I know that you take the object you want to hash and put it through an hash function, then use the index it returns to get the corresponding object you want. There is something I don't understand though:
What structure do you use to store the objects in so you can qui... | Yes, you usually use an array but then you do a couple of things:
You convert the hash code to an array index by using the remainder of the hash code divided by the array size.
You make the size of the array a prime number as that makes step #1 more efficient (some hash algorithms need this to get a uniform distributi... |
3,134,743 | 3,134,895 | C++ program design question | In couple of recent projects that I took part in I was almost addicted to the following coding pattern: (I'm not sure if there is a proper name for this, but anyway...)
Let's say some object is in some determined state and we wan't to change this state from outside. These changes could mean any behaviour, could invoke ... | I hope this isn't taken offensively, but I can't help but think this design is an overly fancy solution for a rather simple problem.
Why do you need to aggregate mutators, for instance? One can merely write:
template <class T>
void mutate(T& t)
{
t.mutate1(...);
t.mutate2(...);
t.mutate3(...);
}
There's yo... |
3,134,745 | 3,195,976 | LNK 2028 - 2019 / Managed and Unmanaged C++ ? (VS 2008) | I am trying to link an open-source library to one of my project. The library is unmanaged (named Tetgen) and my project is in managed C++.
My project recognizes the header and can use the functions defined in it. But I get a 2028 error each time it wants to access to some methods defined in the .cpp:
error LNK2028: u... | That was because of a linker problem linking to different folders containing the same files.
|
3,134,821 | 3,134,958 | Local time with milliseconds | how can I get current time with library boost. I can do this:
ptime now = boost::posix_timesecond_clock::local_time();
tm d_tm = to_tm(now);
But the last time unit of tm structure is second and I need in millisecond. Can I get current time with milliseconds?
| look at boost::posix_time::microsec_clock::local_time()
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <iostream>
int
main()
{
boost::posix_time::ptime time = boost::posix_time::microsec_clock::local_time();
boost::posix_time::time_duration duration( time.time_of_day() );
std::cout <<... |
3,134,831 | 3,134,855 | In C++, is it still bad practice to return a vector from a function? | Short version: It's common to return large objects—such as vectors/arrays—in many programming languages. Is this style now acceptable in C++0x if the class has a move constructor, or do C++ programmers consider it weird/ugly/abomination?
Long version: In C++0x is this still considered bad form?
std::vector<std::string>... | Dave Abrahams has a pretty comprehensive analysis of the speed of passing/returning values.
Short answer, if you need to return a value then return a value. Don't use output references because the compiler does it anyway. Of course there are caveats, so you should read that article.
|
3,135,160 | 3,135,391 | Ways to Find a Race Condition | I have a bit of code with a race condition in it... I know that it is a race condition because it does not happen consistently, and it seems to happen more often on dual core machines.
It never happens when I'm tracing. Although, there is a possibility that it could be a deadlock as well. By analyzing stages of complet... | Put sleeps in various parts of your code. Something that is threadsafe will be threadsafe even if it (or asynchronous code) sleeps for even seconds.
|
3,135,261 | 3,135,358 | Difference between two vector<MyType*> A and B | I've got two vector<MyType*> objects called A and B. The MyType class has a field ID and I want to get the MyType* which are in A but not in B. I'm working on a image analysis application and I was hoping to find a fast/optimized solution.
| The unordered approach will typically have quadratic complexity unless the data is sorted beforehand (by your ID field), in which case it would be linear and would not require repeated searches through B.
struct CompareId
{
bool operator()(const MyType* a, const MyType* b) const
{
return a>ID < b->ID;
... |
3,135,296 | 3,135,628 | Call C/C++ code form a fortran program in visual studio? (How to compile mixed C and fortran code in visual studio) | i am looking for a way, how i can integrate a c++ code with fortran code (i want simply call some C/C++ functions in the fortran code).
I have found some proposals for gcc or console compilers, but i have not any idea how to translate this approach to solve integrationproblem within the visual studio.
At the time I am ... | There is a new way to do this that has many advantages -- use the Fortran 2003 ISO C Binding. This is a standard and therefore largely OS and language independent way of interfacing Fortran and C (and any language that will use C calling conventions). Intel Fortran 11 supports along with numerous other compilers --... |
3,135,738 | 3,135,818 | How is a pipe reading with a size of 4 bytes into a 4 byte int returning more data? | Reading from a pipe:
unsigned int sample_in = 0; //4 bytes - 32bits, right?
unsigned int len = sizeof(sample_in); // = 4 in debugger
while (len > 0)
{
if (0 == ReadFile(hRead,
&sample_in,
sizeof(sample_in),
&bytesRead... | Judging from your comment that says //36 bits? I suspect that you're expecting the data to be sent in a BCD-style format: In other words, where each digit is a number that takes up four bits, or two digits per byte. This way would result in wasted space however, you would use four bits, but values "10" to "15" aren't u... |
3,135,795 | 3,136,016 | Why does this template class in a library generate linker errors when used? | I've got the following setup. RectangleT class defined in a header file in a library. Attempted to use the class in my main application. When linking I get an error for every function I try to call - except constructor and the GetLeft/GetTop/GetRight/GetBottom - BUT - I do get the error when calling GetWidth / GetHeigh... | I removed compiler directive MY2D_API and tried your code, it works fine, see below.
Windows 7, MS VS 2010
int main ()
{
My2D::RectangleT < int > rect;
rect.SetBottom(3);
rect.SetLeft(3);
rect.SetRight(8);
rect.SetTop(8);
return rect.GetHeight();
}
|
3,135,947 | 3,135,998 | Access own bank account via self-written application | I have used MS Money for several years now and due to my "coding interest" it would be great to know where to start learning the basics for programming such an application. Better to say: Its not about how to design and write an application, its about the "bank details". (Just displaying the amount of a certain bank ac... | Most of the apps I've worked with read in a file exported from the bank's website, which is relatively straight forward.
If that's the road you're looking to go down you'll need to write code to:
Login to the bank's website to download the file via HTTPS
Either get specs for the file format or reverse engineer it
App... |
3,136,038 | 3,136,215 | Select() + UDP resulting in too many open files | I currently have a select() statement configured to keep track of two UDP sockers. I send perhaps 10 - 20 messages a second at one general data socket, which is this interpreted as I expected.
However, once I hit around 1024 messages, I get the notice:
talker: socket: Too many open files
talker: failed to bind sock... | I think in this case "Too many open files" really means you've hit the file descriptor limit; network sockets count towards this limit. Are you sure that there's nothing else - say in routehelper - that's creating further sockets?
What platform are you running on? If Linux, lsof or grobbling around in /proc/<pid>/fd - ... |
3,136,044 | 3,136,076 | pwsz string confusion | I have never posted before so I am sorry if I am not clear. I am trying to use a third party DLL written in c++ on 2005 and all I have is some very poor documentation. I am dynamically linking to the DLL and using the Ordinal value read from Dependency walker to get a pointer to a method in the DLL. Such as (LPFNDDLLZC... | You could use MultiByteToWideChar to turn your LPSTR into an LPWSTR which should solve your problem.
|
3,136,054 | 4,292,423 | Need help with configuration of codeblocks for Qt ! | codeblocks 8.02. , win xp SP2 , Qt 4.6
After installing Qt SDK, I installed QtWorkbench (codeblocks plugin that allows you to create Qt applications.) http://code.google.com/p/qtworkbench/.
I worked under instructions from that page. I opened the folder "dialogs" and in it I opened a new empty codeblocks project. Also ... | I 'm the author of QtWorkbench and I have stopped supporting it some time ago. I 'm pretty sure it's outdated by now. I really think that new Qt users should go with QtCreator the "official" Qt IDE to get the best support out of the box. QtWorkbench is still in Google Code in case any one wants to pick up developing i... |
3,136,055 | 3,136,166 | wxWidgets: wxString::wxString(int) private within this context | I have a subclass of wxHtmlListBox called TestClass, but I get the error:
/usr/include/wx-2.8/wx/string.h:682:0 /usr/include/wx-2.8/wx/string.h:682: error: 'wxString::wxString(int)' is private
MainFrame.cpp:106:0 MainFrame.cpp:106: error: within this context
MainFrame.cpp line 106 is this:
TestClass *tc = new T... | You're passing wxBORDER_DEFAULT into a const wxString reference:
TestClass(
wxWindow* parent, // this
wxWindowID id = wxID_ANY, // wxID_ANY
const wxPoint& pos = wxDefaultPosition, // wxDefaultPosition
const wxSize& size = wxDefaultSize, // wxDefaultSize
long style = 0, // NULL
const wxString& na... |
3,136,105 | 3,136,164 | Best way to do alpha blending with OpenGL? | I'm drawing 2D Polygons, actually I'm drawing lots of triangles and using GLUOrtho2D. I noticed that by zooming out I got much better frame rates. I realized I was maxing out the graphics card's fill rate, not drawing too many polygons as I had initially suspected. I think this is because I'm drawing lots of overlappin... | I doubt using a different blend function would help. One generally chooses the correct blend function based on desired output, not performance.
Are all the polygons you render transparent/translucent? If not, it might help to separate the rendering of those apart from the opaque polygons you have and set the proper GL ... |
3,136,267 | 3,136,285 | Set individual bit in C++ | I have a 5 byte data element and I need some help in figuring out how in C++ to set an individual bit of one of these byte; Please see my sample code below:
char m_TxBuf[4];
I would like to set bit 2 to high of byte m_TxBuf[1].
00000 0 00
^ This one
Any support is greatly appreciated;
Thanks!
| Bitwise operators in C++.
"...set bit 2..."
Bit endianness.
I would like to set bit 2 to high of byte m_TxBuf[1];
m_TxBuf[1] |= 1 << 2
|
3,136,520 | 3,136,537 | Determine if map contains a value for a key? | What is the best way to determine if a STL map contains a value for a given key?
#include <map>
using namespace std;
struct Bar
{
int i;
};
int main()
{
map<int, Bar> m;
Bar b = {0};
Bar b1 = {1};
m[0] = b;
m[1] = b1;
//Bar b2 = m[2];
map<int, Bar>::iterator iter = m.find(2);
Ba... |
Does something along these lines exist?
No. With the stl map class, you use ::find() to search the map, and compare the returned iterator to std::map::end()
so
map<int,Bar>::iterator it = m.find('2');
Bar b3;
if(it != m.end())
{
//element found;
b3 = it->second;
}
Obviously you can write your own getValue() ro... |
3,136,594 | 3,136,618 | Naming convention - underscore in C++ and C# variables | It's common to see a _var variable name in a class field. What does the underscore mean? Is there a reference for all these special naming conventions?
| The underscore is simply a convention; nothing more. As such, its use is always somewhat different to each person. Here's how I understand them for the two languages in question:
In C++, an underscore usually indicates a private member variable.
In C#, I usually see it used only when defining the underlying private mem... |
3,136,616 | 3,136,629 | multiple definition linker error after adding a function to a previously linking file | So my program is working fine. Compiling, linking, running, the works. Then, I decide to add a simple function to one of my files, like this:
#ifndef UTILITY_HPP
#define UTILITY_HPP
/* #includes here. There's no circular include, I've checked. */
namespace yarl
{
namespace utility
{
(several functi... | Either declare the function inline, or define it in a separate .cpp file. Otherwise every C++ file in which you include the header is trying to make its own, publicly-available definition of the function.
Edit: and fwiw, you don't need to explicitly return true or false if you're testing a conditional. Just return the ... |
3,136,625 | 3,136,707 | I can't make this dijkstra code compile. (The Algorithm Design Manual) | This Code is a code I built from the algorithm design manual book but I can't make it compile cause I've got little experience with pointers I think that's the main reason I think I can't compile it:
And if someone can change a little bit in the djikstra to make it through heap with the current configuration.
#include<... | Change the definition of the struct, and it would compile.
struct edgenode_tag
{
int y;
int weight;
struct edgenode_tag *next;
};
typedef edgenode_tag edgenode;
While this will solve your problem, don't trust my answer below until someone better than me comments on it.
What was wrong in your code ?
You are... |
3,136,651 | 3,136,675 | Is there a standard C++ class that is like QByteArray? | Is there a STL C++ class that works like QByteArray?
| std::string
or
std::vector<unsigned char>
|
3,136,765 | 3,136,813 | How many gumballs in the jar. 2 errors | Trying to code a guess how many gumballs in the gumballs jar, kinda thing. There are two problems I keep getting:
It's supposed to say if the guess is to high or to low but that only happens when i enter a number over 1000 and it says:
Enter your guess: 1001
Too High!
Too Low!
Enter your guess:
If you type a let... | Let me hint at one problem. Let's take a look at the two checks you have for printing the message "too high" and "too low":
if(iUserguess > iGumballs)
if(iUserguess > iGumballs)
Notice anything wrong when I put them together?
|
3,136,790 | 3,137,072 | Using boost::mpl::lambda to remove types from a boost::mpl::list based on static const member variable | I have a list of types defined as:
typedef boost::mpl::list<Apple, Pear, Brick> OriginalList;
I would like to create a second list that does not contain any fruit, i.e. the resultant list formed from the first list would contain a single type Brick. Fruit is identified through a static const variable defined within th... | I think the best you can do is to define an IsFruit struct like
template <typename T> struct isFruit : boost::mpl::bool_<T::IsFruit> {};
And then you can define your no-fruit list as
typedef boost::mpl::remove_if<
OriginalList,
boost::mpl::lambda< isFruit< boost::mpl::_1 > >::type
>::type NoFruitList;
The addi... |
3,136,919 | 3,137,174 | C++ state design pattern with multiple state machines | I have a C++ state machine implemented using the State design pattern. Each state is implemented as a nested friend class of the context class.
class Context {
public:
/* The Context class' user calls process1() to get it to perform an action */
void process1();
private:
class IState;
void switchState( IState... | I assume that in your code, switchState is invoked by the individual states when it's time to transition to something else. Something like this:
void StateA::doProcess(Context& context) {
context.switchState(new StateB()); // NOTE: potential leak!
}
Is this the case?
If so, one thing you might consider is having th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.