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 |
|---|---|---|---|---|
4,008,143 | 4,026,621 | Is it possible to embed html with js into QwebKit | will I need to load java script objects into QwebKit when my application is loading
I can use setHtml with the html and the java script string formatted but its very hard to
Maintain.
My question is can I embed the html and java script as resource into Qwebkit ?
Also I don’t what that the html and the javascript be ava... | Yes, you can.
Simply add your JS/CSS to the resource file (look up the Qt docs if you don't know how) and then in your HTML simply use qrc:/file/path/or/alias.
For example, if I add JQuery to the resource file, aliased as /js/jquery, then to load it, I'd place this into my HTML file:
<script type="text/javascript" src=... |
4,008,252 | 4,008,264 | Two functions doing the exact same thing, alias? | In a derived class I have a function called evaluate() (it's a virtual in the base class). In this derived class i also have a function set_value() and hence i want get_value() as well. get_value() should return the exact same thing as evaluate()
Is there anyway to say that a call to get_value is a call to evaluate()? ... | Nope, there are no aliases in C++ you're searching for. Sure, that is the way:
double Variable::get_value() const
{
return evaluate();
}
On the other hand you could make get_value() function in a superclass and let it do the same thing if it is your design requirement.
The another advantage of implementing get_va... |
4,008,253 | 4,008,266 | How to sort C++ array in ASC and DESC mode? | I have this array:
array[0] = 18;
array[1] = -10;
array[2] = 2;
array[3] = 4;
array[4] = 6;
array[5] = -12;
array[6] = -8;
array[7] = -6;
array[8] = 4;
array[9] = 13;
how do I sort the array in asc/desc mode in C++?
| To sort an array in ascending, use:
#include <algorithm>
int main()
{
// ...
std::sort(array, array+n); // where n is the number of elements you want to sort
}
To sort it in descending, use
#include <algorithm>
#include <functional>
int main()
{
// ...
std::sort(array, array+n, std::greater<int>());
}
... |
4,008,364 | 4,078,001 | How to catch GTK focus state in gtkrc? | GTK+ 2.x has the follow states: NORMAL, PRELIGHT, ACTIVE, INSENSITIVE, SELECTED for use in GTK themes and I can do things like...
bg[NORMAL] = "#f6f6f6"
.. to change background color when in NORMAL state.
Also, I can change the background image of a button (when the mouse is over it) by changing the PRELIGHT state ima... | I don't think so. The RC file documentation doesn't even mention "focus", so I don't think it's possible to theme that in this way.
|
4,008,369 | 4,008,423 | Combining std::function objects | Say I have
double xSquared( const double )
{
return x*x;
}
...
std::function<double (double)> func = &xSquared;
...
which works fine for the (more complicated) purposes I use this structure, up till now. Now I have a function that accepts a std::function of the above form and I need to create a new std::function ... | Since you are using C++0x already, why not just use the lambda expression?
func1D divideByXMinusA(const func1D& f, double a) {
return [=](double x) { return f(x)/(x-a); };
}
Edit: Using std::bind:
func1D divideByXMinusA_withBind(const func1D& f, double a) {
using namespace std::placeholders;
return std::b... |
4,008,465 | 4,008,499 | What is the best method to compare two vectors of CString | I am trying to find the most efficient, optimized and fastest way to compare to std vectors of CString. the strings in question are case-sensitive. I have tried using the == operator for the vector container but this sometimes return false positives. I mean for instance if one vector contains elements in the order (a,b... |
if one vector contains elements in the order (a,b,c) and the other has them in the order (b,c,a) the == operator will return false even thought they share the same data.
Simply insert the data into two containers where the order does not matter and compare those:
std::vector<CString> vec1;
std::vector<CString> vec2;
... |
4,008,648 | 4,008,709 | Member function pointer | If the following from the C++ FAQ Lite is true: "a function name decays to a pointer to the function" (as an array name decays to a pointer to its first element); why do we have to include the ampersand?
typedef int (Fred::*FredMemFn)(char x, float y);
FredMemFn p = &Fred::f;
And not just:
typedef int (Fred::*FredMe... | Original answer:
because a member-function is not a function and a member-function-pointer is not a function-pointer. Therefore the rules of decay don't apply.
Also, there is function type in C++, but not member-function type. So you can use a function in places where a pointer-to-function is expected, but you can't us... |
4,008,756 | 4,009,705 | DBGHelp.dll causes load of msvcrt.dll in debug version | My application compiles with VC6 sp6, uses DBGHelp.lib to get stack information. The code is simmilar in debug and release compilations.
The problem is that when executing the debug version, DBGHelp.dll loads msvcrt.dll (the release version). msvcrtd.dll is already loaded by my debug link anyway.
So I end up having bot... | What is the problem with having both MSVCRT.LIB and MSVCRTD.DLL loaded? This is only in your Debug build anyway, I would have thought, as you seem to note in the question.
I don't think you really want to start messing around with Debug OS DLLs - that's what DBGHELP.DLL is - this is no more desirable than having your ... |
4,008,788 | 4,008,852 | Call destructor via void pointer with templates | I wrote a class to contain my objects in it.
The code is:
class objectPool
{
private:
struct itemType_{uint count; void* object;};
std::multimap< std::string, itemType_ > pool_;
public:
template<class T>
bool addItem(std::string key, T*& object)
{
std::multimap< std::string, itemType_ >::... | You correctly store a NULL into your T* reference, but that is a reference to the local variable. When you later update that local by calling new, that has no effect on the item stored in the pool.
The easier way to fix this would be to just create the object inside the addItem function using new T.
As for your other ... |
4,008,853 | 4,008,882 | Can I have functors in C? | Can I have functors in C? I mean for example in C++ I can do:
struct Rules
{
operator()(/*maybe some args*/)
{
}
};
Some (fictitious) algorithm:
int sort(iter beg, iter end, Rules);
Can I do identically in C?
| Not really. At best, you could do something like:
int sort(iter a, iter b, bool (*cmp)(iter a, iter b, void *), void *p_state)
{
...
cmp(a, b, p_state);
}
bool func(iter a, iter b, void *p_state)
{
type_t *p_type = (type_t *)p_state;
...
}
type_t state;
...
sort(a, b, func, &state);
This allows yo... |
4,008,921 | 4,019,992 | C++: Libcurl curl_easy_init() gives an access violation error and crashes the program | I'm trying to use libcurl with a program I'm making, but I'm having some problems with it. So far I've only tried the examples from libcurl's website, but they crash as soon as the program gets to the curl initialization.
My current code:
#include <iostream>
#include <curl/curl.h>
int main(int argc, char *argv[])
{
... | This is almost certainly a mismatch of DLL's. Firstly check on your PATH for any older or different versions of libcurl.dll.
I just built your snippet using VS2010 professional against this release for MSVC 7.18.0 / Win32 generic and it worked fine.
|
4,009,171 | 4,009,211 | Class variable which is object of this class | The title can be confusing, but I'm wondering is it possible to create program like this one:
class family_tree
{
private:
string name, surname;
family_tree father(); //fragile point!
public:
family_tree();
family_tree(string n, string sur");
void print();
};
What does the standard say about such ... | class family_tree
{
private:
string name, surname;
family_tree father(); //fragile point!
public:
family_tree();
family_tree(string n, string sur); // note that I removed a " here.
void print();
};
It's perfectly valid. Your fragile point is not fragile at all- you have a function that returns a f... |
4,009,172 | 4,009,260 | MFC: Convert CStringArray to float, converting just part of the value | I want to convert val.ElementAt(i) to float value :
float *d = new float[NMAX];
char *buffer = new char[128];
CStringArray val;
//adding some values to val
buffer = (LPSTR)(LPCSTR)val.ElementAt(i).GetBuffer();
d[i] = atof(buffer);
as the result in d[i] I have just part of the value(if it was 55 in d is - 5, 66... | You shouldn't be assigning buffer; it's bad code (doesn't do what you want). You could use strncpy, but instead, why not just use the CString directly:
d[i] = atof(val.ElementAt(i));
Assuming you're compiling for MBCS, this should work.
BTW, you could also use the operator[] overload, to make the code slightly cleaner... |
4,009,181 | 4,009,496 | Why can't a multidimensional array be allocated with one new call in C++? | In C++ you can easily allocate one dimensional array like this:
T *array=new T[N];
And you can delete it with one statement too:
delete[] array;
The compiler will know the magic how to deallocate the correct number of bytes.
But why can't you alloc 2-dimensional arrays like this?
T *array=new T[N,M];
Or even like th... | Your workaround of doing T *array=new T[N*M]; is the closest you can get to a true multi-dimensional array. Notice that to locate the elements in this array, you need the value of M (I believe your example is wrong, it should be T[i*M+j]) which is known only at run-time.
When you allocate a 2D array at compile-time, sa... |
4,009,250 | 4,009,493 | An algorithm to create HTML table from this row data? | I have come unstuck on a relatively (almost) trivial problem. I have a row of data that I want to display in tabular form (HTML). For some reason (possibly long day [again] behind the computer), I am not coming up with any elegant solutions (algorithms) to do this.
I have presented some sample data, and how such data w... | I assumed you have Raw data stored similar to what I have below.
Also, the level is non-unique.
<?
$rowData = array(
0=> array('index'=>1, 'Score'=>"level 1", 'amount'=>12.24),
1=> array('index'=>3, 'Score'=>"level 4", 'amount'=>14.61),
2=> array('index'=>9, 'Score'=>"level 10", 'amount'=... |
4,009,307 | 4,009,614 | Getting list of files in a folder using C | I have path to a folder for example
/myfolder
or in Windows:
C:\myfolder
and I want to get a list of all files in that folder. How shall I do so in C?
Is it different in C++ or C99?
How can I get a list of its folders?
Any help is appreciated.
| In POSIX operating systems, you can call opendir() and readdir(). In Windows you can call _findfirst() and _findnext(). With a little effort you can implement your own opendir() and readdir() as wrapper functions under Windows, so that your application code can use the same API everywhere. An example of that can be ... |
4,009,389 | 4,009,414 | calculate size of file | i have following program to calculate size of file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
string line;
ifstream myfile ("C:\\Users\\7\\Desktop\\example\\text.txt",ios::in | ios::out |ios::binary);
if (!myfile){
cout<<"cannot open file";
e... | You are subtracting the current-file-position (l) from the end-of-file position (m) to get the size. This will work as you expect if the current-file-position is at the start of the file, but as you have just read the entire contents of the file, (l) is "starting" at the end of the file.
Just use the value of (m) rathe... |
4,009,463 | 4,009,551 | Alignment of char arrays | How is STL vector usually implemented? It has a raw storage of char[] which it occasionally resizes by a certain factor and then calls placement new when an element is pushed_back (a very interesting grammatical form I should note - linguists should study such verb forms as pushed_back :)
And then there are the alignm... |
An alignment requirement for an object
of type X where sizeof(X) == n is at
least the requirement that address of
X be divisible by n or something like
that
No. The alignment requirement of a type is always a factor of its size, but need not be equal to its size. It is usually equal to the greatest of the ali... |
4,009,480 | 4,009,557 | Fast accessing pixel values of jpeg images | CompVision once again, I'm working with jpeg images in my application. Just because I'm a bit familiar with MFC and ATL, I used CImage to access pixel values.
For my needs I calculate brightness matrix for the image during initialization. Function goes like this (Image is the name of my own class, unimportant, bright ... | Use CBitmap::GetBits() to get a raw pointer to the pixel data. You can now directly party on the pixels without going through the expensive GetPixel() method. There are a number of things you need to be careful with when you do this:
You have to use CBitmap::GetPitch() to calculate the offset to the start of a line.... |
4,009,505 | 4,009,520 | Calling Parent methods and accessing private variable in a Parent class? | I'm trying to get the following code to work, but I can't find good-enough documentation on how C++ handles public vs. private inheritance to allow me to do what I want. If someone could explain why I can't access Parent::setSize(int) or Parent::size using private inheritance or Parent::size using public inheritance. ... | When you use private inheritance, all public and protected members of the base class become private in the derived class. In your example, setSize becomes private in Child, so you can't call it from main.
Also, size is already private in Parent. Once declared private, a member always remains private to the base class r... |
4,009,530 | 4,009,599 | <functional> (nested bind) problems with MSVC 2010 | I have the following code (I'm sorry for the lengthiness):
double primeValue( const func1D &func,
const double lowerBound, const double upperBound,
const double pole )
{
// check bounds
if( lowerBound >= upperBound )
throw runtime_error( "lowerBound must be smaller ... | Why not just use a lambda? All of the binding stuff has been deprecated for this kind of purpose.
double primeValue( const func1D &func,
const double lowerBound, const double upperBound,
const double pole )
{
// check bounds
if( lowerBound >= upperBound )
throw runt... |
4,009,580 | 4,010,307 | An array of structures within a structure - what's the pointer type? | I have the following declaration in a file that gets generated by a perl script ( during compilation ):
struct _gamedata
{
short res_count;
struct
{
void * resptr;
short id;
short type;
} res_table[3];
}
_gamecoderes =
{
3,
{
{ &char_resource_ID_RES_welcome_object_ID,1002, 1001 },
{ &blah_resource_ID_... | Ideally use memcpy(3), at least use type _gamedata, or define a protocol
We can consider two use cases. In what I might call the programmer-API type, serialization is an internal convenience and the record format is determined by the compiler and library. In the more formally defined and bulletproof implementation, a p... |
4,009,596 | 4,009,873 | calculate prefix sum | I have following code to accomplish prefix sum task:
#include <iostream>
#include<math.h>
using namespace std;
int Log(int n){
int count=1;
while (n!=0){
n>>=1;
count++;
}
return count;
}
int main(){
int x[16]={39,21,20,50,13,18,2,33,49,39,47,15,30,47,24,... | The quickest way to get your algorithm working: Drop the outer for(i...) loop, instead setting i to 0, and use only the inner for (j...) loop.
int main(){
...
int i=0;
for (int j=0;j<=n-1;j++){
if (j>=(powf(2,i))){
int t=powf(2,i);
x[j]=x[j]+x[j-t];
}
}
...
}
... |
4,009,737 | 4,009,762 | Library for audio resampling | In an embedded (Windows CE) C++ project, I have to resample an arbitrary sample-rate down (or up) to 44100 Hz.
Is there a free and portable C/C++ library for audio resampling?
| This page lists a bunch of options.
Formatted exert, for the records. Please check out the above link for important details and licence information:
libresample and sndfile-resample (from libsamplerate) (in the Planet CCRMA Distribution).
libsoxr, the SoX resampler library
ssrc (from Shibatch)
There is a project combi... |
4,009,752 | 4,010,818 | Boost.Spirit bug when mixing "alternates" with "optionals"? | I've only been working with Boost.Spirit (from Boost 1.44) for three days, trying to parse raw e-mail messages by way of the exact grammar in RFC2822. I thought I was starting to understand it and get somewhere, but then I ran into a problem:
#include <iostream>
#include <boost/spirit/include/qi.hpp>
namespace qi = bo... | That is because you hit a bug in Spirit's directive repeat[]. Thanks for the report, I fixed this problem in SVN (rev. [66167]) and it will be available in Boost V1.45. At the same time I would like to add your small test as a regression test to Spirit's test suite. I hope you don't mind me doing so.
|
4,009,770 | 4,012,150 | What are the key tools and steps it takes to make a 3d video game? | What are the key steps and tools it takes to creating a 3d video game.
For example, I understand that a 3d artist will create 3d models in 3d Studio Max, or Maya, but where do these models go from there?
Are the 3d models first animated by a 3d animator in 3d Studio Max/Maya?
Then do these models along with the anima... |
Are the 3d models first animated by a 3d animator in 3d Studio Max/Maya?
Yes, often. There may also be motion capture which is typically cleaned up in this software too. The models and animations may be exported into an intermediate format and then conditioned, and converted to an ingame format. The exact process va... |
4,009,838 | 4,009,890 | Is _1 part of C++0x? | I've seen two recent answers using _1 as a pure C++0x solution (no explicit mention of boost lambdas).
Is there such an animal as std::_1 I would think that having native lambdas will make such a construct redundant.
A Google code search for std::_1 brings two results from the same project so that's inconclusive.
| Yes, they are part of C++0x inside the std::placeholders namespace, from the latest draft (n3126) §20.8.10.1.3 "Placeholders":
namespace std {
namespace placeholders {
// M is the implementation-defined number of placeholders
extern unspecified _1;
extern unspecified _2;
.
.
... |
4,009,923 | 4,010,082 | c++ fatal error C1061 with large switch, metaprogramming | that's the code:
static inline void
shrinkData(const vector<Data> &data, unsigned short shrinkType){
#define CASE_N(N) \
case(N): \
ptr = MemoryManager::requestMemory(n*sizeof(ShrinkData<N>)); \
for(int i=0; i<n; i++){ \
new(ptr) ShrinkData<N>(data[i]); \
ptr+=sizeof(Shr... | According to this link there is a "feature" in compiler that allows only for limited number of loops. Never happened to me. Try to put ptr initialization and the following for loop in a block. Another solution is to create template function that covers the whole snippet, so that the macro becomes something like this:
#... |
4,010,036 | 4,014,926 | Laser light detection with OpenCV and C++ | I want to track a laser light dot(which is on a wall) with a webcam and i am using openCV to do this task. can anybody suggest me a way to do it with C++.
Thank you !
| You have three options depending on the stability of your background, and the things you want to do with the image.
You can make your image so dark that the only thing you can see is the laser-point. You can do this by closing the diaphragm and/or reducing the shutter time. Even with cheap webcams this can usually be d... |
4,010,041 | 4,010,052 | constructor with one default parameter | Suppose I have a class
class C {
C(int a=10);
};
why if I call
C c;
the contructor C(int =10) is called and if I call
C c();
the default constructor is called? How to avoid this? I want to execute only my constructor, I tried to make the default constructor private, but it doesn't work.
|
Actually, C c(); should be parsed as a function declaration. In order to explicitly invoke the default-constructor, you need to write C c = C();.
Once you define any constructor, the compiler will not provide a default-constructor for your type, so none could be called.
Since your constructor can be invoked with one ... |
4,010,069 | 4,010,953 | Problem on Mac : "Can't find a register in class BREG while reloading asm" | I tried to port some code onto Mac OS X.
The program uses the "ttmath" library, a header big-num header library.
This library works fine on both windows and linux, but when I try to compile and run it on a Mac, the following error message always shows up :
"can't find a register in class 'BREG' while reloading 'asm'".... | Thanks for DeadMG!
This problem is due to the PIC-safe option.
I added "-mdynamic-no-pic" and "-fno-pic" when I compile the code, and it works fine now :)
|
4,010,085 | 4,010,094 | RegisterClass fails with Error Code 2 | I am creating a splash for a program that I'm making but RegisterClass keeps on failing (2: The system cannot find the file specified.)
My code is this:
WNDCLASS wc = {0};
wc.lpfnWndProc = DefWindowProc;
wc.hInstance = g_hinstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
if (wc.hCursor == NULL)
{
#ifdef DEBUG
log... | There's a stray semicolon at the end of this line:
if (RegisterClass(&wc) == 0);
The error code is actually from some previous call, but the block always gets executed because of the extra semicolon.
|
4,010,097 | 4,010,126 | General use cases for C++ containers | What are the general use cases for the C++ standard library containers?
bitset
deque
list
map
multimap
multiset
priority_queue
queue
set
stack
vector
For example, a map is generally better for a paired search.
| A picture is worth a thousand words.
It's available from nolyc, the informative bot of ##C++ on Freenode, using the command "container choice" or "containerchoice". The link to this picture you receive in response is hosted at adrinael.net, which suggests we should thank Adrinael, member of Freenode's ##C++ community.... |
4,010,117 | 4,010,137 | Does C++ have good libraries to accelerate Windows Forms like software? | Suppose you have to develop a software to access customer database, let's say for example "SQL Server".
Are there good libraries to accelerate this job in order to give to my client a good UI?
For example, I could show a grid where he can select his desired customer for updating and deleting existing customers data, al... | You're looking for Qt.
With Qt Quick (sometimes known as QML) you get a system to develop GUIs with barely any C++ code - a little like XAML, but lots better as you can embed it into the traditional Qt forms.
Ars has a little article and tutorial about writing Qt software, don;t worry about the 'Ubuntu' part, Qt is ver... |
4,010,207 | 4,010,217 | fstream to const char * | What I want to do is read a file called "test.txt", and then have the contents of the file be a type const char *. How would one do this?
| #include <string>
#include <fstream>
int main()
{
std::string line,text;
std::ifstream in("test.txt");
while(std::getline(in, line))
{
text += line + "\n";
}
const char* data = text.c_str();
}
Be careful not to explicitly call delete on data
|
4,010,262 | 4,010,326 | Pure GUI apps for Win/Linux/Mac in C++ with G++ | GUI apps for Win/Linux/Mac in C/C++:
I want know how to write a "pure," "native," "API-level" apps for Windows, Linux, and Mac in C++.
I don't want "one-code run-anywhere", but native code for every OS.
Solution For Windows:
Just use Mingw/Win32 API; it's very simple and clear. That way I like programming under Window... | Mac
In the Mac case, you'll just want to fire up XCode and use Objective-C. Objective-C++ is mostly used to let you access existing C++ libraries from Objective-C.
Don't use Carbon, it's deprecated. It was only intended to make porting from Mac OS 9 easier.
Linux
This one is tough because there's really no guarantee ... |
4,010,281 | 4,010,291 | accessing protected members of superclass in C++ with templates | Why can't a C++ compiler recognize that g() and b are inherited members of Superclass as seen in this code:
template<typename T> struct Superclass {
protected:
int b;
void g() {}
};
template<typename T> struct Subclass : public Superclass<T> {
void f() {
g(); // compiler error: uncategorized
b = 3; // c... | This can be amended by pulling the names into the current scope using using:
template<typename T> struct Subclass : public Superclass<T> {
using Superclass<T>::b;
using Superclass<T>::g;
void f() {
g();
b = 3;
}
};
Or by qualifying the name via the this pointer access:
template<typename T> struct Subc... |
4,010,290 | 4,026,416 | Resizing a QGraphicsItem to take up all space in a QGraphicsView, problems when window is resized | I have a QGraphicsItem (actually, a QDeclarativeItem) and I want it to take up the entire visible space of the QGraphicsView (again, its actually the derived QDeclarativeView class) to which it was added. Normally, you can use QDeclarativeView::setResizeMode(QDeclarativeView::SizeRootObjectToView) and QDeclarativeView ... | I have solved my problems.
The problem seems to be with QML's WebView element. I switched it out for a QGraphicsProxyWidget registered from C++, with the widget set to a normal QWebView and all the problems disappear. It now behaves exactly how I expected the WebView to behave.
The downside is that I need to manually e... |
4,010,399 | 4,010,516 | Wrapping a C library in a C++ class with type conversion | I'm slowly learning to be a better C++ programmer and I'm currently debating the best way to implement a wrapper for a C library. The library is a wrapper around a compressed file format that can store tags of various types (char *, char, double, float, int32_t). The types are stored as uint8_t* and there are a bunch... | You can use templates for this, and it doesn't require a wrapper class. Just specialise a function template:
template <typename T>
T tag_to(const uint8_t *v);
template <>
char tag_to<char>(const uint8_t *v) { ... }
template <>
char* tag_to<char*>(const uint8_t *v) { ... }
template <>
uint32_t tag_to<uint32_t>(const ... |
4,010,500 | 4,015,004 | Most efficient way to modify a stream of data | I have a stream of 16 bit values, and I need to adjust the 4 least significant bits of each sample. The new values are different for each short, but repeat every X shorts - essentially tagging each short with an ID.
Are there any bit twiddling tricks to do this faster than just a for-loop?
More details
I'm converting ... | Best way to stomp those last 4 bits is your option 2:
int i;
i &= 0xFFF0;
i |= tag;
Doing this on a long would be faster if you know tag values in advance.
You can memcpy 4 shorts in one long and then do the same operations as above on 4 shorts at a time:
long l;
l &= 0xFFF0FFF0FFF0FFF0;
l |= tags;
where tags = (long... |
4,010,917 | 4,010,925 | C++: malloc : error: invalid conversion from ‘void*’ to ‘uint8_t*’ | I got this problem:
invalid conversion from ‘void*’ to ‘uint8_t*’
When doing this:
int numBytes;
uint8_t *buffer;
buffer=malloc(numBytes); //error here, why?
or must I have to put it like this?
buffer=malloc(numBytes);
Please explain this.
| You cannot implicitly cast from void * in C++ (unlike C in this respect). You could do:
buffer = static_cast<uint8_t *>(malloc(numBytes));
but really, you should just be using new/delete instead of malloc/free!
|
4,010,937 | 4,010,943 | Why does storing references (not pointers) in containers in C++ not work? | In my program I have a STL set.
set<string> myStrings;
To improve the efficiency of my code I changed it to hold, only pointers. (I don't need actual string copies to be stored.)
set<string*> myStrings;
I have read that it is a good practice to substitute pointers with references when possible. (Of course, only if th... | Containers store objects. References are not objects.
The C++11 specification clearly states (§23.2.1[container.requirements.general]/1):
Containers are objects that store other objects.
|
4,011,316 | 4,011,468 | Object Oriented c++ Question | class Sequence{
public:
Sequence();
virtual void buildTables();
protected:
string seq;
struct tables{
int a;
int b;
}thetable;
virtual void updateCount();//Uses member data seq. sorry. about the confusion.
}
void Sequence::buildTabeles(){
for (int i ... |
You don't have a constructor that initializes thetable.
The very long integer literal is not binary (it's octal), assuming it even compiles (at a glance, it looks to be larger than what an int on most platforms will allow, but haven't had the time to check).
Please consider adding a constructor so that all member var... |
4,011,348 | 4,039,186 | Qt Tray Icon Drag and Drop | Does anyone know if it is possible to use drag and drop with a tray icon using Qt?
| I've been doing some research and here is what I have come up with:
A QSystemTrayIcon cannot explicitly handle a drag/drop event. However there is a workaround based on the Spifftastic tray icon location method.
You create a uniquely colored icon
and place it as the icon for a brief
moment and take a screenshot of it.... |
4,011,442 | 4,011,573 | How does this code work? | I found this piece of C++ code on a forum that I can't fully understand. Since I don't have their library that performs matrix/vector math, I need to manually figure it out and replicate the functionality.
Calculate Euler rotation angles between 2 vectors .. we use Rodrigues formula
vector $V1 = << my first vector ... | I'm pretty sure that's psuedocode. It's definitely not C++. All the functions are pretty self explanatory.
acos() --- self explanatory
$V1 * $V2 --- dot product
(note:, that would normally be interpreted as a regular matrix multiplication, but but in the context of "float $angle = acos($V1*$V2);", it doesn't make sen... |
4,011,679 | 4,011,695 | Separating template class into multiple files yields linking issues | I have created an example below to illustrate the problem I'm having. Basically, when I separate a template class into separate .h/.cpp file, I get unresolved symbols for the constructor. Using a single file, it compiles fine. What is causing this?
fruits.cpp:
#include "apple.h"
class FruitsDB {
public:
... | Just put your template function definitions in your header files. The thing about template functions is, they aren't actually functions. They are templates of functions. So they can't be compiled out of context like normal functions. They can only be compiled if the template parameters are known. So the compiling ... |
4,011,701 | 4,011,730 | How to prevent copying a wild pointer string | My program is crash intermittently when it tries to copy a character array which is not ended by a NULL terminator('\0').
class CMenuButton {
TCHAR m_szNode[32];
CMenuButton() {
memset(m_szNode, '\0', sizeof(m_szNode));
}
};
int main() {
....
CString szTemp = ((CMenuButton*)pButton)->m_szNode; // some... | I suspect that your real problem could be that pButton is a bad pointer, so check that out first.
The only way to be 100% sure that a pointer is correct, and points to a correctly sized/allocated object is to never use pointers you didn't create, and never accept/return pointers. You would use cookies, instead, and lo... |
4,011,745 | 4,011,898 | c++ socket stream api | I'm using what looks to be a real nice API for streaming sockets found here:
http://www.pcs.cnu.edu/~dgame/sockets/socketsC++/sockets.html.
I'm having trouble accessing the IP of the connected user because its a private member of a class "Socket" that is used within another class "ServerSocket". My program looks exactl... | The Socket class you are using has a private data member:
sockaddr_in m_addr;
This contains the info of the client connected to the socket. You can get the human-readable address with:
char str[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(m_addr.sin_addr), str, INET_ADDRSTRLEN);
As for the changes you need to make, either ... |
4,011,753 | 4,011,784 | Is pointer better than instance when declaring members in class? | Option 1:
class B{//};
class A
{
public:
void Funcs();
private:
std::vector<A> vecA;
};
Option2:
class B{//};
class A
{
public:
void Funcs();
private:
std::vector<A*> vecpA;
};
Which one is better, is there any guidelines?
| This is one of those things where it depends on the specific scenario. Here is an incomplete laundry list of questions to ask yourself when deciding between these different options:
Is it polymorphic? I.e., do you know the exact type at compile-time, or could you have different runtime types that all inherit from the ... |
4,011,872 | 4,011,883 | How can I call a C++ function from C? | I have a header declaring functions that take pointers to C++ objects as parameters. The implementaton is in a seperate C++ file. How can I include this header in C and use the functions in C even though the arguments need to be C++ object pointers?
| Unfortunately, my first attempt answered the wrong question....
For the question you did ask...
You can, as someone point out, pass around void *'s. And that's what I would also recommend. As far as C is concerned, pointers to C++ objects should be totally opaque.
C++ functions can be labeled extern "C" as well if th... |
4,012,052 | 4,012,161 | Overload comparison operators for a templated class | I'm having troubles in overloading comparison operators in order to compare two pair struct in such way:
typedef pair<string, unsigned int> INDEX;
bool operator>(INDEX &v1, INDEX &v2)
{
if(v1.second == v2.second) //if integer parts are equal
{
//string that comes earlier in the dictionary should be lar... | A temporary, such as the result of element func, cannot be bound to a reference to non-const, such as the formal arguments of your operator>.
Declare it thusly:
bool operator>( INDEX const& v1, INDEX const& v2 )
However, the implementation that you present doesn't seem to be correct for operator>.
And while I'm at it,... |
4,012,092 | 4,012,158 | Memory ordering issues | I'm experimenting with C++0x support and there is a problem, that I guess shouldn't be there. Either I don't understand the subject or gcc has a bug.
I have the following code, initially x and y are equal. Thread 1 always increments x first and then increments y. Both are atomic integer values, so there is no problem w... | The problem could be in your test:
if (x < y)
the thread could evaluate x and not get around to evaluating y until much later.
|
4,012,175 | 4,012,244 | EXE and DLL dependency - When to recompile the EXE? | I've the following class definitions in exe and dll.
// A.exe:
Class A { void fun() { B* b = new B(); b.funx(); }
// B.dll:
Class B { void funx (void) { C* y = new C(); y.funy(); }
Class C { void funy() { } }
Lets say I change the size of class B, should i recompile A.exe? And should I recompile A.exe even if I cha... | You have to recompile a.exe every time the public interface of b.dll changes (not only the size, also when members are reordered, private/public changes [this also affect member ordering, without being visible from the source code], ...). If C is part of the public interface, then you need to recompile A.exe also every... |
4,012,222 | 4,012,230 | C++ 'strcpy' gives a Warning (C4996) | I am getting this warning but all functions working properly .
what does this really means?
'strcpy': This function or variable may be unsafe.
Consider using strcpy_s instead. To disable deprecation,
use _CRT_SECURE_NO_WARNINGS. See online help for details.
| This function (strcpy) is considered unsafe due to the fact that there is no bounds checking and can lead to buffer overflow. (Actually strcpy is infamous for overflow exploits and all programmers avoid it-or at least should avoid it). The advice is to use a safe function which takes into account the size of the destin... |
4,012,304 | 4,012,555 | C++ Using a file format | A couple of days ago, I asked how you could reverse engineer a file format. While that didn't really work out, someone gave me the file format. (Click Here) Thank you Xadet.
I'm still quite new to all this, and I was wondering where I should go from here. I am guessing I will have to use inline-asm in C++ to use this f... | I assume you don't want to have a C++ program that reads that file format document when it starts, then parses the actual data file on that basis. Instead, you just want a C++ program dedicated to reading the current version of that file format? (This is much simpler and will run faster). You don't need to use ASM. ... |
4,012,360 | 8,907,233 | Loading an image from resource and converting to bitmap in memory | I've searched around using google but I'm completely confused on how to load an image (PNG in my case) from resource and then converting it to a bitmap in memory for use in my splash screen. I've read about GDI+ and libpng but I don't really know how to do what I want. Could anyone help?
| I ended up using PicoPNG to convert the PNG to a two dimensional vector which I then manually contructed a bitmap from. My final code looked like this:
HBITMAP LoadPNGasBMP(const HMODULE hModule, const LPCTSTR lpPNGName)
{
/* First we need to get an pointer to the PNG */
HRSRC found = FindResource(hModule, lpPN... |
4,012,462 | 4,012,483 | Does Visual C++ 2010 support the C++11 threads library? | I am using Visual C++ 2010. Does it support the C++11 threads library, such that I could compile the code in this question?
If not, what library can I use that would support this?
| Visual C++ 2010 does not provide the C++11 thread support or atomics libraries.
If you want to use that code in Visual C++ 2010, you'll need to use a third-party implementation of those libraries. One option is just::thread; it's not free, but I have a copy and am quite pleased with it.
Alternatively, you can use anot... |
4,012,524 | 4,012,542 | C++ overloaded new[] query : What size does it take as parameter? | I have overloadded operator new[] like this
void * human::operator new[] (unsigned long int count){
cout << " calling new for array with size = " << count << endl ;
void * temp = malloc(count) ;
return temp ;
}
and now calling
human * h = new human[14] ;
say sizeof(human) = 16 , but count it p... | The extra space allocated is used to store the size of the array for internal usage (in practice so that delete[] knows how much to delete).
It is stored at the beginning of the memory range, immediately before &h. To see this, just look at the value of temp inside your operator new[]. The value will differ from that i... |
4,012,745 | 4,013,067 | getting 'undeclared identifier' error | Following the tutorial at http://www.codersource.net/mfc/mfc-tutorials/ctabctrl.aspx , I have declared the function ActivateTabDialogs() in my header file and called it inside another function in my class. The compiler gives error C2065: 'ActivateTabDialogs' : undeclared identifier, at the line ActivateTabDialogs(); in... | Turns out that I didn't add the handler using the class wizard, and put the function OnSelChange() manually, and that was causing the problem. Thanks a lot for your attention
|
4,012,750 | 4,012,857 | UDP checksum error c++ | I am calculating UDP checksum using the following function (found it somewhere):
uint16_t udp_checksum(const void *buff, size_t len, in_addr_t src_addr, in_addr_t dest_addr)
{
const uint16_t *buf=(const uint16_t *)buff;
uint16_t *ip_src=(uint16_t *)&src_addr,
*ip_... | UDP checksum computation requires an UDP pseudo-header.
Here are some code samples from my libraries that might help:
// SmartBuffer is a stream-like buffer class
uint16_t SmartBuffer::checksum(const void* buf, size_t buflen)
{
assert(buf);
uint32_t r = 0;
size_t len = buflen;
const uint16_t* d = rein... |
4,012,943 | 4,013,032 | static_cast on derived classes when base turns from not polymorphic to polymorphic | I am reviewing C++ casts operator and I have the following doubt:
for polymorphic classes
I I should use polymorphic_cast
I should never use of static_cast since down-casting might carry to undefined behavior. The code compiles this case anyway.
Now suppose that I have the following situtation
class CBase{};
class ... | Background you didn't include - boost has polymorphic_cast as a wrapper around dynamic_cast<> that throws when the cast fails. static_cast<> is fine if you're certain that the data is of the type you're casting to... there is no problem with or without virtual members, and the code you include saying it won't compile ... |
4,013,045 | 4,013,160 | BadPtr after several iterations | C++. Its may be more question of debugging in Visual Studio and working with memory.
I have a program that analyzes list of files, and path to current file is a concatenation of to strings: CString object named 'folder' and filename itself(CString too).
But after 144'th iteration(im sure the number is unimportant), fo... | I haven't looked at your code, but this smells like someone writing over the bounds of their data. To catch something like this:
Let your loop run up to the 143rd iteration. (Use a conditional breakpoint to break at the 143rd time.) Examine your folder to make sure it really is still Ok.
Set a data breakpoint on the... |
4,013,046 | 4,013,112 | How to speed up transfer of images from client to server | I am solving a problem of transferring images from a camera in a loop from a client (a robot with camera) to a server (PC).
I am trying to come up with ideas how to maximize the transfer speed so I can get the best possible FPS (that is because I want to create a live video stream out of the transferred images). Disreg... | This might be quite a bit of work but if your client can handle the computations in real time you could use the same method that video encoders use. Send a key frame every say 5 frames and in between only send the information that changed not the whole frame. I don't know the details of how this is done, but try Googli... |
4,013,164 | 4,013,241 | c++ vector of iterators | I understand that I can point to number of vectors std::vector<int> using for loop on one vector<int*> onev_point_2_all etc.. but how do i do that using iterators is there a way of creating a vector of iterators instead of a vector of pointers ?
| You can have a vector of iterators, not necessary iterators of a vector and not necessarily iterators of the same collection, but they must all be of the same type.
You would not need the underlying collection to be able to dereference them, so if you know they are all valid iterators and that's all you want to do, you... |
4,013,171 | 4,014,283 | Adding HTTP header to all outgoing packets on Windows? | I am developing a Windows application that will live in the system tray. The application can be enabled/disabled by the user.
Whenever the user enables it, it needs to listen/sniff HTTP traffic and add a specific HTTP header on all outgoing packets.
I think it can be done by changing the system or browser settings to b... | The simplest way of doing this is what you describe: configure your browser to work via proxy, and then implement it, adding/modifying headers as necessary.
Your idea about adding HTTP headers to outgoing "packets" is wrong. Because you forget that HTTP protocol is based on TCP, which is a stream. That is, you should n... |
4,013,250 | 4,353,791 | Using strings to identify objects: what's the purpose? | OGRE3D for example uses strings to identify objects, so each time the code does something on an object using its name (a string), it has to do string operations, and since a 3D engine is very sensitive on speed, how can it be a good way on doing it ?
When a computer has to do operations on a string, it does it sequenti... | Well I got the answer by a teacher:
In fact a string identifier, once in a map thus inserted in order, is quickly found with a dichotomic search.
|
4,013,261 | 4,013,289 | change of vectors first pointer | When i use vector to store some data, I usually access to this data by the pointer of the vector's first entry. because it it faster than the at() method. But I realize that when I insert a block of data, say an array to the end of vector, the first entry's pointer changes. This may be realated to stack stuff, But if I... | std::vector can dynamically resize. The way it does this is to hold more space than is required. Once you hit the reserved capacity a larger block of data needs to be reserved (depends on implementation, but often the capacity of the new block is double the previous size). The data is then copied across to the new loca... |
4,013,277 | 4,067,419 | Error when trying to price instrument when using Quantlib | I am receiving the following error when trying to price a 20x10 swap from a bootstrapped curve. The error get thrown on the last line of the ImpliedRate function
SwapRatesServiceTests.ImpliedRate_ForTwenty_x_TenYearSwap_ReturnsRate:
System.ApplicationException : 2nd leg: empty Handle cannot be dereferenced
I don't... | Based on feedback from the Quantlib mailing list
The Jibar index needs to have a reference to the risk free curve created. Without a term structure, the Jibar can return past fixings but not forecast future ones. The Jibar constructor needs to be replaced with
new Jibar(new Period(Frequency.Quarterly), DiscountingTe... |
4,013,296 | 4,013,594 | Libjpeg error - improper call in state 205 | I'm using libjpeg (C/C++ programming on Windows Mobile 6.5), in order to decode images from an IP camera (sent in a MJPEG stream), before pushing them into a DirectShow graph.
Until now, I've been using a single function for : receiving the stream, parsing it manually (in order to find JPEG data starting- and end-point... | 205 is 0xCD, that is the standard value put by VS in debug mode in unitialized memory, so I think that your cinfo was not initialized properly at the moment you've called the decoder. Post the code when you use it.
Also, the setjump() you're using make me think it's IJG library. Be careful with it because it's not a st... |
4,013,327 | 4,013,631 | Shared template member function of multiple classes | I have multiple classes that are quite different in their behavior, but at the same time, share common functions that have to access the member variables.
So what I want to do, is to create a templated member function to avoid extra copy-paste code duplication.
The final result should be like:
ClassA::CallFoo()
ClassB:... | If what you are saying is that all of these classes inherit from LibClass, which contains memberX, then just add one more layer of inheritance:
class myLibClass : public LibClass
{
void CallFoo() { // do stuff with memberX }
};
class classA : public myLibClass {};
class classB : public myLibClass {};
etc...
|
4,013,364 | 4,022,825 | SDL_SetVideoMode hangs the process | During initialisation of my program I call SDL_SetVideoMode() just after SDL_Init() and it is hanging my program.
When executing the program, if I press Ctrl-C during the hang it will continue as normal and all works fine.
Obviously, having to interupt SDL_SetVideoMode() every time isn't ideal! Anyone have any ideas o... | I've since found the problem. I was simply not freeing the image surface after displaying which meant SDL_Quit wasn’t being called correctly!
Fixed code from example below:
SDL_Surface* m_pImage;
Presentation::DisplayNextSlide()
{
m_pImage = IMG_Load(filename);
if(!m_pImage)
{
//error handling...
}
... |
4,013,391 | 4,016,714 | Is it possible to have a function(-name) as a template parameter in C++? | I don't want function pointer overhead, I just want the same code for two different functions with the same signature:
void f(int x);
void g(int x);
...
template<typename F>
void do_work()
{
int v = calculate();
F(v);
}
...
do_work<f>();
do_work<g>();
Is this possible?
To clear up possible confusion: With "te... | One approach that is highly likely to generate the direct function call, because it gives the compiler no option, is to use a static member function:
struct F { static void func(int x) { /*whatever*/ } };
struct G { static void func(int x) { /*whatever*/ } };
template<class T>
void do_work() {
T::func(calculate())... |
4,013,505 | 4,013,560 | Listen for changes in a DOM structure | Is there any standardized way (not language dependent, I need at least C++, Java and Ruby) of listening for changes in a DOM-document? I would like to have a function called every time a node's attributes change, a node gets renamed, deleted, etcetera.
I found the Handlers for UserData, however those don't allow me to ... | You want to add a handler for Mutation Events. I've used these in Firefox, although I don't know what availability they have in libraries for the languages you mention.
http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-eventgroupings-mutationevents
|
4,013,703 | 4,013,818 | Can't overload << for Enum in C++ | I have created an enumerated data type to define possible flight lengths. I'd like to overload its << operator so the representation is nicer.
When I compile this, I get the following error (posted for completeness' sake. Basically multiple definitions of operator <<(ostream&, Categoria&)):
g++ -oProjectoAEDA.exe src\v... | Multiple definition linker errors because you've defined the function in a header file that's included in two or more compilation units.
Either add inline, like
inline std::ostream& operator<<(std::ostream & os, Categoria & cat)
or move the definition to an implementation file (you still need a declaration in the head... |
4,013,922 | 4,013,994 | overload resolution in templates | Any one Explain this with an example
"Involving conversions on a function argumentsinvolved in template
parameter deduction."
EXamples like this:
template<class T> struct B { /* ... */ };
template<class T> struct D : public B<T> { /* ... */ };
template<class T> void f(B<T>&);
void g(B<int>& bi, D<int>& di)
... | It is about what the example shows. In sum, these are those conversions
The function parameter can be a Base<T>, while the function argument is a Derived<T>. Compare with ifstream << "hello" - left side of operator<< is deduced in that way.
The function parameter can be a const U&, while the function argument is a U (... |
4,014,114 | 4,014,394 | Using Poco XMLWriter with UTF8 strings in C++ | I have a problem trying to get my head around using UTF8 with Poco::XML::XMLWriter. In the following code example, everything works fine when the input contains ASCII characters. However, occasionally the string in wordmapIt->first contains a non-ASCII value, such as a character -105 occurring in the middle of a string... | It sounds like you have a byte string in Windows code page 1252 encoding. “Character -105” presumably really means byte 0x97, which would map to Unicode character U+2014 Em Dash (—) in cp1252.
I'm not familiar with Poco, but I would guess you're expected to convert your cp1252 strings to UTF-8 output encoding using a T... |
4,014,151 | 4,039,601 | Is it appropriate to use MFCs PropertySheet for a TDI-application? | I think it is possible to write a TDI-Application with MFCs CPropertySheet class. Is this the right way to do it, or is there a standard way with not using this class?
It should also be possible to include a status-, menu- and toolbar into the application.
Thanks!
| No, this is a bad idea.
If you have VS2008 (with MFC Feature Pack) or above then when you make a new MFC MDI application, it will do all the hard work of creating a TDI interface for you.
See here for a tutorial.
|
4,014,172 | 4,015,843 | wprintf format type specification %ws | I just discovered that %ws was common knowledge (to some), for formatting unicode strings, as is %wZ - however msdn does not document these in a place I can find them. There are many people who write about these usefull printf format types individually on the web, but no official catch-all that I can find, and hence le... | In an ideal world the list of valid types on MSDN here would be complete. It does mention that some are Microsoft extensions.
However, there is also separate info on wsprintf formatting, which includes ws and ls as you noted.
I don't see any other type lists that apply here on MSDN.
As noted in comments, I do thi... |
4,014,177 | 4,016,771 | One way cryptographic hashing of a number ensuring each result is unique | Is there a good algorithm for this? after an amount of searching around I haven't been able to find any conclusive answers.
Basically in a system which collects various bits of data about its users, each user is identified by a 64 bit unique Id. this Id is used as a primary key to a data set which may include any amoun... | For each ID generate a unique random ID and store it as part of the users information.
Then you can get from an ID to hash. The reverse is computationally possible (as you must scan the whole key space) but excessively hard and time consuming.
|
4,014,294 | 4,015,073 | Operator overloading on class templates | I'm having some problems defining some operator overloads for template classes. Let's take this hypothetical class for example.
template <class T>
class MyClass {
// ...
};
operator+=
// In MyClass.h
MyClass<T>& operator+=(const MyClass<T>& classObj);
// In MyClass.cpp
template <class T>
MyClass<T>& MyClass<T>::o... | // In MyClass.h
MyClass<T>& operator+=(const MyClass<T>& classObj);
// In MyClass.cpp
template <class T>
MyClass<T>& MyClass<T>::operator+=(const MyClass<T>& classObj) {
// ...
return *this;
}
This is invalid for templates. The full source code of the operator must be in all translation units that it is used in.... |
4,014,302 | 4,014,321 | C++ smart pointer to statically and dynamically allocated resource | my base class need to expose a method that for some derived classes would return a smart pointer to dynamically allocated array, and for some other derived classes would return a pointer/reference to statically allocated one.
example:
class Base
{
public:
virtual ??? foo()=0;
}
class A : public Base
{
private:
... | You can provide custom deleters for Boost smart pointers. This can also be an empty function that does not do anything. For the class returning a dynamically allocated array, you can use a standard shared_array, and for the class returning a pointer to a statically allocated array you can return a shared_array with an ... |
4,014,529 | 4,014,727 | Turning boost::tuples::cons<...> back into the corresponding boost::tuple<...> | For a little library project I'm using boost::tuple. Right now, I'm facing the problem of turning a "cons list" I operated on via metaprogramming back to a boost::tuple<...> type. The "dirty" solution would be to provide lots of partial specialications a la
template<class T> struct id{typedef T type;};
template<class ... | If you're doing template metaprogramming and you need conversion from typelists to tuple, maybe you should consider using Boost.MPL and Boost.Fusion. The former provides a set of compile-time containers and algorithms to manipulate list of times, and the latter make the link between pure compile-time (MPL) and pure run... |
4,014,732 | 4,014,825 | Auto correction , auto complete features | Hii ,
We see suggestions when we type a word in Ms-word , google etc... How do they do that ?
I would like to know how the techniqueslike auto correct , auto complete , spell checking etc.. are performed . HOw are the words actually stored... what algorithms are followed ... ???
Any links that suggest a possible way ar... | Here are some data structures that are especially useful for working with (and finding) strings.
Tries
Suffix trees
Directed acyclic word graphs
Suffix array
Patricia trie
These can be especially useful for auto-completion.
Here's a simple spell checker written in Python with a bit of digression on how it works.
In o... |
4,014,851 | 4,014,878 | How to call a lib written in C++ from C? | It seems to me like a no-brainer, but I cannot find any information against or for it.
From the point of view of demangling etc, I don't suppose this to be a big problem, but I can't figure out, how I can write a little tiny C program which calls a function from a little tiny C++ library.
I am on linux right now, tryin... | Typically, you need to force the C++ compiler to build the library with C linkage for the exported functions.
You can do that by doing the following to your header:
#ifdef __cplusplus
extern "C" {
#endif
void func(void);
/* ... Other function defs go here ... */
#ifdef __cplusplus
}
#endif
Normally, the linker will... |
4,014,965 | 4,015,455 | What do I have to learn to create Mafia 3? | I want to know, what other things ( what 3d engine for example ) I have to learn to create a game like Mafia 2 or GTA IV.
| Developing a game with the complexity and scale of, say, Mafia or GTA is not an easy task. Several hundred people are involved for some years in the process developing a game like GTA or any other AAA game. The development is a very time consuming and not trivial task in general. For a single person, it should be impos... |
4,014,967 | 4,015,272 | C++ linking to libraries with makefile (newbe) | I'm trying to understand how to use non standard libraries in my C++ projects.
I have a few questions.
Lets say I want to use POCO library. So I downloaded it and build it using make (static build). Now I have bunch of .o files and .h files.
There is a Path.h file and a Path.o file in different directories.
Now I want ... | Besides the .h and .o files, you will probably also have one or more libXXX.a and/or libXXX.so files. These are the actual library files that your application should link against.
To use the library, you include the relevant headers in your source file, and you change your makefile to tell the linker that it should als... |
4,015,220 | 4,015,449 | Overlapped WSARecv() Callback Not Being Called in MFC App | I have a COM component, implemented in C++ with ATL, that uses overlapped socket I/O. Right after the connection is made to the server, it starts an overlapped read on the socket, with code like this:
// Pass pointer to this instance as hEvent parameter, for use by callback
m_recvOverlapped.hEvent = reinterpret_cast<H... | OK, I found the answer by searching for other Stack Overflow questions regarding WSARecv.
From Len Holgate's answer to Win32 Overlapped I/O - Completion routines or WaitForMultipleObjects?:
. . . you can pass a completion routine which is called when completion occurs. This is known as 'alertable I/O' and requires tha... |
4,015,351 | 4,015,433 | What data structure to use? | I need a data structure with the following properties:
Access to elements must be very fast
Elements, that are not added, shouldn't take memory (as ideal, size of empty structure near to zero)
Each element has two integer coordinates (x,y) (access to elements only by them)
Max count of elements known at creation time ... | Check this out - you could alter the element type to float if this does everything you want.
Concise Sparse Matrix Package in C
For C++ you could use Boost.uBLAS - sparse_matrix details here.
|
4,015,401 | 4,015,427 | operator<< for nested class | I'm trying to overload the << operator for the nested class ArticleIterator.
// ...
class ArticleContainer {
public:
class ArticleIterator {
// ...
friend ostream& operator<<(ostream& out, const ArticleIterator& artit);
};
// ...
};
If I define operat... | You don't put the friend keyword when defining the function, only when declaring it.
struct A
{
struct B
{
friend std::ostream& operator<<(std::ostream& os, const B& b);
};
};
std::ostream& operator<<(std::ostream& os, const A::B& b)
{
return os << "b";
}
|
4,015,641 | 4,015,750 | how to dynamically create methods to operate on class objects initialized at runtime | I have a class, say
class AddElement{
int a,b,c;
}
With methods to set/get a,b,c... My question is definitely a logic question - say I implement AddElement as follows:
int Value=1;
Value+=AddElement.get_a()+AddElement.get_b()+AddElement.get_b();
Now imagine I want to do the above except 'a,b,c' are now arrays, a... | You provide your class with a method GetSumOfActiveElements that does just what the name says. You can make this class virtual and create subclasses for each scenario, or have the class manage the memory efficiently in some other way.
|
4,016,061 | 4,016,183 | Why is inlining considered faster than a function call? | Now, I know it's because there's not the overhead of calling a function, but is the overhead of calling a function really that heavy (and worth the bloat of having it inlined) ?
From what I can remember, when a function is called, say f(x,y), x and y are pushed onto the stack, and the stack pointer jumps to an empty bl... | Aside from the fact that there's no call (and therefore no associated expenses, like parameter preparation before the call and cleanup after the call), there's another significant advantage of inlining. When the function body is inlined, it's body can be re-interpreted in the specific context of the caller. This might ... |
4,016,112 | 4,017,082 | What are the default APPDATA directories each version of Windows? | Is there a list of default APPDATA directories each version of Windows? (XP & up)
I need to know the default directory each OS will return for the following call:
SHGetSpecialFolderLocation( NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE , &pidl );
| There isn't really a simple answer to make into a list even for just english installs.
Here are some examples I just pulled from a few machines.
Windows 8 - C:\Users\%USERNAME%\AppData\Roaming
Windows 7 - C:\Users\%USERNAME%\AppData\Roaming
2K8 - C:\Users\%USERNAME%\AppData\Roaming
Vista - C:\Users\%USERNAME%... |
4,016,412 | 6,664,834 | PostgreSQL's libpq: Encoding for binary transport of ARRAY[]-data? | after hours of documentations/boards/mailinglists and no progress I may ask you: How do I 'encode' my data to use it for binary transport using libpq's PQexecParams(.) ?
Simple variables are just in big endian order:
PGconn *conn;
PGresult *res;
char *paramValues[1];
int paramLengths[1];
int paramFormats[1];
conn = PQ... | As ccuter already mentioned, you need to create your own API. The following code extracts a 1-dimensional array of int4's ignoring any NULL values.
#define INT4OID 23
/*! Structure of array header to determine array type */
struct array_int4 {
int32_t ndim; /* Number of dimensions */
int32_t _ign; /* offset fo... |
4,016,471 | 4,016,490 | C++ circular reference problem | I have 2 classes: DataObject and DataElement. DataObject holds pointers to (only) DataElements, and a DataElement contains pointers to several types, among which a DataObject.
This used to be no problem, since I only use pointers to DataObjects in DataElement, so a forward declaration of DataObject in the header of Dat... | Define the destructor in a .cpp file that includes both headers.
|
4,016,587 | 4,016,632 | c++ class pointer deletion segfaulting | I've got a simple class called object that I'm having a problem with. Theres one method which causes a segfault if I call it. I don't understand why.
typedef class object
{
private:
short id;
std::string name;
SDL_Rect offset;
public:
object();
object(short i, std::string n);
... | Since you didn't new anything in the constructor, it is wrong to delete anything in the destructor. Just leave the destructor empty, or even better yet, get rid of it completely. The compiler-generated destructor does exactly what you want (nothing). You also don't have to write the copy constructor and the copy assign... |
4,016,620 | 4,017,611 | Parameter issue with operator overload for != | I'm trying to define an overload for the != operator. My code is as follows. (Update: outdated code. If one of two article pointers points to NULL, this code will crash.)
bool ArticleContainer::ArticleIterator::operator!=(const ArticleIterator& artit) {
if (this->article == NULL && artit.article == NULL)
re... | I think the intent of your code is wrong, but technically you can try this:
bool ArticleContainer::ArticleIterator::operator!=(const ArticleIterator& artit) {
if (article == NULL && artit.article == NULL)
return false;
if (article == NULL || artit.article == NULL)
return true;
if (article->G... |
4,017,011 | 4,017,172 | Problem with pointer to a member function | In code below (please see comment):
#include "stdafx.h"
#include <iostream>
using std::cout;
struct Base
{
void fnc()
{
cout << "Base::fnc()";
}
};
struct Impl
{
void* data_;
Impl(void (Base::*fp)())
{
fp();//HERE I'M INVOKING IT - I'M DOING SOMETHING WRONG!
}
};
int _tmain(int argc, _TCHAR* argv[])
... | typedef int (MyClass::*memberPointer_t)(int);
...
memberPointer_t mb = &MyClass::function;
MyClass* object = getObject();
int returnValue = (object->*mb)(3);
...
Since it's a pointer to a member function, you must call it on an object and use the ->* or the .* operator to call it.
|
4,017,034 | 4,017,061 | C++: Where does the ofstream class save the files to? | I moved from Windows to Mac and now I'm experiencing a problem with the file input/output classes: ifstream & ofstream.
In Windows when you run with g++/Code Blocks
ofstream out("output.txt");
out << "TEST";
out.close();
A new file "output.txt" will be created in the same directory.
However in MAC OS X, this file is ... | The stream classes, like all other file-opening functions, use the current directory when you provide a relative path. You can control the current directory with a function like chdir, but a better solution is to use fully qualified file names. Then you remove your program's dependency on the current directory.
|
4,017,131 | 4,017,409 | Why aren't my variables holding state after WaitForSingleObject? | I am implementing a Go Back N protocol for a networking class. I am using WaitForSingleObject to know when the socket on my receiver thread has data inside it:
int result = WaitForSingleObject(dataReady, INFINITE);
For Go Back N, I have to send multiple packets to the receiver at once, and manipulate the data, and the... | As I was entering my code (hand typing since my code was on another computer), I realized a very stupid bug when I was setting the original value for expectedSeq. I was setting it to 0 every run through of a packet.
Have to love the code that comes out when you are coding until 5 am!
|
4,017,327 | 4,017,597 | __gnu_cxx hash map with keys of type std::pair<std::string, unsigned int>? | Since std::pair<std::string, unsigned int> is not defined for __gnu_cxx hash map, how do I create a __gnu_cxx hash map with keys of type std::pair<std::string, unsigned int> and values of type std::pair<int, CBTNODE>? (CBTNODE is typedef as typedef int CBTNODE)
If it's possible, I would really want to substitute std::... | This seems to compile and print the right answer (1):
#include <hash_map>
#include <utility>
#include <string>
#include <iostream>
typedef int CBTNODE;
typedef std::pair<std::string, unsigned int> INDEX;
typedef std::pair<int, CBTNODE> Element;
struct pairhash{
size_t operator()(const INDEX &p) const {
re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.