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 |
|---|---|---|---|---|
6,039,867 | 6,039,876 | Error in printing out the data obtained in pointer to character strings | I am trying to call an interface function and print out the resulting values. The function prototype contains pointers to character string as arguments. When I print out the resulting values I receive some strange symbols. Is my below approach correct?
int interfacecall(char *a, char *b ...);
char * a= "Testdata";
cha... | Your printf is not that safe. It should be :
printf("%s", b); //corrected - safe!
In C++, you can also use std::cout as:
std::cout << b; //its simpler - must include<iostream>
Make sure that b is a null-terminated c-string, otherwise it wil print garbage and may crash your program. Null-terminated string means it m... |
6,040,122 | 6,040,146 | using find_if in set | In my main.cpp:
using namespace std;
#include <cstdlib>
#include <iostream>
#include <set>
#include <string>
#include <cstring>
#include <sstream>
#include <algorithm>
class findme
{
public:
bool operator()(const std::string& s) {
return s == "tom";
}
};
int main(int argc, char *argv[])
{
set<st... | std::find_if returns an iterator to the found element (or one-past-the-end if no element matched the predicate):
std::set<std::string>::iterator it =
std::find_if(myset.begin(), myset.end(), findme());
if (it != myset.end())
{
// etc.
|
6,040,225 | 6,041,816 | Translating many meshes - HLSL | Okay forgive me if this is at all vague, but I've been up all night trying to catch up with some coding.
I have a reasonably large and defined terrain with minimal optimisations in place and I have just started to introduce predefined meshes (.X objects) which come with materials and textures. Previously I was working ... | As someone said earlier you should be doing the translation on your vertex shader, if you have a worldViewProjection matrix constant within your shader, then you need to multiply the vertex position by that matrix and return the transformed position on your output before you move onto your pixel shader.
Make sure the w... |
6,040,271 | 6,040,289 | Constant pointer variables in C++ |
Possible Duplicate:
What is the difference between const int*, const int * const, and int const *?
I know two variations of pointer variables in C++.
Say I have
mystruct{
int num;
}
Variation 1:
const mystruct* m1; means the member variables in m1 can not be altered, for instance, m1->num = 2 would produce an e... | Variant 3 is exactly the same as variant 1. The const applies to whatever is to the left of it. If there is nothing (first variant), it applies to the thing that is right of it. Also, you're missing one variation.
const int* pi1; // varyable pointer to constant int
int const* pi2; // again - varyable pointer to constan... |
6,040,382 | 6,040,414 | how to get rid of - "warning: converting to non-pointer type 'char' from NULL"? | I have this block of code:
int myFunc( std::string &value )
{
char buffer[fileSize];
....
buffer[bytesRead] = NULL;
value = buffer;
return 0;
}
The line - buffer[bytes] = NULL is giving me a warning: converting to non-pointer type 'char' from NULL. How do I get rid of this warning?
| Don't use NULL? It's generally reserved for pointers, and you don't have a pointer, only a simple char. Just use \0 (null-terminator) or a simple 0.
|
6,040,384 | 6,040,431 | Implicit conversion of vector<shared_ptr<Foo> > to vector<shared_ptr<const Foo> > | According to this page you can implicitly convert shared_ptr<Foo> to shared_ptr<const Foo>. That makes good sense.
However, I run into an error when I try to convert a std::vector containing shared_ptr<Foo> to one containing shared_ptr<const Foo>.
Is there a good way to achieve this conversion?
| No: std::vector<shared_ptr<Foo> > and std::vector<shared_ptr<const Foo> > are different types, so you can't treat an object of one as an object of the other type.
If you really need a std::vector<shared_ptr<const Foo> >, you can easily create one with shared_ptrs to the same elements as the original:
std::vector<share... |
6,040,665 | 6,068,432 | How does a Qt custom widget notify ScrollArea parent about change of view | I'm writing an image viewer as a custom Qt widget (see: https://github.com/dov/Qviv) and I now got stuck on the question of how to make my widget notify a parent QScrollArea of changes in the view port, and thus to tell it to move the scrollbars. E.g. if the image viewer changes the zoom factor as the result of a keypr... | I finally downloaded the Qt sources and investigated how QTextEdit does it. What I found is that QTextEdit inherits the QAbstractScrollArea on its own, and thus the scroll area and the scrollbars are part of the widget. This is different from Gtk, which uses a higher level of abstraction, through its GtkAdjustment's th... |
6,040,761 | 6,040,797 | Passing a pointer to a structure | Hi
I have a function A ( xy * abc) that takes a pointer to a structure.
typedef struct
{
int a;
char * b;
} xy;
typedef struct
{
xy c;
xy d;
} uv;
uv *sha;
If i need to call the function A for c and d using uv how should I pass the argument? I am calling function A by using this:
A (&sha->c);
A (&sha->d);
Is this... | If uv is a struct, and not a pointer to struct, you need to do A(&uv.c), but in your case, uv is a struct type, not an actual struct, you need to have a variable of type uv:
uv somevar;
A(&somevar.c);
|
6,040,853 | 6,040,987 | Getting multiple errors creating a model in Qt | I'm creating a class in Qt. But everything was working until I built a tablemodel class. I'm now getting the errors "expected ( before * token" and "Creator does not name a type".
What's the problem? It seems very cryptic.
#ifndef OPENMODEL_H
#define OPENMODEL_H
#include <QAbstractTableModel>
#include <QString>
#inclu... | You have a cyclic reference between these header-files. openmodel.h includes creator.h and the other way around. So, when creator.cpp (I presume there is such a file) gets compiled, it will include openmodel.h before the class Creator is declared (remember that #include means that the contents of the file will be paste... |
6,041,094 | 6,041,149 | cgi with lighttpd on Ubuntu | Suppose I have an executable file with .o or .a extension. How can I run it on lightTPD? Should I allow cgi or just fast-cgi will be enough?
I am using ubuntu 9.04 and if this make any difference executable file supporting V8-engine.
the problem is I dont see any modcgi in my /etc/lighttpdlighttpd.conf, could just be w... | I don't think you can run .o or .a files via CGI (nor can you run them normally), because they're not linked yet. But, if you have a fully compiled and linked ELF binary, you could name it with the .cgi extension, and set cgi.assign to ".cgi" => "".
|
6,041,100 | 6,041,145 | Is it possible to implement the __super macro? | Please tell me if there is a way to manually implement the Microsoft specific __super macro...
| class Base{
public:
void func(){
// something
}
};
class Derived : public Base{
public:
void func(){
Base::func(); // just use the base class name
}
};
Though I assume that's not what you want and you want a generic access for every class? I don't know of a direct solution, but you can always typedef ... |
6,041,350 | 6,041,417 | Is there any easy way to play a mp3 file |
Possible Duplicate:
How to play mp3 file in c++?
Hi,
I am doing a project which demands the functions of mp3 player. There is no need of giant, full pledged solution, all I want is just "play","pause","stop". I found some libs which are libmad,lame.But, I can't find any example for them. If anybody shed a light on t... | There is a Phonon component in Qt 4.
Not sure about Window, but in Ubuntu it can play pretty much every format whose codec is available.
You might look into Qt Docs at http://doc.qt.nokia.com/latest/phonon-overview.html
|
6,041,459 | 6,043,086 | C++ vector of arrays | Why does this work:
std::pair<int, int> p = {1,2};
std::vector<std::pair<int, int>> vp = { {1,2}, {3,4} };
But this doesn't?
std::array<int, 2> a = {1,2}; // still ok
std::vector<std::array<int, 2>> va = { {1,2}, {3,4} };
Using g++ 4.5.1 with -std=c++0x, the second line fails with:
error: could not convert ‘{{1, 2},... | Unfortunately, std::array does not have an initializer list constructor. Indeed, it has no user-defined constructor whatsoever -- this "feature" is a leftover from C++03 where omitting all user-defined constructors was the only way to enable the C-style brace initialization. It is IMHO a defect in the current standard.... |
6,041,570 | 6,041,588 | C++ : How to pass function pointer, stored in a local variable, as a template parameter | using namespace std;
float test1(float i){
return i * i;
}
int test2(int i){
return i+9;
}
struct Wrapper{
typedef void (*wrapper_type)(int);
template<class R, class A>
void wrap(string name,R (*fn) (A) ){
wrapper_type f_ = &Wrapper::wrapper1<R,A,fn>;
// in the real program, f_ ... | Template parameters must be known at compile time, so you'll have to redesign your code taking this into account.
Edit: for your updated question use Boost function_traits.
template<R (*fn) (A)>
void wrap(string name){
wrapper_type f_ = &Wrapper::wrapper1<function_traits<A>::result_type, function_traits<A>::arg1_ty... |
6,041,582 | 6,042,386 | WriteFile() blocks (writing from C++ client to C# server via named pipe ) | I am stuck here, please help.
I have a C# named pipe server, the pipe is created by:
new NamedPipeServerStream(pipeName, PipeDirection.InOut, numThreads);
In C++ I created the client like this:
m_hPipe = CreateFile(
strPipeName, // Pipe name
GENERIC_READ | GENERIC_WRITE, // Read ... | FILE_FLAG_OVERLAPPED enables asynchronous I/O. It does not automatically make any operations asynchronous, non-blocking, or buffered.
You need to use the 5th parameter of WriteFile – pass in an OVERLAPPED structure, either with an event to set on completion, or associate the file handle with an I/O Completion Port.
|
6,041,615 | 6,042,473 | C++ finding the GUI thread from a list of thread IDs | I am building an application program in C++ which uses Windows hooks to control third-party programs. The program I am making is a tutorial program to show how to use these third-party programs. I can find the process ID of the third-party program that I want to hook into and I can then query this process ID to find a ... | How about finding the main window of the app, and then using GetWindowThreadProcessId to get the thread ID of that?
If you don't already know the main window, can try finding it using FindWindow() if you know the window name and classname, or EnumWindows() to enumerate over all the top-level windows on the desktop, and... |
6,041,666 | 6,041,681 | Packing multiple variable into one string | A stream of chars are sent out to a communication device. For readability purposes, i wrote inidividual configurations as variables:
unsigned char a1;
unsigned char a2;
unsigned char a3;
unsigned char a4;
unsigned char a5;
std::string a6;
unsigned char a7;
unsigned char a8;
What is the best way to pack it into a vari... | A packed structure, rather than just a structure would be more appropriate.
EDIT: Ofcourse, you should not use string as a part of your structure, It skipped me while answering but as others have pointed out. You should conver string to character array using str.c_str()); and then store the same in the packed struct... |
6,041,840 | 6,041,904 | Proper way to login into facebook from a c++ application? | Users can register on my webpage using either a new usr/pass or their facebook credentials. But I also have a standalone desktop c++ application. What would be the proper way to let them log-in in the desktop application using facebook credentials?
| You're supposed to embed a web browser to make a request to https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=http://www.facebook.com/connect/login_success.html&response_type=token and listen for the URI to change to get your token.
More on http://developers.facebook.com/docs/reference/dialogs/oa... |
6,041,979 | 6,042,054 | BadImageFormatException error when using C++ .dll function for C#? | I am having trouble with using P/Invoke for C#. Here is the function (written in C++) that I am trying to call from the .dll:
string
BeatTracker::getName() const
{
return "Tempo and Beat Tracker";
}
And here is my code for trying to call this function:
[DllImport("qm-vamp-plugins.dll",EntryPoint="BeatTracker")]
pu... | This exception can be caused by a mismath between the .NET runtime proc architecture used and the imported dll one.
More precisely:
Do you use a 64bit Windows? The runtime will, by default, run in 64bit. If your C++ library was compiled targeting 32bit, you will get a BadFormatException upon library loading. The Same g... |
6,042,034 | 6,042,246 | Transforming n binary calls to one n-ary call in C++? | We have a helper function in our codebase to concatenate two (Windows) path strings:
CString AppendPath(CString const& part1, CString const& part2);
It is often used in this way:
const CString filePath = AppendPath(AppendPath(AppendPath(base, toplevel), sub1), filename);
This is rather acceptable, but it got me wonde... | Without C++0x, it's also possible to use chaining (I don't recommend overloading the comma operator, the syntax gets weird).
The syntax is somewhat different, but very close:
CString const Path = AppendPath(base)(toplevel)(sub1)(filename);
This is done simply by creating a temporary object that will perform the catena... |
6,042,228 | 6,042,367 | How to fix this warning : conversion to 'unsigned char' from 'int' may alter its value | I am getting this warning while compiling the library.
warning: conversion to 'unsigned char' from 'int' may alter its value
This prevents us from using compiler option -Werror.
Can anyone suggest the way to fix this warning ???
| Shoot in the dark:
Use a static_cast to instruct the compiler that you know that the conversion will not result into a truncation: int i; unsigned char c = static_cast<unsigned char>(i);
If you are not so sure, check out boost::numeric_cast.
It's equivalent to static_cast in this case, but much more explicit (easier to... |
6,042,433 | 6,042,798 | Is there a slicing problem with this inheritance structure? | I am doing some game design, and decided that I want a data centric model... one "game data" object which gets passed from subsystem to subsystem, and knows itself how it should be drawn, how physics should operate on itself, how inputs from the user will affect it etc.
So I started out with "Listener"ish objects like ... | Slicing occurs when you pass by value. If your base types are abstract (have pure virtual functions), slicing cannot occur; the compiler will complain instead. (Slicing occurs when an object is copied, but only the base class is copied.)
As long as you're not trying to use value semantics (pass by value, etc.), your ... |
6,042,490 | 6,042,683 | Constructing "array" of noncopyable objects | I have a class that's inhenerently non-copyable (a thread, so there's no copy semantics that make sense), and I want to have a largeish 'array' of these, identically constructed with a non-default constructor. Note that the array is fixed size.
I can only use the default constructor with C++ arrays, unless I initialise... | A vector of smart pointers, with each instance dynamically
allocated, is definitely the simplest way. Otherwise (and I'd
only do this if absolutely necessary), you can more or less
emulate what std::vector does internally. Something along the
lines of:
union
{
double just_to_ensure_alignment;
unsigned char da... |
6,042,659 | 6,043,206 | What's causing this QT 4.7.3 error? | I have a program which compiles just fine in OpenSuse 11.2 with QT version 4.5. However, when I compiled the same program using OpenSuse 11.4 with QT 4.7.3, I'm getting this error message:
"This file was generated using the moc from 4.7.3. It cannot be used with the include files from this version of Qt. The moc ha... | This error occurs because you are using a project that was compiled on one version of Qt.
The main reason for this is that Qt uses moc tool that creates glue code for signal slot handling and other stuff.
Moc does this by parsing the header files to find definitions like Q_OBJECT, signal:, slot:, etc.
This code is comp... |
6,042,819 | 6,043,283 | Linking to OpenCV under MacOSX | I'm trying to compile a C++/OpenCV Code in MacOS X Snow Leopard which was originally under Linux. I installed OpenCV 2.2 using MacPorts, but I cannot use something like this anymore:
g++ -o Localization Localization.o DataReader.o Kalman.o -libopencv_core -libopencv_highgui -L/usr/local/lib/
I'm getting this error:
ld... | The link flag should be -lopencv_core not -libopencv_core. The latter will look for a file called libibopencv_core.{dylib,a} instead of libopencv_core.{dylib,a}. The same for opencv_highgui.
|
6,042,862 | 6,043,882 | Puzzle: To escape the check of typeid | I formed a nice interview question by chance. :)
template<typename T>
bool foo (T obj)
{
if(typeid(T) == typeid(obj))
return false;
return true; // <-- execute this
}
You have to call (only above mentioned) foo() in such a way that it returns true. Conditions are,
Cannot edit or overload foo() or typeid
No p... | int main ()
{
typedef char C[1];
foo<C>(0); // returns true;
}
Refer this question to know the explanation of this answer and root of this question.
|
6,042,948 | 6,043,049 | Confusing between object in Heap and Stack memory | A method;
Sterling operator+(const Sterling& o) const {
return Sterling(*this) += o;
}
Does this line "Sterling(*this) += o" create a new Object in stack memory? If true, how can it return an object in the stack to outside the method?
Can I do like this:
Sterling operator+(const St... | Sterling operator+(const Sterling& o) const {
return Sterling(*this) += o;
}
Creates object on the stack, but you don't actually return this object, you return a copy of it. This function does:
create a temp object
call operator+= of the temp object with o
return copy of the result - note the Sterling operator... |
6,043,344 | 6,043,445 | Do I have to rewrite a function for it to work in QT? | I have two functions one that saves content of my array to a textfile and a function that reads the same into the array. Everything was written in VS and now I'm trying to make a GUI to my app.
My save to file function works like a charm but when I try to read that file in QT with my read function nothing happens. Do I... | Generally, no, you shouldn't need to do anything differently to make correct code work as part of a Qt application. I haven't studied your code in detail, but it seems fine at a glance at least.
However, there are some things that will be different. First of all, control in graphical programs is usually inside out from... |
6,043,382 | 6,125,947 | Jenkins and cFix unit testing (C++) | Has anyone used cFix (Visual Assert) along with Jenkins CI?
How to set it up? How can i execute C++ Project Tests (Testt Framework cFix{isualAssert) via Jenkins?
Any pointers!
Thanks
| I wrote a small program to convert cFix output to XML. I used the simplest Junit XML format recognized by jenkins for my program output.
<?xml version="1.0" encoding="UTF-8"?>
<testsuite>
<testcase name="TestIsOpen" classname="A.B">
<error type="error">Details</error>
</testcase>
<testcase name="TestAcce... |
6,043,531 | 6,051,244 | Can't compile Qt with Microsoft compiler | I want to build Qt (4.7.3) with the VS2010 compiler but ran into a problem while configuring.
I’m using the VS-command-shell.
My configure-command looks like this:
configure.exe -platform win32-msvc2010 -no-webkit -no-phonon -no-phonon-backend -no-script -no-scripttools -no-multimedia -no-qt3support
This happens like ... | It's so stupid I have to answer it myself.
The reason was that I didn't have the C++ compiler installed.
I always thought I did, but only used VS2010 for C# development up until now.
Don't down-rate b/c I wasted some people's time! When was the last time such a stupid thing happened to you during coding?
|
6,043,689 | 6,043,754 | c++ what is "pointer = new type" as opposed to "pointer = new type []"? | In many tutorials, the first code samples about dynamic memory start along the lines of:
int * pointer;
pointer = new int; // version 1
//OR
pointer = new int [20]; // version 2
They always proceed to explain how the second version works, but totally avoid talking about the first version.
What I want to know... | This is a typical error in C and C++ for beginners. The first sentence, creates a space for holding just an int. The second one creates a space for holding 20 of those ints. In both cases, however, it assigns the address of the beginning of the dynamically-reserved area to the pointer variable.
To add to the confusion,... |
6,043,858 | 6,044,935 | Set ostringstream to append automatically | How do I append data for ostringstream objects? Assumingly:
ostringstream oss;
oss << '0x11';
How do I set it to perform oss << 0x22 from the last known element automatically? I read through that I need to set some flag but how do I do it?
edit: Sorry for being very very vague about the question. Prolly the coffee is ... | It is unspecified what the app flag does when passed to an
ostringstream constructor. This flag is only relevant to
ofstream. On the other hand, ostringstream is a stream,
and as such, data are always inserted after the previously
inserted data, provided no seek has occured in the meantime. This is, after all, the de... |
6,043,970 | 6,044,158 | boost::mpl::vector - getting to a type's base-offset | Is it possible to get at the offset of a mpl::vector after performing a mpl::find<seq,type> on it ?
Put differently I want to do the compile time equavalent of:
#include <vector>
#include <algorithm>
#include <iostream>
int main()
{
typedef std::vector<int> v_type;
v_type v_int(3);
v_int[0] = 1;
v_int[1] = 2;... | If what you're looking for is a kind of indexOf feature, I guess the example from Boost.MPL doc concerning find will do the trick:
typedef vector<char,int,unsigned,long,unsigned long> types;
typedef find<types,unsigned>::type iter;
BOOST_MPL_ASSERT(( is_same< deref<iter>::type, unsigned > ));
BOOST_MPL_ASSERT_RELATION... |
6,044,111 | 6,044,190 | Question about multi-inheritance in C++? | I have the following code:
#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
#define MNAME 30
class Person {
public:
char name[MNAME + 1];
};
class Student : public Person {
};
class Staff : public Person {
};
class Faculty : public Student, public Staff {
};
int _tmain(int argc, _TCH... | With regular multiple inheritance you get multiple copies of shared base classes. If you want one copy, use virtual inheritance.
Explained well in Wikipedia
class Student : public virtual Person {
};
class Staff : public virtual Person {
};
Will get you what you expected
|
6,044,151 | 6,044,247 | C++ classes - how return vector of custom type from a function? | I am having trouble setting up my functions in a class when I want to have a function return a vector of type struct which I have just defined. Compiler gives a "Use of undeclared identifier" error.
In the .h file: (no errors given)
struct workingPoint;
public:
vector<workingPoint>calculateWorkingPointCloud();
And i... | It is simply a problem of the lookup. You need to fully qualify the name, e.g.
vector<DeltaKinematics::workingPoint> DeltaKinematics::calculateWorkingPointCloud(){...
I asked a similar question about this issue here. Maybe it is also interesting for you.
|
6,044,192 | 6,044,407 | best method to find the COM port to which my embeded device got connected in my vc++ program | I want to find the COM port my device got connected in my vc++ program.
upto now i used to scan all the ports from 0 to 15 and send some command if the reply is suitable to me i can confirm that it is the port i am finding.
But this is Taking a lot of time.
anyother solution???
| The serial API does not provide for any of the sort of identification that you seem to desire so the only choice that you have is to poll he various ports. If the device is a USB device, you may be able to garnish clues from the friendly name associated with that device (see How do I get the friendly name of a COM por... |
6,044,261 | 6,044,756 | Can g++ check the throw specifiers? | Two questions about this :
Is there a way to force g++ to ignore the throw specifiers ?
(for example, as I remember, Visual Studio ignores the throw specifiers, different from throw())
Is it possible to force g++ to check if the throw specifiers are correct - what I mean is to check ( and this can be done by a one-pas... |
gcc has an option -fno-enforce-eh-specs, see the documentation and check that it does what you want.
I don't remember any way to statically check exception specifications with gcc.
Note that (dynamic) exception specifications are deprecated in C++0X which add a noexcept exception specification replacing the empty exc... |
6,044,392 | 6,044,712 | Inline asm in c++ in vs __asm | char name[25];
int generated_int;
for(int i = 0; i<sizeof(name); i++)
{
name[i] = (char)0;
}
cout << "Name: ";
cin >> name;
int nameLen = strlen(name);
__asm
{
pusha;
mov esi, &name //I got error here, I cant use "&". How to move name address to esi?
mov ecx, nameLen
mov ebx, 45
start:
mov... | You seem to be looking for the lea instruction, which loads the effective address of some symbol into a register. The following instruction will store the address of name in esi.
lea esi, name
|
6,044,527 | 6,044,590 | Downcast in a diamond hierarchy | Why static_cast cannot downcast from a virtual base ?
struct A {};
struct B : public virtual A {};
struct C : public virtual A {};
struct D : public B, public C {};
int main()
{
D d;
A& a = d;
D* p = static_cast<D*>(&a); //error
}
g++ 4.5 says:
error: cannot convert from base ‘A’ to derived type ‘D’ via vi... | Because if the object was actually of type E (derived from D), the location of A subobject relative to D subobject could be different than if the object is actually D.
It actually already happens if you consider instead casting from A to C. When you allocate C, it has to contain instance of A and it lives at some speci... |
6,044,543 | 6,044,599 | save pixel array to jpeg image file c++ | i have a pixel array containing the values from 0 to 255 ...
i have passed it to my c++ function ...
this pixel array i want to save it to jpeg image file...
how to do it with correct encoding ??
i have converted the array to binary string
and saved it into the file in the below code but it just saves an empty image ... | From your description it looks like you have YUV-data that you need to convert to jpeg. Correct? Imagemagick is a very powerful tool that can handle this.
From wikipedias entry on YUV:
Y' values are conventionally shifted and scaled to the range [16, 235] rather than using the full range of [0, 255]. This confusing pra... |
6,044,771 | 6,064,704 | gSOAP deletes referenced values in objects after request finished | i'm using gSOAP to request information from a SOAP webservice
the soap webservice returns an object.
i do the request in a calls called: "dataconnector"
in dataconnector i can output all values for the returned object
but outside that all the referenced values in the object are null.
i did some searching and apperantly... | This is not a specific gSOAP or web-services question. When the variable response gets out of scope, it deallocates the memory it has used and in my opinion you should really not unlink the memory gSOAP has reserved. If you unlink it, you are responsible for freeing it!
The way to go is to make a copy of the objects re... |
6,045,266 | 6,045,345 | Dynamic 2D Array Creation Runtime Error | I'm trying to create a multidimentional int array with the following function code:
int ** createIntMatrix(unsigned int rows, unsigned int cols)
{
int ** matrix;
unsigned int i,j;
matrix = (int **) calloc(cols, sizeof(int *));
for(i = 0; i < cols; i++)
matrix[i] = (int *) calloc(rows, sizeof(int));
... | for(i = 0; i < cols; i++)
for(j = 0; i < rows; i++)
matrix[i][j] = 0;
note the inside for loop, it says j=0; i<rows; i++ (before Aarohi Johal's edit)
Next you do not have to set the memory manually to 0, as calloc does it for you.
In C++, you should use new and delete .
In the code segment
matrix = (int ... |
6,045,273 | 6,045,604 | boost-mpl comparing iterators | Gosh, when working with mpl libraries, figuring out syntax is a hit-and-miss exerience (previous question ). What is the correct syntax to compare two mpl itterators -i.e., the it != v.end() test ?
template<typename T>
struct get_type_ordinal
{
rbl_type_ordinal_type operator()()
{
typedef typename boost::mpl:... | try boost::is_same<>, that should do the trick.
|
6,045,321 | 6,045,555 | "Proper" use of multiple inheritance in C++ | One day I read in the book (probably Head First Java, not sure). It says that "there's only one good usage of multiple inheritance used in a C++ library."
(There was a name of the library, but I forgot it) What library properly used multiple inheritance, and how multiple inheritance used?
| One thing that you can use multiple inheritance for is for mixins. You can use mixins to add functionality to a class that is defined in another class (the class that you're mixing in).
A link specifically about mixins in C++: MixinsForCeePlusPlus
|
6,045,692 | 6,045,863 | looking for a quick way to populate a std::list | I have a Visual Studio 2008 C++ program where I'm populating a std::list with the addresses of a memory pool.
I have an implementation that works using std::generate and it's not bad, but it can be a bit slow with large pools of small allocation blocks.
/// fill the allocation list with the memory addresses of each b... | Your code passes over the list twice instead of once.
So it might help to define an iterator that returns the addresses, so that everything is done in a single pass:
struct blocks {
void *current;
size_t increment;
blocks(void* start, size_t size = 0) : current(start), increment(size) {}
bool operator... |
6,045,809 | 6,045,967 | Link error "undefined reference to `__gxx_personality_v0'" and g++ |
Possible Duplicate:
Undefined Symbol ___gxx_personality_v0 on link
I have a problem with the following program.
// fkt.cpp
#include "fkt.h"
int add2(int a, int b)
{
return a+b;
}
And the header:
// fkt.h
int add2(int a, int b);
Now I compile this with:
g++ -c fkt.cpp
Now I run nm and get:
00000000 T _Z6ad... | If g++ still gives error Try using:
g++ file.c -lstdc++
Look at this post: What is __gxx_personality_v0 for?
Make sure -lstdc++ is at the end of the command. If you place it at the beginning (i.e. before file.c), you still can get this same error.
|
6,046,175 | 6,046,295 | How to convert WinProc message codes to text? | I have defined a winproc message handler like so
WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
Is there a nice utility function to convert uMsg codes to text? I need it for debugging.
I can not seem to find it with google on msdn. I could code it myself but it should exists already...
Thanks.
| Sounds like a job for Spy++ if its mearly debugging you want, however, if you need it at a more code level, then you might need to use CPP defines to create the logging eg:
#define WNDMSG(x) case x: LogWndMessage(#x);
|
6,046,188 | 6,046,317 | Is STLPort's string implementation using reference counting? | Is STLPort implemented string via reference counting mechanism?
| According to the source, no.
|
6,046,218 | 6,046,266 | How do I build a vector of system::drawing::rectangle | How do I build a vector of system::drawing::rectangle in c++?
I tried vecor of std but got an error message that mixed types are not supported. What can I do?
| You can use the List<T> class.
|
6,046,228 | 6,046,291 | C++ Variadic Macros in Boost.Fusion? | So, according to this answer, C++ doesn't support variadic macros, and the C++ standard doesn't mention variadic macros anywhere. I know that C99 introduced variadic macros with __VA_ARGS__, and certain C++ compilers (like GCC) even provide extensions to allow this in C++, but the fact remains that variadic macros sim... | BOOST_FUSION_ADAPT_STRUCT(
demo::employee,
(std::string, name)
(int, age))
This is a single macro which takes two arguments:
Argument 1: demo::employee
Argument 2: (std::string, name)(int, age)
Argument 2 is concatenated with a string to form another macro invocation which also takes 2 parameters:
BOOST_FU... |
6,046,335 | 6,046,917 | C++ qt control cursor position in console | I'm writing a Qt console application. I need functions to control cursor position in console(gnome-terminal)(move it back, forward, on the nex-previous line).
I have tried to seek this functions in QtCore, but unsuccessful. Does Qt have at all such tools?
| AFAIK, Qt does not have any functions for abstracting the console in such a manner.
You can probably use another library rather easily, as it is unlikely to interfere with Qt much.
|
6,046,445 | 6,047,266 | MFC Dialog Data Exchange (DDX) comma instead point as decimal | To initialize the controls in my dialogs and to gather user input, I'm using DDX. How can I change the program to display float numbers with a comma instead of a point (best without changing the locale)?
The program has the "C" locale set, if I change the locale, I have to take care on every atof, sprintf operation (th... | This is a locale specific thing you probably will need to handle the changing of it using locale.
Note that DDX is for initializing control objects so that your control variable member declarations stay in sync with the values you chose in your resource file or whatever you did when initializing the dialog the controls... |
6,046,464 | 6,046,527 | Do I need to use _stdcall when I export functions to be used by other languages? | In order for my function be used by other language, do I have to use _stdcall to declare my functions in C++?
| It may not be strictly necessary, but it's generally the path of least resistance. Just for example, if the other language happened to be C, you could probably use _cdecl or _fastcall. If you want to support arbitrary languages, though, _stdcall is the obvious choice.
|
6,046,610 | 6,047,160 | Wondering if the lower version of visual studio can use the dll built using higher version of visual studio? | Have both versions of visual studio installed on a machine. I am wondering if the lower version of visual studio can use the dll built using higher version of visual studio?
| In general, you cannot mix dlls compiled with different versions of the CRT in one program. Here's a link to the documentation at MSDN.
As others mentioned, it works if you keep the interface simple. Don't free memory allocated with one CRT in a DLL linked to another version of the CRT, don't pass FILE* and similar aro... |
6,046,644 | 6,046,694 | A java-like class class in cpp | I want to write a program that supports several types of commands.
In order to make it generic and easy to extend for later new commands, i want to write a class for each command (with its own handling), and call the base 'command' class with the handler function.
I know that in Java there is the class class to help wi... | You could implement a Command class with a pure virtual method.
http://www.exforsys.com/tutorials/c-plus-plus/c-pure-virtual-function-and-base-class.html
|
6,046,728 | 6,046,927 | XML parsing with PugiXML, infinite loop | this is pretty much the first C++ program that I ever made, it should display a list of xml nodes in the document. I made an exact same thing work using TinyXML, but I find Pugi much nicer and would like to continue using it.
Program code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
#... | Have you tried changing that for loop to:
for(xml_node child = parent.first_child(); child; child = child.next_sibling())
This is how the samples do it (traverse_base.cpp for example).
The important part is child = child.next_sibling(), not parent.next_sibling().
|
6,046,846 | 6,046,888 | Have a dll project, can I force it to be linked to a static library? | wondering how to generate static library. Some quick method to turn a dll output to static lib?
| In Properties, go to Configuration Properties -> General. Change 'Configuration Type' to 'Static library'. You may need to change the use of MFC (if you are using it), to static.
|
6,046,942 | 6,046,995 | MFC WinApp calls InitInstance and OnAppExit/destructor in different threads | I got problem at one of our customers environment - when I AfxGetApp()->WriteProfileString in OnAppExit (or destructor) it doesn't work. I cannot reproduce it anywhere. I tracked it down that the OnAppExit is called from different thread than InitInstance - again, this isn't true at any of my machines.
Can it be the i... | OnAppExit might get called on a different thread if you have threads in your app which generate an error and call exit. Under normal usage OnAppExit should only be called in your main thread. Here's the documentation for exit - http://msdn.microsoft.com/en-us/library/k9dcesdd.aspx.
|
6,047,255 | 6,047,343 | wrap a c++ library in c? (don't "extern c") | is it possible to wrap a c++ library into c?
how could i do this?
are there any existing tools?
(need to get access to a existing c++ library but only with C)
| You can write object-oriented code in C, so if it's an object-oriented C++ library, it's possible to wrap it in a C interface. However, doing so can be very tedious, especially if you need to support inheritance, virtual functions and such stuff.
If the C++ library employs Generic Programming (templates), it might get... |
6,047,499 | 6,050,830 | How does Very Sleepy find symbol files? | Has anyone figured out how the Very Sleepy profiler finds PDB files? It seems like it doesn't use the _NT_SYMBOL_PATH env variable.. I've had success by putting PDBs in the same directory as the executable and DLLs, but I'm trying to profile a program that uses a TON of DLLs and it's getting really painful. Isn't there... | The path to the original .pdb file is getting included in the DLL. Just don't move them.
The source code for Very Sleepy is readily available. It uses the DbgHelp API, symbolinfo.cpp source code file. The call to SymInitialize() allows a tool to specify the the search path for symbols, 2nd argument. It passes NULL,... |
6,047,527 | 6,047,564 | How to pass an std::string to glShaderSource? | I have the following code:
glShaderSource(shader, 1, (const char **)data.c_str(), NULL);
But it makes my program crash. How do I convert std::string into const char ** ?
I also tried (const char **)& but it said "requires l-value" which I don't understand. It works fine when I use this code:
const char *data = "some ... | data.c_str() returns a const char*, so do this:
const char *c_str = data.c_str();
glShaderSource(shader, 1, &c_str, NULL);
|
6,047,700 | 6,047,804 | About invalidating iterators | STL containers have the problem that iterators can be invalidated when the container changes. Would it be possible for the container to announce that it has changed by adding a call has_changed()?
It is common to query empty() before certain operations. If the container set a bool on operations that would affect it... | The (approximate) way fail-fast iterators work in Java is that the container increments a counter each time it changes. The iterators copy this counter on creation, and increment it each time the container is changed through them. If the iterator detects a mismatch, it throws an exception.
C++ has the exciting property... |
6,047,840 | 6,048,021 | Does an allocator.construct loop equal std::uninitialized_copy? | In this context T is a certain type and allocator is an allocator object for that type. By default it is std::allocator<T> but this is not necessarily true.
I have a chunk of memory acquired by allocator.allocate(n). I also have a container con of T objects (say, a std::vector<T>). I want to initialize that chunk of m... | According to this explanations They should do the same, as allocator::construct is said to construct the object and std::uninitialized... also constructs the objects. But I do not know, what exactly the standard says and what freedom you have, when implementing your own allocator::construct.
EDIT: Ok, the C++03 standar... |
6,047,857 | 6,047,921 | Generic/template programming best practices: To limit types, or not to limit types | That is my question. I'm just curious what the consensus is on limiting the types that can be passed in to a generic function or class. I thought I had read at some point, that if you're doing generic programming, it was generally better to leave things open instead of trying to close them down (don't recall the sour... | Always leave it as open as possible - but make sure to
document the required interface and behaviour for valid types to use with your generic code.
use a type's interface characteristics (traits) to determine whether to allow/disallow it. Don't base your decision on the type name.
produce reasonable diagnosis if
some... |
6,047,985 | 6,049,100 | QGraphicsItem drawing problem | I am working on a small Tower Defense game in order to learn Qt. I am using a QGraphicsScene to hold all the object of the game. To make them move, I am not using the Animation framework but I'm calling the advance() method along with a QTimer.
I'd like to make my projectiles explode when they hit an enemy. The problem... | Say cnt is 3.
You are drawing an ellipse with
painter->drawEllipse(-3,-3,6,6)
This would require a boundingRect with at least a width and height of 9.
Also the boundingRect is specified using the internal item coordinate system. You are drawing from (-3,-3) to (6,6) which is outside of the boundingRect.
|
6,048,280 | 6,048,347 | Distinguishing Pass-by-Reference and Pass-by-Value | How are pass-by-reference functions typically distinguished from pass-by-value functions? For example:
template <typename T>
void sort(std::vector<T>& source); // Sorts source.
// Versus...
template <typename T>
std::vector<T> sort(std::vector<T> source); // Returns a sorted copy of source.
These two functions are ... | Can't you just give them different names? I would name the functional version sorted, for example.
Just because you can overload functions (or function templates in this case) does not mean you have to.
By the way, you can implement the "functional version" in terms of the "imperative version":
template <typename T>
vo... |
6,048,488 | 6,048,826 | default viewer on Windows mobile 6.x | How can I find out if a default viewer exist for a file type (PDF for example)? I am planing to use ShellExecute to open a PDF file that I have downloaded from server, but I need to know if the device is capable of viewing the file before I attempt to download it.
P.S. This is a Visual C++ 2008 mobile project.
Thank Yo... | Same as with the desktop. For example, for PDFs you'd look in the registry (with RegOpenKeyEx and its relatives) for an extension association:
[HKEY_CLASSES_ROOT\.pdf]
If that exists, the default value will be the name of another key in HKEY_CLASSES_ROOT, which you'd open to
[HKEY_CLASSES_ROOT\{class name}\Shell\Open\... |
6,048,823 | 6,048,908 | Create new thread in windows with cygwin | I am using netbeans. I installed cygwin and use it for c++ programming in netbeans. I want to create a thread. I searched lots of sites. But I couldn't find anything suitable for my condition(C++ and windows(as OS) and not visual C++).
| Cygwin implements the POSIX Threads API, aka pthreads.
|
6,049,038 | 6,049,109 | Please suggest infrastructure for passing data between C# and C++ | I'm using P/invoke to interoperate between C# and C++ in this project. I'd like to pass data structures that are symmetrically defined. What's the best infrastructure to use? Could protocol buffers be useful here?
| I would suggest to use C++/CLI since you can use the same header files / definition files in both worlds. One of the main goals for developing C++ CLI was to fill the gap between the managed and the unamanaged world. This article gives you even more advantages.
In the MSDN there is a nice description how C++cli works a... |
6,049,198 | 6,049,844 | TRACE Macro Error When Attempting to Pass String Variable | My calls to the TRACE macro are resulting in an error when I attempt to pass a string to it like so:
TRACE(_T("PrintAppMsgTrace: %s"), _T(GetCmdIdStr( pMsg[APP_MSG_CODE_OFFSET] )));
This is the error I get in the console window output:
_CrtDbgReport: String too long or IO Error
Here is the prototype for GetCmdIdStr:... | The _T() macro is used on string literals. It expands to either just the original string literal, if you're compiling ANSI, or the string literal with an L prefix if you're compiling UNICODE. You can't apply it to the return value of a function.
If possible, the simplest thing to do would be to change the GetCmdIdStr... |
6,049,226 | 6,050,195 | How to know if anybody has subscribed to a particular event I'm going to fire? | I got 2 events in my ActiveX/ATL library
dispinterface _IMyEvents
{
properties:
methods:
[id(1), helpstring("method OnReceiveData")] HRESULT OnReceiveData([in] long BytesReceived, [in, out] VARIANT_BOOL * Proceed);
[id(2), helpstring("method OnReceiveDataEx")] HRESULT OnReceiveDataEx([in] long BytesRece... | If you need to make this distinction, ATL or no, you will need two interfaces. One for OnReceiveData and one for OnReceiveDataEx. A given event sink has to implement all the methods of an event interface, even if it only cares about one.
|
6,049,412 | 6,049,488 | Pointer, Class and void* in C++ | I get a code for Fibonacci Heap. This code uses the follow function to compare two keys:
int
cmp(void *x, void *y)
{
int a, b;
a = (int)x;
b = (int)y;
if (a < b)
return -1;
if (a == b)
return 0;
return 1;
}
This works because the KEY is currently a INT number.
I would like to adap... | Change the following lines
a = (Node*)x;
b = (Node*)y;
to
a = *( (Node*) x);
// type cast from void* to Node* and then fetch the contents by dereferencing the pointer.
b = *( (Node*) y);
You were merely type casting the pointers from void* to Node* and trying to assign the pointer to a variable of type Node.
|
6,049,436 | 6,049,555 | Any hit for dereferencing std::tr1:shared_ptr vs. dereferencing a naked pointer? | I realize that there is a (Sometimes significant) performance hit for creating, assigning, copying, and destroying a std::tr1::shared_ptr or boost::shared_ptr (due to the reference counting mechanisms). Is it correct that once constructed, accessing the pointer wrapped by a shared_ptr has no performance penalty?
in ot... | In an optimized build without debugging support, there shouldn't be any overhead. You can find out by taking a look at the implementation you are using. Chances are, its operator-> overload just returns the pointer to the pointed-to object and its operator* overload just dereferences this pointer.
(This is what the V... |
6,049,563 | 6,050,129 | With "-fno-exceptions", what happens with "new T"? | I was wondering, will new T still throw bad_alloc if I compile my program using the -fno-exceptions option to disable exception handling?
Or will the compiler (GCC and clang support that option) implicitly transform the use of new T to new (nothrow) T?
| I can't give a definitive answer to all the perks around -fno-exceptions, just the observations on a 32 bit linux machine, gcc 4.5.1 - bad_alloc is thrown with and without -fno-exceptions
[21:38:35 1 ~/tmp] $ cat bad_alloc.cpp
int main()
{
char* c = new char[4000000000U];
}
[21:38:58 1 ~/tmp] $ g++ bad_alloc.cpp
[... |
6,050,275 | 6,050,579 | How to implement client-server udp multicast in one program? | I have written a server and a client both as separate apps. They communicate through UDP Multicast (becouse I need that everyone who joins the group can read & write messages). Now I have two windows, but my aim is to create one simple chat program, but I don't know how to listen and send at the same time. Do I need to... | You can use one or two sockets, it all depends on whether you wish to bind to a particular network adapter and whether you wish to use unicast & broadcast packets. It is often easier to manage one for sending and one for receiving.
To listen to sent multicast packets on the same host check the IP_MULTICAST_LOOP socket... |
6,050,298 | 6,051,000 | How do I count the number of files in a directory using boost::filesystem? | I am given a boost::filesystem::path. Is there a fast way to get the number of files in the directory pointed to by the path?
| Here's one-liner in Standard C++:
#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/lambda/bind.hpp>
int main()
{
using namespace boost::filesystem;
using namespace boost::lambda;
path the_path( "/home/myhome" );
int cnt = std::count_if(
directory_iterator(the_path),
... |
6,050,441 | 6,051,740 | Why does this constructor overload resolve incorrectly? | This is my (stripped) class and instantiation of one object:
template <typename T, typename Allocator = std::allocator<T> >
class Carray {
typedef typename Allocator::size_type size_type;
// ...
explicit Carray(size_type n, const T& value, const Allocator& alloc = Allocator()) {
// ...
}
... | This should work with all iterator types (including pointers) and the current standard.
#include <iostream>
#include <iterator>
#include <vector>
// uses sfinae to determine if the passed in type is indeed an iterator
template <typename T>
struct is_iterator_impl
{
typedef char yes[1];
typedef char no[2];
templ... |
6,050,605 | 6,050,671 | C++ time_t to std::string for a specific time zone | In a Linux environment working in C++, I need to convert a time_t value into an English string representation for various time zones. e.g. 1305750080 -> "2011-05-18 13:21:20 PST". I am able to use gmtime() or localtime() combined with strftime() to generate strings for GMT and my local timezone. How would I select an a... | I think you can do this with tzset.
setenv("TZ", "EST5EDT", 1);
tzset();
|
6,050,800 | 6,051,063 | Learning OpenGL ES for Android game development | What's the best way to run into android game development with OpenGL ES? I tried some tutorials, but all they assume that you are already familiar with OpenGL(using c++). So, if I want to use OpenGL ES I need to learn it with c++?
| This book is pretty awesome for learning Opengl ES 2.0. It does a great job of teaching the ins and outs of opengl es in a platform agnostic POV. From that point the OpenGL/interface examples for the android sdk/ndk should get you where you need to go!
|
6,050,996 | 6,319,589 | Boost Python - Overloaded Functions with default arguments problem | I have a class that has two functions, both of which take a different set of parameters and both of which have default arguments like so:
void PlaySound(const std::string &soundName, int channel = 0, bool UseStoredPath = true);
void PlaySound(FMOD::Sound* sound, int channel = 0);
I've found how to do default argument... | This works for me:
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(
PlaySoundFromFile, Engine::PlaySound, 1, 3)
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(
PlaySoundFromFMOD, Engine::PlaySound, 1, 2)
BOOST_PYTHON_MODULE(EngineModule)
{
class_<Engine>("Engine")
.def("PlaySound", static_cast< void(Engine::*)
... |
6,051,178 | 6,051,505 | Socket transmit data but can't receive response | I am trying to implement UpNP in C++, I found a few sources on google but none worked. I found this one working (http://www.codeproject.com/KB/IP/upnplib.aspx) but it's for .NET, so I decided to sniff the network to see what the code was doing and then do the same with sockets.
Here are the results (full size: http://i... | EDIT:
As hasturkun pointed out, my initial answer was wrong. Also, slemdx correctly diagnosed the problem: the uPnP request is going out from the wrong interface. The problem is, I am not sure how you can determine the right interface. One possibility is to use the interface containing the default gateway on the routin... |
6,051,802 | 6,051,829 | initizlize an array from a vector | It is possible to initialise a vector from an array holding elements with the same type as vector, such as
double a[] ={ somevalues };
std::vector<double> vec(a, a+dimension)
I was wondering whether the other way around is possible or not without an explicit loop? Is that possible to initialise an array from a vector... | No, it is not possible to do it at initialization, but you can use one algorithm from the STL:
std::vector<int> v = create_vector();
int array[100];
assert( v.size() >= 100 );
std::copy( v.begin(), v.begin()+100, array );
Or alternatively:
std::copy_n( v.begin(), 100, array );
The assert is to ensure that you don't g... |
6,051,872 | 6,052,091 | How to Generically Define Insertion Operators for all C++ IOStream Manipulators? | All,
Why does the following code fail to compile for 'std::endl', but it's fine for all of the other inserted types?
#include <sstream> // ostringstream
/// @brief A class that does streamed, formatted output via 'operator<<'.
class My_Stream
{
public:
/// @brief A member method that manipulates the underlying str... | Because endl is a function template:
template <class charT, class traits>
basic_ostream<charT,traits>& endl(basic_ostream<charT,traits>& os);
So the identifier itself is not a value. It only becomes a value (function pointer) when it's instantiated. But your operator<< is itself a template, and there is no type inform... |
6,052,044 | 6,052,114 | Static and Dynamic Libraries | I am using SFML, and I am building an application in Code::Blocks and mingw32. I have have added the SFML libraries (sfml-whatever.a) to my project, and it runs nicely.
BUT iIrc, the static libraries get 'compiled' into the executable. If this is so, then why do I have to place all the SFML DLL's next to the executabl... | In this case, the static libraries simply contain the code that interfaces to the dynamic libraries, it's not the actual library code.
|
6,052,131 | 6,052,274 | Can Virtual Classes in C++ have Member Variables? | Suppose I have a purely virtual class, can I do something like this in C++:
class ITreatable
{
public:
bool hasBeenTreated; // <- Can this be here?
virtual bool Treat() = 0;
};
And if not, how can I ensure that classes which inherit ITreatable have a member variable called hasBeenTreated? I... | Absolutely.
Strictly speaking, there is no such thing as a "virtual class". I understand that you are using the term to mean a class constructed of only data members and virtual member functions.
Consider that only functions can be virtual; if you wish for data members to be accessed polymorphically, you must do this t... |
6,052,198 | 6,052,212 | What happens if I do printf("one\0two");? | As implied by the title, what's meant to get printed if I do this in C++:
printf("one\0two");
? GCC gives me a warning when I do this, but visual studio is fine with it. Do they work differently at all? Thinking about it, I'd expect printf to stop at the first \0, but apparently the code that uses this has been workin... | You'll get:
$ a.out
one$
the \0 is a null and ends the string. No newline.
$ cat try.c
#include <stdio.h>
int
main(){
printf("one\0two");
return 0;
}
542 $ gcc try.c
try.c: In function ‘main’:
try.c:5: warning: embedded ‘\0’ in format
543 $ ./a.out
one544 $
|
6,052,455 | 6,052,499 | Return reference to sliced object (supertype) | Consider the following classes:
class Coord
{
public:
double _x, _y;
Coord(double x, double y)
{
_x = x;
_y = y;
}
};
class NamedPoint : public Coord
{
public:
int _id;
NamedPoint(int id, double x, double y) :
Coord(x,y),
_id(id)
{
}
};
I'd like to cre... | What's the point of the function? NamedPoint is implicitly convertible to Coord anyway:
void foo(Coord& c)
{
c._x = 5;
}
NamedCoord nc(0, 1, 2);
foo(nc); // c references the Coord part of nc
Anyway, your function should simply use this conversion:
const Coord& NamedPoint::coord()
{
// Bad: takes the value of ... |
6,052,486 | 6,052,984 | Non Blocking communication in MPI and MPI Wait Issue. Not all information is passed correctly | I noticed that not all my MPI_Isend/MPI_IRecv were being executed. I think it may perhaps be either the order in which I do my send and receive or the fact that the code doesn't wait until all the commands are executed. I have copied the excerpt from the code below. Could you suggest as to what I could be doing incorre... | Either rank 0 or 1 could still be sending data after this block of code has been executed (as you don't wait on the send request object). This could cause problems if you modify the data before it has finished sending.
For this particular example, perhaps MPI_Sendrecv would be useful?
|
6,052,529 | 6,052,589 | Is ->h_addr_list[0] the address I need? | I am working on implementing UpNP on C++, and I need to get the local internal IP address assigned by the router to make the sockets works. The address I need is the one that appears on routers where it shows the computers connected to the router and the local IP assigned to each computer. I am using this:
PHOSTENT ... | (Assuming winsock here, as per previous question)
You shouldn't assume that the first address is the correct one (as there may be multiple interfaces, and more than one may be active)
I'd recommend enumerating addresses using either getaddrinfo with an empty pNodeName argument, or GetAdaptersAddresses.
Both of these re... |
6,052,603 | 6,052,629 | Fast weighted random selection from very large set of values | I'm currently working on a problem that requires the random selection of an element from a set. Each of the elements has a weight(selection probability) associated with it.
My problem is that for sets with a small number of elements say 5-10, the complexity (running time) of the solution I was is acceptable, however as... | Assuming that the element weights are fixed, you can work with precomputed sums. This is like working with the cumulative probability function directly, rather than the density function.
The lookup can then be implemented as a binary search, and hence be log(N) in the number of elements.
A binary search obviously requi... |
6,052,742 | 6,053,081 | given a triangle and a segment, find third point which would create a similar triangle | I've seen similar questions asked, but I find the explanations still somewhat difficult.
I have a triangle with its 3 vertices given in (x,y). I am also given a segment of two points. I want to place a third point around the segment so that it completes a triangle with similar shape to the original triangle. This new t... | For the sake of being specific, suppose your original triangle has vertices A, B, and C. The line segment has end points D and E. Furthermore, you want DE to correspond to AB. The problem is then to find a point F such that triangle DEF is similar to triangle ABC. I hope that's what you're trying to solve, because that... |
6,052,857 | 6,054,646 | Const correctness with temporary instances | Here is the example of the "scoped lock" idiom with common mistake: no local variable is created, so lock is not in effect. This code compiles flawlessly both with VC++ 2010 and Comeau C++ online:
class Mutex
{
public:
void lock() {}
};
class ScopedLock
{
public:
ScopedLock() : m_pm(0) {}
ScopedLock(Mutex&... | You answered the question yourself.
It appears that ScopedLock(m_mutex); statement creates a local variable m_mutex of type ScopedLock
The explanation is to be found in the Standard's Section 6.8 Ambiguity Resolution:
There is an ambiguity in the grammar involving expression-statements and declarations: An expressi... |
6,052,948 | 6,053,121 | Delay outputting 0's | Can someone please tell me what is wrong here. delay has a buffer (del) with a pointer *p, but is outputting zero (0) every sample.
(Fixed Delay with 3 secs)
float delay(float *sig, float dtime, float *del, int *p, int vecsize, float sr) {
int dt;
float out;
dt = (int) (dtime*sr);// dtime = 3secs, sr=4410... | Your delay() function appears to work fine, so the error must be in how you called it. See the following example program:
#include <stdio.h>
float delay(float *sig, float dtime, float *del, int *p, int vecsize, float sr)
{
int dt;
float out;
dt = (int) (dtime*sr);// dtime = 3secs, sr=44100.0
for(int... |
6,052,969 | 6,053,187 | Most efficient way of writing byte array for streaming | I need to create a byte array that is needed to be stream to another device through UART. There are some fixed parameters that I can fill in before hand but variables such as string is dynamically sized. Right up till now, I've been doing:
unsigned char buffer[255];
unsigned char wr_head = 0;
buffer[wr_head++] = 0x01; ... | A ring buffer is a typical solution for problems like these.
I have no idea what kind of device you're on, but I'll just suppose that you're writing for some kind of embedded device. Let's assume that there's some interrupt moving data from the ring buffer to the UART. This interrupt will call getc, other code will c... |
6,052,981 | 6,065,861 | wxWidgets 2.9.1 what file replaced wxmswd.lib? | I'm currently working through the 3dbuzz.com c++ complete videos. In the video which uses a much older version of wxWidgets it says to include wxmswd.lib, this file however does not exist and must have been replaced with something else can anyone tell me what to include instead???
| Yes I ment linking the libs. After long time searching I found that the new file for wxWidgets is
wxmsw29ud_core.lib replace the 29 with 28 if your using wxWidgets with 2.8.x versions.
|
6,053,105 | 6,053,380 | OpenGL Camera Rotation Not Working | I know this is a common question (as I have read many threads on here and other forums about it) but for the life of me I can not get the camera rotation that I desire. I want the camera to be able to 'look around' and not for it to 'orbit' around a point, this point being the OpenGL origin.
I am aware that 'there is n... | Moving a 'camera' is equivalent to applying the inverse transformation to the model.
Let's say you have an object centered at point x in your world, oriented with rotation matrix R. You also have a camera at point y in your world, oriented with rotation matrix S. To get what I believe is your desired result when re... |
6,053,194 | 6,053,254 | How to use a pipe with select after forking and executing? | I'm a noob to linux programming, so please bear with me. In my application, I fork(), then execl() another binary after having setup a single pipe for reading in. After the fork and exec are OK, i do a dup2() for reading in from the stdout of the executed binary. I need my parent application to wait for output from the... | To use select() you must create a struct fd_set and populate it using the FD_ macros. In this way you will inform the function which descriptors you are interested in (note that it is common to be interested in several at once). For example:
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(your_input_fd, &rfds);
int retval = se... |
6,053,225 | 6,053,249 | Is it acceptable practice to give an object a pointer to "the world"? | I often find myself in situations where objects need to communicate between each other. For example, a button might need to talk to various textboxes. Would it be proper to simply construct each widget with a pointer to the container for all of them? Would it be better to give it a pointer to a resource container map w... | Any object should know as little as possible about things outside itself. What you are describing sounds alot like the ani-pattern often referred to as a 'God object'
You get better de-coupling if you use messages/events.
|
6,053,444 | 6,053,477 | C++ template method, changing the behavior based on the template class | I'm trying to write a c++ template method.
Below is a sample code demonstrating what I want to do within the method.
template<class T>
void method(T value) {
// This string should change based on type T
char *str = "Int" or "Float" or .. ;
...
...
std::cout << value << " is of type " << str << s... | You can specialize your template over different types. If you start with a base case:
template <class T>
void method(T value);
You can then declare different behavior for any specific value of T:
template <>
void method<int>(int value) {
// special behavior
}
And so forth. But since only the input type of your func... |
6,054,066 | 6,054,133 | Visual Studio: project is not up to date "because "AlwaysCreate" was specified"? | I've migrated a solution from VS2008 to VS2010 (SP1).
Now one of my project never finds peace in being up-to-date. Every build have the following output:
1>------ Build started: Project: PROJ_NAME, Configuration: Release Win32 ------
1>Build started 19/05/2011 7:59:27 AM.
1>InitializeBuildStatus:
1> Creating "Release\... | I had a similar problem when one of the include files listed in the project didn't actually exist. I had deleted the file, but forgot to remove it from the project.
The dependency checker then believes the project is not up to date, but the builder finds nothing to build.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.