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 |
|---|---|---|---|---|
1,802,929 | 1,802,952 | How can we use .NET dll in VC++? | Please suggest me the best way to use .NET dll in VC++ project.
| Make it ComVisible. See link text
|
1,803,079 | 1,803,110 | What is the advantage of using initializers for a constructor in C++? | Sphere() : theRadius(1.0)
{
}
Why is it preferable to have a constructor written with initializers (above) than a constructor that initializes the data members within its body (below)?
Sphere()
{
theRadius = 1.0;
}
| All members are initialised before entering the body of the constructor. If you don't provide an initialiser in the init list, then they're default constructed.
In your first example the following happens:
theRadius is initialised to 1.0
In your second example the following happens:
theRadius is initialised
1.0 is ... |
1,803,112 | 1,803,408 | Set a QComboBox or QSpinBox to a value not allowed | I am maintaining an application which tries to help the user get his parameters to work together, as there are many interdependencies.
Now there is a default value of x for a variable Y. When the user changes some other variable Z, there might be a new minimum value for Y which is greater than x. This is set as a mini... | As one approach you may create new class, inherited from Qt standart QSpinBox(or in second case from QComboBox) and add your own logic to them: posibility to show value below the minimum, but when someone want explicitly change value in your input widgets, you will check for bounds.
|
1,803,281 | 1,803,294 | Pointer for item in iteration over std::list | I'm working on a very basic game and I have a std::list collection of objects that pertain to my game. I declared it as:
std::list<Target> targets;
When I iterate over it, using
for (std::list<Target>::iterator iter = targets.begin(); iter != targets.end(); iter++) {
Target t = *iter;
t.move();... | You are copying the objects, do it this way:
*iter.move()
If you use Target t = *iter; you are essentially making a copy of your object and moving it, instead of moving your intended object.
As xtofl said(thx) you can get the reference as well.
Target &t = *iter;
t.move();
|
1,803,590 | 7,623,152 | Waf generating Visual Studio projects? | Can the Waf build system generate Visual Studio project files for C/C++?
| An "extra" tool does now (check waflib/extras/msvs.py).
Since this is used by the waf author, I think you can rely on it.
|
1,803,887 | 1,804,079 | Locks and Mutexes in C++ | I have learnt C++ for a while and still didn't come across good book which would explain what are those beasts? Are they integral C++ feature? If so how is it that they are only mentioned in such book like The C++ Programming Language by B.S. If not, where can you get reliable information about them - prefferably a boo... | Locks and Mutexes are concurrency constructs used to ensure two threads won't access the same shared data at the same time, thus achieving correctness.
The current C++ standard doesn't feature concurrency tools.
Although you mentioned you prefer books to online tutorials, Herb Sutter's Effective Concurrency column is d... |
1,803,989 | 1,804,354 | Setting a column style? (Unmanaged c++) | I'm currently able to set a listview style VIA the ListView_SetExtendedListViewStyle method, however this makes all columns have the same style. My goal is to only modify one column (to basically have the LVS_EX_UNDERLINEHOT|LVS_EX_UNDERLINECOLD|LVS_EX_TWOCLICKACTIVATE style).
Is there a way to modify the style of only... | If you use the WTL framework then there is a very useful CCustomDraw class that you can use to easily intercept NM_CUSTOMDRAW messages and draw your own listview content.
There is a good CodeProject article on custom draw using WTL here.
|
1,804,148 | 1,808,002 | Runtime error: Access violation when using .push_back() with a std::vector? | I have a vector, defined by std::vector<LPDIRECT3DTEXTURE9> textures; Later, I am passing a LPDIRECT3DTEXTURE9 object to it, like so textures.push_back(texture); Here is a sample of this:
void SpriteManager::AddSprite(float x, float y, float z, LPDIRECT3DTEXTURE9 texture)
{
//snip
textures.push_back(texture);... | By far the most common reason is that you actually don't have a vector. In this case, textures appears to be a member of the SpriteManager class. So, that suggest you actually don't have a SpriteManager object either. Is the this pointer valid?
|
1,804,398 | 1,804,482 | Using a virtually inherited function non-virtually? | I have run into trouble trying to implement functionality for serializing some classes in my game. I store some data in a raw text file and I want to be able to save and load to/from it.
The details of this, however, are irrelevant. The problem is that I am trying to make each object that is interesting for the save fi... | The problem is not in your attempt to call a virtual function non-virtually. The problem is this line: os = Character::operator<<(os);. That is an assignment, but std::ostream doesn't have an operator=.
You don't need the assignment anyway. The stream returned is the same stream as the stream you pass in. The only rea... |
1,804,514 | 1,809,788 | How to accept empty value in boost::program_options | I'm using boost::program_options library to process command line params.
I need to accept a file name via -r option, in case if it is empty (-r given without params) I need to use stdin.
desc.add_options()
("replay,r", boost::program_options::value<std::string>(), "bla bla bla")
In this case boost wouldn't accept -r ... | Please use the implicit_value method, e.g
desc.add_options()
("replay,r", po::value<std::string>()->implicit_value("stdin"), "bla bla bla")
This makes the option accept either 0 or 1 token, and if no tokens are provided, it will act as if 'stdin' was provided. Of course, you can pick any other implicit value -- inclu... |
1,804,606 | 1,804,618 | Static initialization and destruction of a static library's globals not happening with g++ | Until some time ago, I thought a .a static library was just a collection of .o object files, just archiving them and not making them handled differently. But linking with a .o object and linking with a .a static library containing this .o object are apparently not the same. And I don't understand why...
Let's consider ... | .a static libraries contain several .o but they are not linked in unless you reference them from the main app.
.o files standalone link always.
So .o files in the linker always go inside, referenced or not, but from .a files only referenced .o object files are linked.
As a note, static global objects are not required t... |
1,804,728 | 1,820,918 | How to receive drag and drop from Apple Address book in Qt 4.4 on Mac OS X 10.5/10.6 | I am trying to trap drag and drop events from the standard Apple address book app to my Qt app. This code works fine with Qt 4.4. on Mac OS X 10.4:
void
MyView::contentsDropEvent( QDropEvent* e )
{
QList<QUrl> urls = e->mimeData()->urls();
...
I can then use the URL to get the vCard. Marvellous.
But from Mac ... | richardmg of Qt/Nokia kindly supplied me with some example code. I have filled in some of the gaps. This now works fine on Mac OS X 10.5.
#include <QtGui>
class VCardMime : public QMacPasteboardMime
{
public:
VCardMime() : QMacPasteboardMime(MIME_ALL)
{ }
QString convertorName()
{
return Q... |
1,804,734 | 1,804,742 | How can I perform a file search in C++ | I just started learning C++ and am currently using codeblocks.
I want to write an application that can search for files in a directory including its subdirs, but I cant seem to find any good examples for this and I've read somewhere that this is only possible through a library like boost.
Is this true?
Are there any e... | It's also possible to use it using OS system calls, readdir on linux for example. boost (and other libraries) will allow you to write portable code for several (all?) OSes.
Here u can find elaborate examples http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1046380353&id=1044780608
|
1,804,840 | 1,804,924 | Extending enums in C++? | Is there a way in C++ to extend/"inherit" enums?
I.E:
enum Enum {A,B,C};
enum EnumEx : public Enum {D,E,F};
or at least define a conversion between them?
| No, there is not.
enum are really the poor thing in C++, and that's unfortunate of course.
Even the class enum introduced in C++0x does not address this extensibility issue (though they do some things for type safety at least).
The only advantage of enum is that they do not exist: they offer some type safety while not ... |
1,805,209 | 1,805,316 | Multiple association problem with C++ | How would you solve this problem? (At the beginning it seemed simple, then I found it to be puzzling).
You have a class called Executor. Suppose you have many instance of it and they do different things upon call of a method do(Argument).
Argument has 2 different parameters and they are A* pa, B* pb (one of which can... | I think you want to create a class called "Subscription" which represents a single subscription from an Executor to a Manager containing information on under what conditions the this Subscription would trigger, as well as some sort of GUID or name for this subscription. I'm thinking something like
class Subscription
... |
1,805,445 | 1,805,474 | Boost lib linker error Visual C++ | I downloaded the source for Launchy and am trying to build it in Visual Studio 2005. The Launchy project is built using VC7 so I had to update the project files to VC8 and that process seemed to go well. However, Launchy also uses the Boost 1.33.1 libs and what I have built are the Boost 1.41.0 libs (props to Boost f... | Difference is clearly described in Boost docs - "mt-sgd" means "debug, statically linked runtime libraries, multithreaded, with debug symbols". "mt-gd" is the same, but using dynamically linked runtime libraries (i.e. msvcrtd.lib instead of libcmtd.lib).
Either change project settings to use dynamic CRT linking (i.e. /... |
1,805,666 | 1,806,759 | How to store a vector of LPD3DXSPRITE objects? | Let's say I want to store a vector of LPD3DXSPRITE objects. The line to declare this code would be std::vector<LPD3DXSPRITE> sprites; I should be able to create my sprite with:
LPD3DXSPRITE sprite = NULL;
D3DXCreateSprite(myRenderingDevice, &sprite);
Finally, I should be able to add this to the vector like so:
sprit... | After looking through your code, I found the problem. Something to look at when you get any breaks in your application is the "Autos" tab or the Locals tab. Here you'll notice something about the this pointer: it's null!
That means the instance that AddSprite is being called on doesn't exist. This is your SpriteManager... |
1,805,906 | 1,805,917 | C / C++ Library for HTTPS Client with Basic Authentication | Do you recommend any good library or examples online for implementing an HTTPS client that can connect to a website using basic authentication? This is meant to run in linux servers.
Any pointers help.
Update: Question about the unanimous libcurl - does it come bundled by default in major distributions like Debian, Ubu... | libcurl supports both HTTPS and HTTP Basic Authentication. There's plenty of example code online.
All of the distributions you mention have libcurl packaged. It is not absolutely certain to be installed, but it is very common.
|
1,806,022 | 1,806,038 | Is this code legal in C++ | I just found that when it comes to templates this code compiles in g++ 3.4.2 and works unless m() is not called:
template <typename T>
class C
{
T e;
public:
C(): e(0) {};
void m()
{
e = 0;
};
};
Now one may create and use instance
C<const int> c;
Until c.m() is not called the... | Yes, this is legal. The template specification is that until a method is instantiated, it doesn't exist and therefor is not checked by the compiler. Here's the relevant bit from the spec:
14.7.1 - Implicit instantiation
-9- An implementation shall not implicitly instantiate a function
template, a member template, ... |
1,806,074 | 1,806,116 | C++ extract polynomial coefficients | So I have a polynomial that looks like this: -4x^0 + x^1 + 4x^3 - 3x^4
I can tokenize this by space and '+' into: -4x^0, x^1, 4x^3, -, 3x^4
How could I just get the coefficients with the negative sign: -4, 1, 0, 4, -3
x is the only variable that will appear and this will alway appear in order
im planning on storing th... | Once you have tokenized to "-4x^0", "x^1", etc. you can use strtol() to convert the textual representation into a number. strtol will automatically stop at the first non-digit character so the 'x' will stop it; strtol will give you a pointer to the character that stoped it, so if you want to be paranoid, you can verif... |
1,806,390 | 1,807,119 | Does a boolean condition in a for loop that is always false get optimized away? | I have the following situation
bool user_set_flag;
getFlagFromUser(&user_set_flag);
while(1){
if(user_set_flag){
//do some computation and output
}
//do other computation
}
The variable user_set_flag is only set once and only once in the code, at the very start, its essentially the user selec... | Firstly, processors have a capability called branch prediction. After a few runs of the loop, the processor will be able to notice that your if statement always goes one way. (It can even notice regular patterns, like true false true false.) It will then speculatively execute that branch, and so long as it able to pred... |
1,806,669 | 1,807,795 | Vertical Scrollbar in CListCtrl | I'm using a CListCtrl in Icon view, but it scrolls horizontally:
1 3 5 7 -->
2 4 6 8 -->
I'd rather it scroll horizontally:
1 2
3 4
5 6
| |
V V
Is there a way to do this?
| Change the Alignment style in designer from Left to Top.
|
1,806,687 | 1,806,752 | Why isn't my virtual function working? | I have an abstract class called camera which PointCamera uses as its super class. For some reason one of the virtual functions throw an error in the debugger and tells me that it is trying to execute 0x00000000. This only happens if the function in question is the last one declared in the abstract class. If I switch th... |
Ok I just re-compiled everything and it worked. I don't know what went wrong. Thanks for your suggestions.
Check your dependencies. I bet something that should be depending on a header file isn't. When you did a clean build, the source code file that relied on that header file was brought up to date.
|
1,806,711 | 1,806,737 | weird C++ constructor/copy constructor issues in g++ | #include <iostream>
using namespace std;
class X {
public:
X() {
cout<<"Cons"<<endl;
}
X(const X& x){
cout<<"Copy"<<endl;
}
void operator=(const X& x){
cout<<"... | To expand on @flyfishr64's answer
The copy constructor is invoked here because this:
X s = fun();
is an initialization. You are using fun() to construct the object, not invoking the default constructor. It is equivalent to:
X s(fun());
The "Cons" you see printed out is for the instance in fun(). See this article: Ass... |
1,807,033 | 1,807,435 | C++ GNU Linker Errors | I'm trying to complie my program on Windows via Cygwin with the compilation command:
g++ ping.cpp -I./include -L./lib -lchartdir50
I'm using an API called ChartDirector which draws charts for me. I've never linked libraries this way before (usually I do it through Visual Studio) so i'm a little new to this. I've got a... | Hmm... thats odd. I'm using a 64-bit system, but for some reason I tried it with the 32-bit library and it compiled. Thanks!
|
1,807,110 | 1,807,117 | Is it possible to have a while loop in c++ that makes the check in the middle of the loop instead of the beginning or end? | I want to have a while loop do something like the following, but is this possible in c++? If so, how does the syntax go?
do {
//some code
while( expression to be evaluated );
// some more code
}
I would want the loop to be exited as soon as the while statement decides the expression is no longer true( i.e... | You can do:
while (1) {
//some code
if ( condition) {
break;
}
// some more code
}
|
1,807,203 | 1,807,422 | Building optimized Qt4 - "./configure" flags and their meanings | I recently followed a discussion on the Qt4-interest mailing list about whether it is legal or not to build a commercial/proprietary application and statically link Qt4 into it. While there are some non-proven ways of doing so (by providing object files and a Makefile, etc. to the customer), it doesn't sound like such ... | There are few things that I can think of:
use a compiler/linker combination that does good size optimizations. MSVC is much better at this than MinGW for instance. All the Qt release DLLs built with MSVC total at ~21 MB. Built with MinGW they total at ~41 MB. By the way, do you really need to ship all the DLLs?
use t... |
1,807,297 | 1,807,321 | Question about what I should have before Connect | I have this included:
#include <sys/socket.h> /* for socket(), connect(), send(), and recv() */
/* Establish the connection to the echo server */
if (connect(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)
DieWithError("connect() failed");
But I am getting this:
TCPClient.cpp:395: error: no m... | I guess you have your own class ClientHandler with a connect method. To avoid confusion call connect from the global namespace:
::connect ( sock, ...
|
1,807,338 | 1,812,036 | Code leaks memory, seems to be coming from ID3DXBuffer | I load a shader with the following:
ID3DXBuffer* errors = 0;
ID3DXEffect* effect = 0;
HR(D3DXCreateEffectFromFile(
gd3dDevice, L"Shader.fx", 0, 0,
D3DXSHADER_DEBUG|D3DXSHADER_SKIPOPTIMIZATION,
0, &effect, &errors));
for (int i = 0; i < 3; i++) {
if(errors) {
errors->Release();
if (ef... | OK I fixed it, was just a logic issue, 'error' didn't have 'release' called on it on the third try hence the issue.
|
1,807,360 | 1,807,431 | Conditionally instantiate a template at run-time | I have a template class
template <class T>
class myClass
{
public:
/* functions */
private:
typename T::Indices myIndices;
};
Now in my main code I want to instantiate the template class depending on a condition. Like :
myFunc( int operation)
{
switch (operation) {
case 0:
... | Create a base class
class Base {
protected:
virtual ~Base() {}
//... functions
};
template <class T> class myClass : Base {
//...
};
myFunc( int operation){
shared_ptr < Base > ptr;
switch (operation) {
case 0:
// Instantiate myClass with <A> ... |
1,807,516 | 1,807,532 | Conditional operator issue | I'm having some trouble with using the conditional operator to get a reference to an object. I have the a setup similar to this:
class D
{
virtual void bla() = 0;
};
class D1 : public D
{
void bla() {};
};
class D2 : public D
{
void bla() {};
};
class C
{
public:
C()
{
this->d1 = new D1()... | Cast to D& within both branches:
D& d = (rand() %2 == 0 ? static_cast<D&>(c.getD1()) : static_cast<D&>(c.getD2()));
|
1,807,523 | 1,807,601 | Instantiation of function object with different inline function definitions depends on order of linkage | Please help me understand the root cause of the following behaviour.
In file a.cpp I have:
namespace NS {
struct Obj {
void pong(){ cout << "X in "__FILE__ << endl; }
double k;
};
X::X() { Obj obj; obj.pong(); }
void X::operator()() { cout << "X says hello" << endl; }
}
In file b.cpp I have:
n... | This is undefined behavior: The your class definitions define the same class type, and so they have to be both the same. For the linker it means it can choose one arbitrary definition as the one that gets emitted.
If you want them to be separated types, you have to nest them into an unnamed namespace. This will cause ... |
1,807,530 | 1,807,556 | Difference between using character pointers and character arrays | Basic question.
char new_str[]="";
char * newstr;
If I have to concatenate some data into it or use string functions like strcat/substr/strcpy, what's the difference between the two?
I understand I have to allocate memory to the char * approach (Line #2). I'm not really sure how though.
And const char * and string li... | Please go through this article below:
Also see in case of array of char like in your case, char new_str[] then the new_str will always point to the base of the array. The pointer in itself can't be incremented. Yes you can use subscripts to access the next char in array eg: new_str[3];
But in case of pointer to char, t... |
1,807,617 | 1,820,743 | C/C++ Macro expansion vs. Code generation | Both Macro expansion & Code generation have pros & cons. What's your favorite approach and why? When should we choose one over the other? Please kindly advise. Thank you!
Macro expansion can be very handy & helpful:
http://dtemplatelib.sourceforge.net/table.htm
vs
While Code generation gives you plenty of nice code:
ht... | It's a tradeoff. Let me give an example. I stumbled on the technique of differential execution around 1985, and I think it's a really good tool for programming user interfaces. Basically, it takes simple structured programs like this:
void Foo(..args..){
x = y;
if (..some test..){
Bar(arg1, ...)
}
while(..a... |
1,807,663 | 1,807,729 | How to write a const_iterator in VC++6? | I have implemented my own container class and need to implement a const_iterator for it. What is the easiest way to go about implementing const_iterator begin() const_iterator end() and const_iterator::operator++ for my own container class?
Please provide examples. Thanks!
| It seems boost library has a compatible version to be used with VC6 according to this question. In that case you can use either boost::iterator_facade or boost::iterator_adaptor to easily write a const_iterator class. If you can't use boost, then the only option I see is to write a class derived from std::iterator and ... |
1,807,816 | 1,807,842 | constructor as default argument | let's say i have 2 classes
class B
{
B() { /* BLA BLA */ };
B(int a) { /* BLA BLA */ };
B(int a,int b) { /* BLA BLA */ };
}
class A {
public :
A(B par);
}
i was wondering how can i call A's constructor with par having a deafult argument, as each of B constructors. (of course i would like see 3 examples, i... | You can do something like:
A(B par = B())
A(B par = B(1))
A(B par = B(1,2))
Full code as per comment:
class B
{
public:
B() { };
B(int a) {};
B(int a,int b) {};
};
class A {
public :
A(B par = B()/* or B(1) or B(1,2) */);
};
|
1,807,857 | 1,807,947 | repeatedly render loop with Qt and OpenGL | I've made a project with Qt and OpenGL.
In Qt paintGL() was repeatedly call I beleive, so I was able to change values outside of that function and call update() so that it would paint a new image.
I also believe that it called initializeGL() as soon as you start up the program.
Now my question is:
I want that same func... | The exact mechanism will depend on which GUI toolkit you are using. In general, your app needs to service the run loop constantly for events to be dispatched. That is why your app was unresponsive when you had it running in a while loop.
If you need something repainted constantly, the easiest way is to create a timer... |
1,807,944 | 1,808,025 | wxImage to Zip file via stream. Possible? | I'm trying to write out a zip file using the wxZipOutputStream. The code is from this forum and works with the xml file (when I used wxTextOutputStream). Now, I'm trying to include an image file but the SaveFile function in the wxImage class expects a class wxOutputStream but wxTextOutputStream/wxDataOutputStream have ... | It looks like you have to specify the type of image in the archive, try:
value->SaveFile(zip, wxBITMAP_TYPE_PNG)
(The file extension in key should of course be .png)
|
1,807,983 | 1,808,723 | Dividing by arbitrary numbers using shifting operators | How can you divide a number n for example by 24 using shifting operators and additions?
(n % 24 == 0)
| This works by first finding the highest bit of the result, and then working back.
int div24(int value) {
// Find the smallest value of n such that (24<<n) > value
int tmp = 24;
for (int n = 0; tmp < value; ++n)
tmp <<= 1;
// Now start working backwards to find bits of the result. This is O(i).
int result ... |
1,808,342 | 1,808,364 | Question about how to send images in socket programming? | I've got a couple questions about sending images over.
How do I handle different types of files, jpeg, png, etc.
If the file is large, I ave to use sequence numbers... but I don't know how to stop recving if I do not know the number of sequence numbers.
My knowledge of transfering images / files is next to none. I have... | If you use a TCP socket, you need no sequence numbers, because TCP already ensures that data arrive in the same order as they where send. Just send the data, and when done close the connection. Optionally you can use some self-defined type of packet header that gives additional information (e.g. if you want to transmit... |
1,808,471 | 1,808,579 | Is "const LPVOID" equivalent to "void * const"? | And if so, why some Win32 headers use it?
For instance:
BOOL APIENTRY VerQueryValueA( const LPVOID pBlock,
LPSTR lpSubBlock,
LPVOID * lplpBuffer,
PUINT puLen
);
A bit more elaboration: If the API never uses references (or any other C++-only constructs) but only pointers and values, what is the point o... | A typedef-name denotes a type, and not a sequence of tokens (as does a macro). In your case, LPVOID denotes the type also denoted by the token sequence void *. So the diagram looks like
// [...] is the type entity, which we cannot express directly.
LPVOID => [void *]
Semantically if you specify the type const LPVOID,... |
1,808,485 | 1,808,700 | Division of big numbers | I need some division algorithm which can handle big integers (128-bit).
I've already asked how to do it via bit shifting operators. However, my current implementation seems to ask for a better approach
Basically, I store numbers as two long long unsigned int's in the format
A * 2 ^ 64 + B with B < 2 ^ 64.
This number i... | The easiest way I can think of to do this is to treat the 128-bit numbers as four 32-bit numbers:
A_B_C_D = A*2^96 + B*2^64 + C*2^32 + D
And then do long division by 24:
E = A/24 (with remainder Q)
F = Q_B/24 (with remainder R)
G = R_C/24 (with remainder S)
H = S_D/24 (with remainder T)
Where X_Y means X*2^32 + Y.
Th... |
1,808,540 | 1,808,565 | string has not been declared, QT | I am trying to change a certain text box message. It will display my output.
This is what I have in my main()
#include "form2.h"
....
string recvMSG = "random";
182:: Form2::changeOutput(recvMSG);
...
within my form2.h I have:
#include <string.h>
#include <iostream>
#include <stdlib.h>
...
void F... | string is in the std namespace, so you either need to refer to it as std::string, or you need to make the name available in the current scope with using namespace std; or using std::string;.
Also the header is called string, not string.h, so include it this way:
#include <string>
Generally you also might want to use Q... |
1,808,581 | 1,809,773 | Char * marshalling in C# | I have this function in Visual C++ DLL
char * __stdcall GetMessage(int id) {
char buffer[250];
.
.
.
strcpy(buffer, entry); // entry is a char * that has allocated 250 chars
return (char *)buffer;
}
i am trying to import this function from C# with the following code
[DllImport("mydll.dll", CharSet=CharSet.Ansi)]
publi... | I'll re-emphasize the fact that your C++ code is invalid. You are returning a pointer to a local variable on a stack frame that is no longer valid when the function returns. That it works now is merely an accident. As soon as you call another function, the stack space will be reused, corrupting the buffer content. ... |
1,808,971 | 1,809,013 | tryentercritical section undeclared identifier | I get error TryEnterCriticalSection undeclared identifier during compilation. Visual studio knows about the function but the compiler does not. Other Critical Section functions are defined. I have included #define _WIN32_WINNT 0x0400 in stdafx.h per msdn. Definition in winbase.h is surrounded by #if(_WIN32_WINNT >=... | Where have you defined the _WIN32_WINNT symbol in the stdafx.h file? Is it before the #include <windows.h> line? If not then the symbol will be undefined in winbase.h.
|
1,808,994 | 1,809,029 | Oracle C++ linux and more weird stuff | So here is the story. I have this device that uses Linux and more open source tools(btw its an ARM). And I was given the task of creating some magic cashier application with it.
I have done it and now my boss have made a new request. He wants me to make that stuff(the device) connect to a remote database(preferably Ora... | If you do not have ARM versions of the Oracle library, you're totally out of luck there and would need to get one (perhaps there is a free driver?) or implement the wire protocol manually.
|
1,809,227 | 1,809,259 | How to get the first n elements of a std::map | Since there is no .resize() member function in C++ std::map I was wondering, how one can get a std::map with at most n elements.
The obvious solution is to create a loop from 0 to n and use the nth iterator as the first parameter for std::erase().
I was wondering if there is any solution that does not need the loop (at... | You can use std::advance( iter, numberofsteps ) for that.
|
1,809,364 | 1,812,498 | User-mode synchronization library for C++ | Does anyone know of a Windows user-mode thread synchronization library for C++ (utilizing spin locks / atomic operations)? I only need mutexes (~critical sections), but condition variables would be a plus.
| Thank you for the answers. Turns out that basing my expectations about the size of a threading library on boost was a bad idea, and writing your own synchronization code based on InterlockedExchange is dead-simple. My spinlock code achieves a performance of about 20% better than Win32 critical sections (and I mean real... |
1,809,381 | 1,809,481 | Break on NaNs or infs | It is often hard to find the origin of a NaN, since it can happen at any step of a computation and propagate itself.
So is it possible to make a C++ program halt when a computation returns NaN or inf? The best in my opinion would be to have a crash with a nice error message:
Foo: NaN encoutered at Foo.c:624
Is somethi... | You can't do it in a completely portable way, but many platforms provide C APIs that allow you to access the floating point status control register(s).
Specifically, you want to unmask the overflow and invalid floating-point exceptions, which will cause the processor to signal an exception when arithmetic in your progr... |
1,809,679 | 1,809,753 | Difference between implementing a class inside a .h file or in a .cpp file | I was wondering which are the differences between declaring and implementing a class solely in a header file, compared with normal approach in which you protype class in the header and implement in effective .cpp file.
To explain better what I'm talking about I mean differences between normal approach:
// File class.h
... | The main practical difference is that if the member function definitions are in the body of the header, then of course they are compiled once for each translation unit which includes that header. When your project contains a few hundred or thousand source files, and the class in question is fairly widely used, this mig... |
1,809,810 | 1,810,315 | QT creating my form objects, how to access that form? | I am trying to change a certain text box message. It will display my output.
This is what I have in my TCPClient()
#include "form2.h"....string recvMSG = "random";
QString s1 = QString::fromLocal8Bit(recvMSG.c_str());
182:: Form2::changeOutput(s1);
within my form2.h I have:
...
void Form2::changeOutput(QStr... | If I understood the problem correctly, I think the proper "Qt-way" would be to have the TCP client send a signal when it receives a message, and then in your main function connect that signal to the changeOutputs slot.
|
1,809,816 | 1,809,885 | How to use std::transform with templates | I am struggling to find out why I can't get transform to work with a template class.
Here's a simplified version of the template class :
template<typename T>
class base
{
public :
base() : all_() {}
~base() {}
public:
bool add(T t)
{
typename vector<T>::iterator itr
= lower_bound(all_.begin(), all_... | Try:
transform( toAdd.begin(), toAdd.end(),
back_inserter(results),
bind1st( mem_fun(&base<int>::add), &test ) );
The problem isn't the template, it's that bind1st relies on extra support to work (see http://www.sgi.com/tech/stl/AdaptableBinaryFunction.html). AFAIK it can't ever operate on plain ol... |
1,809,937 | 1,810,007 | How to structure a Genetic Algorithm class hierarchy? | I'm doing some work with Genetic Algorithms and want to write my own GA classes. Since a GA can have different ways of doing selection, mutation, cross-over, generating an initial population, calculating fitness, and terminating the algorithm, I need a way to plug in different combinations of these. My initial approach... | I would approach the GA as a collaboration of many objects, rather than one big Class encapsulating the whole algorithm. Basically, you could have an abstract class for every big
point of variation, and concrete classes for every implementation choice you want. You then combine the concrete classes you want into many v... |
1,809,950 | 1,809,970 | Is the following C++ casting correct? | I read a few posts on the usage of static and dynamic casts specifically from When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?
I have a doubt regarding the usage of cast in the following manner. Can someone verify the below mentioned code:-
This is upward casting in inheritance hierarchy
... | If Base is really a base class of Derived, there's absolutely no need for any cast, meaning that static_cast in the above code is absolutely superfluous. It doesn't achieve anything a mere assignment wouldn't do implicitly. Moreover, in upcasts (from derived to base), dynamic_cast is absolutely equivalent to static_cas... |
1,810,163 | 1,810,320 | C++ implicit copy constructor for a class that contains other objects | I know that the compiler sometimes provides a default copy constructor if you don't implement yourself. I am confused about what exactly this constructor does. If I have a class that contains other objects, none of which have a declared copy constructor, what will the behavior be? For example, a class like this:
class ... | Foo f1;
Foo f2(f1);
Yes this will do what you expect it to:
The f2 copy constructor Foo::Foo(Foo const&) is called.
This copy constructs its base class and then each member (recursively)
If you define a class like this:
class X: public Y
{
private:
int m_a;
char* m_b;
Z m_c;
};
... |
1,810,277 | 1,810,297 | My http server in c++ is not sending all files back correctly | I'm working on an HTTP server in c++, and right now it works for requests of text files, but when trying to get a jpeg or something, only part of the file gets sent. The problem seems to be that when I use fgets(buffer, 2000, returned_file) it seems to increment the file position indicator much more than it actually en... | Don't use fgets() to read binary data that needs to survive bit-for-bit. You don't want record-separator translation, and some systems may assume it's text if you read it that way. For that matter, newlines and record-separators are completely meaningless so the fgets()` function of scanning for them is at best a confu... |
1,810,343 | 1,810,488 | Is a wide character string literal starting with L like L"Hello World" guaranteed to be encoded in Unicode? | I've recently tried to get the full picture about what steps it takes to create platform independent C++ applications that support unicode. A thing that is confusing to me is that most howtos and stuff equalize the character encoding (i.e. ANSI or Unicode) and the character type (char or wchar_t). As I've learned so fa... | The L symbol in front of a string literal simply means that each character in the string will be stored as a wchar_t. But this doesn't necessarily imply Unicode. For example, you could use a wide character string to encode GB 18030, a character set used in China which is similar to Unicode. The C++03 standard doesn'... |
1,810,372 | 1,812,575 | C++ serialization library that supports partial serialization? | Are there any good existing C++ serialization libraries that support partial serialization?
By "partial serialization" I mean that I might want to save the values of 3 specific members, and later be able to apply that saved copy to a different instance. I'd only update those 3 members and leave the others intact.
This... | You're clearly not looking for serialization here.
Serialization is about saving an object and then recreating it from the stream of bytes. Think video games saves or the session context for a webserver.
Here what you need is messaging. Google's FlatBuffers is nice for that. Specify a message that will contain every si... |
1,810,485 | 1,810,501 | Am I incorrectly using atoi? | I was having some trouble with my parsing function so I put some cout statements to tell me the value of certain variables during runtime, and I believe that atoi is incorrectly converting characters.
heres a short snippet of my code thats acting strangely:
c = data_file.get();
if (data_index == 50)
cout << "50 dig... | atoi takes a string, i.e. a null terminated array of chars, not a pointer to a single char so this is incorrect and will get you unpredictable results.
char c;
//...
/* ... */ atoi(&c) /* ... */
Also, atoi doesn't provide any way to detect errors, so prefer strtol and similar functions.
E.g.
char *endptr;
char c[2] = ... |
1,810,529 | 1,810,540 | Memorable 32-bit value as a constant | I am looking for a memorable 32-bit value to be used as a constant. If possible, it should be somewhat funny too.
So far, I have come up with these two:
0xcafebabe
0xdeaddad
Can you please suggest some other too?
Thank you.
| A comprehensive list of magic constants is here:
Hexspeak
Magic Number
And see the links therein.
|
1,810,566 | 1,810,571 | c++ templated friend class | I'm trying to write an implementation of a 2-3-4 tree in c++. I'm it's been a while since I've used templates, and I'm getting some errors. Here's my extremely basic code framework:
node.h:
#ifndef TTFNODE_H
#define TTFNODE_H
template <class T>
class TreeNode
{
private:
... | You just need to declare it as a template when you use the friend keyword. You're using incorrect syntax for a friend declaration in your code. What you want to write is:
template <class U> friend class TwoThreeFourTree;
|
1,810,622 | 1,810,630 | C++ returning nested class with template on base class problem | I am trying to create a list object, with the iterator class nested inside to understand how it works.
In some method, I am trying to return an iterator object but it doesn't work.
I created an example to show the problem :
// CLASS A
template <class T>
class A
{
public:
class B;
A(){}
};
// CLASS ... | You need typename:
typename A<T>::B
To indicate to the compiler that A<T>::B is a type. Here's a good explanation why.
What B is depends on what A<T> is, this is called dependency. Any time you are getting a type out of a class or struct, and it's dependent on a template, you'll need to use typename.
|
1,810,657 | 1,810,704 | C++: Iterating through a vector of vectors | Hey there! I'm doing this project and right now I'm trying to:
create some of objects and store them in vectors, which get stored in another vector V
iterate through the vectors inside V
iterate through the objects inside the individual vectors
Anyway, I was just searching the web and I came accross the stl for_each ... | What's the prototype for A::getV()?
I'm only speculating but if A::getV() doesn't return a reference then it can explain the "Vector iterators are incompatible" error message.
Indeed A->getV().begin() and A->getV().end() would be two iterators over different vectors: each A->getV() invocation returning a different cop... |
1,810,953 | 1,810,964 | Is there an easy way to tell if a File stream has opened a directory instead of a file? | I'm making an HTTP server and when I get the path of the file they request I open it with the following:
returned_file = fopen(path, "r");
this (contrary to what I would think) succeeds even if the path is a directory. Is there an easy way to check if the returned_file stream is a directory instead of a file?
| Can you check if the path points to a directory before you call fopen?
|
1,810,991 | 1,811,038 | Recommendations for naming C# classes/methods intended to replace existing APIs | Long explanation aside, I have a situation where I need to basically re-implement a .NET framework class in order to extend the behavior in a manner that is not compatible with an inheritance or composition/delegation strategy. The question is not a matter of whether the course of action I am to take is what you would ... | Here are the ways I've seen in the .NET Framework itself:
Call it something slightly different, but don't use any specific suffix. For example, System.TimeZoneInfo was introduced to supersede System.TimeZone.
Put it in another namespace. For example, the WPF Button is in System.Windows instead of System.Windows.Forms.... |
1,811,118 | 1,811,185 | Super basic declaring new templated class objects question | I know this is probably a first year question, but I'm having some problems with templates and I haven't found a suitable answer yet. I'm trying to instantiate a new templated class like so:
TreeNode <T>newLeft = new TreeNode(root->data[0]);
Which is refering to a constructor which looks like:
template <class T>
//par... | You forgot T in new, and pointers:
TreeNode<T>* newRoot;
newRoot = new TreeNode<T>(root->data[1]);
Note, you'll need to fix your usage of pointers everywhere, not just here. Remember that this isn't Java or C#, and a variable of type TreeNode<T> is not a reference to T - it is a T. And to build a tree, you need refere... |
1,811,358 | 1,811,378 | help overloading << and >> to display two values | This may be a novice question, but I can't figure it out by inspecting the book I have.
The class's constructor initializes two doubles, and I want the following code to output those two doubles with <<.
Complex x( 3.3, 1.1 );
cout << "x: " << x;
After this I need to overload >> to accept two doubles into these.
This... | operator<< :
std::cout is an std::ostream object, so you have to overload operator<< for ostream, which takes std::complex<double> as an argument, assuming you use std::complex<double> from the standard header complex. Since you shouldn't make internal changes to standard containers and classes, make it standalone.
#in... |
1,811,447 | 1,811,471 | populating int array that is a member variable | I'm using C++ to create a tile map for a game. My problem is, I want to populate a multidimensional array of ints in the Map constructor, but it's not working properly. Here's my code in "Map.h" (irrelevant code has been removed).
class Map {
private:
int mapArray[15][20];
};
And my code from Map.cpp
Map... | You can't use array initializers like that in a class constructor. Members can only be initialized by using the initializer list. Your best bet is to load this data from a file, or to declare the array as static.
class Map
{
private:
static int mapArray[15][20];
/* ... */
};
Then define storage for the static array in... |
1,811,516 | 1,811,973 | Integrating Erlang with C++ | What interfaces exist to tie Erlang with C++?
|
Native implemented functions: available in the latest Erlang/OTP version, allows you to implement any of your functions in C.
Port drivers: you can link a C code to the Erlang VM, and access it using port_command.
C Nodes: With the ei library you can mimic a VM and talk to your Erlang VMs using the Erlang distribution... |
1,811,788 | 1,812,017 | C++: How to Perform Deep Cloning of Generic Type | To keep the long story short, I am unable to use the container from the STL and boost library and have to create my own.
My own generic container is coded in VC++6 and I need to know how to manually allocate memory for generic types before storing it in my own container. The generic types are all struct that can conta... | First and for all: if you want to clone any object, all it's aggregates should be cloned, too. This means that every struct/class involved in the cloning action should implement cloning behavior.
Then: the stl uses so called value-semantics: containers will always contain their elements 'by value'. Copying means crea... |
1,812,152 | 1,812,200 | C stdlib .h's on C++ and malloc/realloc | I was really bothered by the inclusion of C stdlib functions on the global namespace and ended up writing things like ::snprintf or ::errno or struct ::stat, etc, to differentiate from some of my own functions in the enclosing namespace where those c stdlib functions were used.
Then I discovered that there is a way to ... | For your first question, it depends on which headers you are trying to include. Most of the C headers are available in the c(lib) form in the existing version of C++. A few aren't, and may be added in C++0x. So if you tried to include any of those, you might have gotten that error.
Second, all the headers of this form ... |
1,812,160 | 1,812,163 | C++: Compile Error for Template Assignment Operator Overloading | I keep getting the error "use of class template requires template argument list" when I compile the following code in VC++6. What is wrong with it?
template <class T>
class StdVector{
public:
StdVector & operator=(const StdVector &v);
};
template <typename T>
StdVector & StdVector<T>... | You need to put the template parameter in the return type:
template <typename T>
StdVector<T> & StdVector<T>::operator=(const StdVector &v)
{
return *this;
}
|
1,812,259 | 1,812,292 | C++ : Potential Issues with Custom Coded Generic Container? | I am unable to use the STL and boost library and I have to write my own container in C++. The following code compiles without error in VC++6.
I have not actually tested the code but is concerned whether this generic container will work with both primitive and non primitive types (like class). Will there be any potentia... | This default constructs the new objects and assigns them (or would, if the Begin() returned T* and not const T*, see dribeas' answer), it might be more efficient if you used raw storage and constructed the new objects in place. Also as GetSize(), Begin() and End() aren't const they can't be called on the parameter v.
t... |
1,812,295 | 1,812,324 | Capture bitstream into string | I'll need to capture my bitstream into a string and keep concatenating the string. However, I'm not really sure how it's to be done. Any ideas?
#include <bitset>
#include <iostream>
#include <string>
using namespace std;
int main ()
{
int i;
char data[30];
int int_arr[30];
printf("\nEnter the Data Bits t... | std::stringstream?
#include <sstream>
std::string WriteSomethingToStringStream()
{
std::ostringstream oss;
oss << "foo?\n";
oss << "bar!\n";
return oss.str();
}
|
1,812,395 | 1,812,588 | Designing a virtual machine with JIT | I'm developing a scripting language that compiles for its own virtual machine, a simple one that has instructions to work with some kind of data like points, vectors, floats and so on.. the memory cell is represented in this way:
struct memory_cell
{
u32 id;
u8 type;
union
{
u8 b; /* boolean */... | Before writing a JIT ("Just-in-time") compiler, you should at least consider how you would write a "Way-ahead-of-time" compiler.
That is, given a program consisting of instructions for your VM, how would you produce a program consisting of x86 (or whatever) instructions, that does the same as the original program? How ... |
1,812,683 | 1,812,878 | SSL reverse proxy for legacy application binary transfers on sockets | I'm struggling to find a reverse proxy http->https like for binary sockets.
There is a Pound server which offers this kind of SSL tunneling but just for the http protocol.
Basically I work on 4'th layer TCP/IP with binary data. Between flex/AIR client and c++ server.
I can wrap sockets in C++ without problems, but this... | Maybe you're looking for Stunnel?
|
1,812,782 | 1,814,476 | C++: Compilation Errors for Custom Coded Generic Container? | The following is based on the code that I posted on this thread. Aside from the obvious bugs, I get the following compilation errors? Any idea why?
The odd thing is that this only occurs for the template class. If I add another non template class to the same .h and .cpp file of the template class and try to instantiate... | If I am not mistaken, templates cannot be exported. That is why I am getting the linker error in Scenario C.
|
1,812,815 | 1,813,093 | How to use magnet links in LibTorrent lib | How to use magnet links in LibTorrent C/C++ lib?
I need an simple example of working with it - Something like I give him a link he gives me a file.
| While I haven't used it personally, but you could check http://www.qbittorrent.org/, it uses libtorrent internally and it is under the GPL-2 license.
|
1,812,990 | 1,812,998 | Incrementing in C++ - When to use x++ or ++x? | I'm currently learning C++ and I've learned about the incrementation a while ago.
I know that you can use "++x" to make the incrementation before and "x++" to do it after.
Still, I really don't know when to use either of the two... I've never really used "++x" and things always worked fine so far - so, when should I us... | It's not a question of preference, but of logic.
x++ increments the value of variable x after processing the current statement.
++x increments the value of variable x before processing the current statement.
So just decide on the logic you write.
x += ++i will increment i and add i+1 to x.
x += i++ will add i to x, the... |
1,813,259 | 1,813,264 | Generate random chars and integers in C++ | How do I generate random chars and integers within a method so that the method can be called in main() and so that the method generates random chars and integers together. I do not want a method that genrates chars and another methods that generates integers.
| You can write a method like (assuming you want only lower case English characters, you can extend it):
void generate(char& ranChar, int& ranNmber)
{
//Generate a random number in the range 0-25 and add the ascii value 'a'
ranChar = rand() % 26 + 'a';
ranNumber = rand();
}
int main()
{
//Seed the random number... |
1,813,552 | 1,813,560 | Tell C++ console to wait | What is the method to tell the console to wait for x seconds. Is there a built in method or must I make one.
| It's platform specific. On Linux/UNIX, or other POSIX-compliant operating systems, you can use the sleep function, which takes a parameter in seconds. On Windows you can use Sleep, which takes a parameter in milliseconds.
|
1,813,647 | 1,813,662 | Simplest way to read registry key value to std::string? | What's the simplest way to read a registry key value to std::String?
Say I've got :
HKEY_LOCAL_MACHINE / SOFTWARE / MyApp / value1 = "some text"
HKEY_LOCAL_MACHINE / SOFTWARE / MyApp / value2 = "some more text"
How do I get those values to std::string in a fast way ?
| I have some very old code, but it should give you a good idea:
/**
* @param location The location of the registry key. For example "Software\\Bethesda Softworks\\Morrowind"
* @param name the name of the registry key, for example "Installed Path"
* @return the value of the key or an empty string if an error occured.
*/
... |
1,813,671 | 1,813,720 | Problem with protected fields in base class in c++ | I have a base class, say BassClass, with some fields, which I made them protected, and some pure virtual functions. Then the derived class, say DerivedClass, like class DerivedClass : public BassClass. Shouldn't DerivedClass inherit the protected fields from BassClass? When I tried to compile the DerivedClass, the comp... | If BassClass (sic) and DerivedClass are templates, and the BassClass member you want to access from DerivedClass isn't specified as a dependent name, it will not be visible.
E.g.
template <typename T> class BaseClass {
protected:
int value;
};
template <typename T> class DerivedClass : public BaseClass<T> {
publi... |
1,813,758 | 1,813,940 | CMFCRibbonEdit does not get focus | I just added a CMFCRibbonEdit to my ribbon but it seems it does not get the focus.
It appears disabled.
I even copy/pasted an implementation of the creation of this control from a Microsoft sample but I get the same behaviour.
Any idea on what I may be doing wrong or forgetting to do ?
| Have you added an update handler for that ribbon element ID?
Check the RibbonGadgets and MSOffice2007Demo samples in the MFC Feature Pack to see how they do it.
The RibbonGadgets one will show you the exact code you need to use in order to add an element of the specified type to your ribbon.
|
1,813,860 | 1,813,901 | Is there any significant difference between nesting a while loop in a while loop and nesting an if-else loop in a while loop? (C++) | EDIT: I forgot to add the loop part of the second code.
Looking at the two code styles
while(some_loop_cont_val)
{
while(pre_x is not done)
{
//do action pre_x
}
//do action x
}
and
while(some_loop_cont_val)
{
if(pre_x is not done)
{
//do action pre_x
}
else
{
... |
break statement from within an inner loop would not allow you to exit outer one. So you'll miss some useful functionality introduced by break/continue statements. Compare:
while(some_loop_cont_val) {
if(some_det) {
break;
}
}
//"break" takes you here
and
while(some_loop_cont_val){
while(some_det... |
1,813,897 | 1,813,903 | Is there a utility to indent C++ programs | I am trying to use "indent" program to indent C++ programs. But it does not seem to work fine. It is messing up the indentation much more.
It is a Class file. Can you please suggest the right options for it or another program that works?
Thanks
| Try Artistic Style:
Artistic Style is a source code indenter, formatter, and beautifier for the C, C++, C# and Java programming languages.
|
1,813,917 | 1,814,660 | How do you include an external library in your own project for C++? | So I'm quite new to C++, I've basically been coding it all semester for a class. For our final project, we made an email client in C++ with .NET, and to do all the email sending and receiving, we went with using the POCO email client.
Now, basically in order to use the POCO library, I've compiled it and done a number o... | If you're using Visual Studio, there should be some info in the MSDN Help Center. Here is the online version for VS2008 from the MSDN library.
|
1,814,189 | 1,814,194 | How to change string into QString? | What is the most basic way to do it?
| If by string you mean std::string you can do it with this method:
QString QString::fromStdString(const std::string & str)
std::string str = "Hello world";
QString qstr = QString::fromStdString(str);
If by string you mean Ascii encoded const char * then you can use this method:
QString QString::fromAscii(const char * ... |
1,814,241 | 1,814,251 | Trying to get signals to work in my QT. I need some advice and help | So I have in my main function:
string s = "\nWelcome to Rawr\n";
const QString output(s);
**emit output(output); <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Getting an error here**
I have set up a Signal in QT Desginer named: output(const QString &s)
My receiver for the signal is my "Form"... in my form.h i have:
The slot i... | Since you declared a variable output, the name output refers to that variable in the local scope. The compiler doesn't know that in output(output) you want one output to refer to the variable and the other output to refer to the slot/method.
Use a different name for the local variable to avoid this collision.
|
1,814,269 | 1,814,367 | c++ Mysql C API mysql_real_escape_string | I'm building a class wrapper for the mysql c api, specifically at the moment for mysql_real_escape_string and I don't think I'm doing it quite right.
this is what I have for the function:
std::string Database::EscapeString(const char *pStr)
{
char *tStr = new char[strlen(pStr)*2+1];
mysql_real_escape_string(m_s... | Looks good to me. I suspect your database problem is elsewhere.
There's an easy way to check: temporarily replace Database::EscapeString with a dummy function, i.e.
std::string Database::EscapeString(const char *pStr) {return string(pStr);}
Then see if you get the same errors.
Edit:
Not knowing exactly what the error... |
1,814,377 | 2,008,561 | Reverse Engineering an Apple Kext - Reconstructing the Class | Greetings!
I am currently attempting to extend the functionality of the Magic Mouse. To do this, I am hoping to write a kext that intercepts events from the multitouch driver, AppleMultitouchDriver.kext, interprets them, and either dispatches new events or forwards the actual event. This approach is similar to the appr... | I've managed to find what I needed. Now all it will take is time and effort. :)
|
1,814,531 | 1,816,913 | Absolute beginners guide to working with audio in C/C++? | I've always been curious about audio conversion software, but I have never seen a proper explanation from a beginners point of view as to how to write a simple program that converts for example, a mp3 file to a wav. I'm not asking about any of the complex algorithms involved, just a small example using a simple library... | Thanks everyone for the responses! I sort of cobbled them together to successfully make a small utility that converts a AIFF/WAV/etc file to an mp3 file. There seems to be some interest in this question, so here it what I did, step by step:
Step 1:
Download and install the libsndfile library as suggested by James Morri... |
1,814,548 | 1,814,618 | boost::system::(...)_category defined but not used | I'm currently getting compiler warnings that resemble the warning I gave in the question title. Warnings such as....
warning: 'boost::system::generic_category' defined but not used
warning: 'boost::system::posix_category' defined but not used
warning: 'boost::system::errno_ecat' defined but not used
warning: 'boost::sy... | This relates to the error_code library in the Boost.System library. Boost error_codes contain two attributes: values and categories. In order to make error_codes extensible so that library users can design their own error categories, the boost designers needed some way to represent a unique error code category. A si... |
1,814,756 | 1,814,800 | parsing argc and argv in c++ | I want to learn more C++... Usually I make a for loop to parse argv, and I wind up with a bunch a C-style strings. I want to do something similar in C++, but preferably without reading from /proc/whatever. At first, I tried to convert the C-style string to a C++ style string without results... The frustrating bit is ... | I'm not sure I fully understand the question.
The cleanest method I know to get all the arguments in an easy to use array is:
std::vector<std::string> v(argv, argv + argc);
But if you're looking for a way to really parse the data, check out Boost.ProgramOptions.
|
1,814,772 | 1,814,778 | C++ header file convention | I am working on a small game using C++, and I used Eclipse CDT's class generator. It created a .h file with the class definitions and a .cpp file that included body-less methods for said class.
So if I followed the template, I'd have a .cpp file filled with the methods declarations, and a .cpp file with method bodies.... | You don't have to include the .cpp file. Including the .h file is all it takes. .h means header, ie, all it should have is function / object definitions. The actual implementations go in the .cpp file of the same name. The linker will deal with straightening it out for you.
The header file contains declarations (al... |
1,814,844 | 1,989,207 | Using tui option of GDB | I am currently working with NS-2(A network Simulator) and I wanted to use the tui option of gdb such that i can view the course code while debugging. (Just like Visual studio)
As of now the source window is blank when i run "gdb -tui" . However I can see the file when i do a "list" in gdb, but I am not able to make it... | While I'm not sure about the GDB TUI, if you're familiar with vi then be sure to check out CGDB. It is a TUI front-end to GDB using vi-like key bindings.
To set a break point in CGDB, just hit escape (of course), navigate to the line you want to break on, then hit the space bar!
|
1,814,993 | 1,814,999 | Does my C++ compiler optimize my code? | While using modern C++ compilers (including MSVC, GCC, ICC), how can I say if it has:
parallelized the code
vectorized the loops (or used other specific processor instructions)
unrolled the loops
detected tail-recursion
performed RVO (return-value optimization)
or optimized in some other way
without diving into the a... | The only way you can really tell is if you examine the assembler output (which you appear to have discounted). Other than that, you could read the doco to see what types of optimization each level of your compiler provides.
But, in all honesty, if you don't trust that the optimization levels of your compiler are doing ... |
1,814,997 | 1,815,019 | Convert from hexadecimal to binary C++ | This kind of builds up on Already asked question...
However here, say, I'm given a hexadecimal input which could be a max of '0xFFFF'
I'll need it converted to binary, so that I'd end up with a max of 16 bits.
I was wondering if using 'bitset' it'd be quite simple.. Any ideas?
EDIT :
After getting answers, improvised p... | Supposing by "hexadecimal input" you mean a string containing a hexadecimal number, then this would work:
const char* const str = "0xFFFF";
std::istringstream iss(str);
int i;
iss >> std::hex >> i;
if(!iss && !iss.eof()) throw "dammit!";
std::cout << '"' << str << "\": " << i << "(0x" << std::hex << i << ")\n";
|
1,815,075 | 1,815,084 | Problem with iterators for std::list of boost::shared_ptr | I'm having a problem with the following code:
#include <list>
#include <boost/shared_ptr.hpp>
#include "Protocol/IMessage.hpp"
template <typename HeaderType>
class Connection {
public:
typedef IMessage<HeaderType> MessageType;
typedef boost::shared_ptr<MessageType> MessagePointer;
template <type... | std::list<MessagePointer> in your code is a dependent type (i.e. it depends on the type of a template argument). Consequently, you need to use typename to state that ::iterator is expected to be a type for all potential instantiations (as it can be a value for some of them, if they are specialized). So:
typename std::l... |
1,815,136 | 1,815,144 | Never ending Win32 Message loop | I have the following code:
MSG mssg;
// run till completed
while (true) {
// is there a message to process?
while(PeekMessage( &mssg, NULL, 0, 0, PM_REMOVE)) {
// dispatch the message
TranslateMessage(&mssg);
DispatchMessage(&mssg);
}
if(mssg.message == WM_QUIT){
break;... | A typical game loop has this form:
MSG mssg;
bool notdone = true;
// run till completed
while ( notdone ) {
// is there a message to process?
if (PeekMessage( &mssg, NULL, 0, 0, PM_REMOVE)) {
if (mssg.message == WM_QUIT) notdone = false;
// dispatch the message
Tr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.