question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
3,326,742 | 3,326,799 | How to avoid the "swapping of death" during development? | Probably everyone ran into this problem at least once during development:
while(/*some condition here that somehow never will be false*/)
{
...
yourvector.push_back(new SomeType());
...
}
As you see the program starts to drain all system memory, your program hangs and your system starts to swap like crazy.... |
Overriding the global new and delete operators won't help, because the free function I would invoke in the delete won't give any idea how many bytes are freed.
But you can make it so. Here's a full framework for overloading the global memory operators (throw it in some global_memory.cpp file):
namespace
{
// u... |
3,326,781 | 3,326,815 | IntSetArray implementation in c++ | i have trying to imlement IntSetArray in c++ it compiles fine but result is wrong first 300 is ok and other numbers are below zero something very strange numbers .e.g -8231313 something like this)
what is wrong? it is code
#include <iostream>
using namespace std;
int quantity=10;
class Set
{
private :
int n... | Think through what happens the first time you try to insert something. x[0] contains 300 and t, what you are trying to insert, is 123.
The first statement in the insert method is this:
for (int i=0;x[i]<t;i++)
This for loop increments i while the ith element of x is less than t. But the 0th element of x is 300, ... |
3,326,822 | 3,326,874 | Using Unicode in a C++ source file | I'm working with a C++ sourcefile in which I would like to have a quoted string that contains Asian Unicode characters.
I'm working with QT on Windows, and the QT Creator development environment has no problem displaying the Unicode. The QStrings also have no problem storing Unicode. When I paste in my Unicode, it disp... | Personally, I don't use any non-ASCII characters in source code. The reason is that if you use arbitary Unicode characters in your source files, you have to worry about the encoding that the compiler considers the source file to be in, what execution character set it will use and how it's going to do the source to exec... |
3,326,906 | 3,327,042 | Get the defaults programs | i use c++ and qt for a project.
I would to know how i can get the default program : default navigator, default mail client, default editor ...
I found for Linux - Gnome: gconftool!
What is for Windows, Mac Os or Linux (KDE) ?
Thanks you.
| On Windows this kind of stuff can be recovered directly from the registry (regedit).
Search the web to find out the specific registry paths, like this.
|
3,326,911 | 3,389,896 | How to turn .h file +dll into some kind of .Net wrapper? | How toturn .h file +dll into some kind of .Net wrapper? or something like that? (no C\C++ sources just h files)
| If you have the header file, and use many implement from that dll you can use swig(http://www.swig.org/) to generate wrapper automatically. Then compile as a dll and invoke the interfaces or class from .Net code.
Or if you only use few method from the dll, just use P/Invoke.
|
3,326,926 | 3,326,975 | How do detect if an address will cause an access violation? | I'm creating a class for a Lua binding which holds a pointer and can be changed by the scripter. It will include a few functions such as :ReadString and :ReadBool, but I don't want the application to crash if I can tell that the address they supplied will cause an access violation.
Is the a good way to detect if an add... | There are ways, but they do not serve the purpose you intend. That is; yes, you can determine whether an address appears to be valid at the current moment in time. But; no, you cannot determine whether that address will be valid a few clock cycles from now. Another thread could change the virtual memory map and a fo... |
3,327,197 | 3,327,409 | How can I use Flex in Visual C++? | I'm trying to use Flex with Visual C++. However, the generated lexer (which is empty and has no rules) throws these errors while building:
configurationlexer.cpp(967): error C3861: 'read' identifier not found
configurationlexer.cpp(967): fatal error C1903: unable to recover from previous error(s); stopping compilation
... | Well, it would be helpful if the bozo that is Bill would read the documentation:
-f, --full, %option full'
specifies fast scanner. No table compression is done and stdio is bypassed. The result is large but fast. This option is equivalent to--Cfr'
which leads to:
-Cr, --read, %option read'
causes the generated s... |
3,327,222 | 3,328,632 | How to edit QtWebKit's right-click context menu in Qt Creator? | Alright, here's my dillema. I am making a simple application with Qt Creator that makes use of Webkit. I thought Qt Creator would have an easy way to edit the right-click context menu with the signals and slots editor, but this has proven to not be true. I know webkit has classes that have to do with the context menu, ... | The QWidget::contextMenuEvent( QContextMenuEvent * event ) is a "virtual protected" function.
You can inherit the QWebView, and then override "contextMenuEvent".
|
3,327,307 | 3,327,322 | How do I make an abstract class properly return a concrete instance of another abstract class? | I recently reworked one of my own libraries to try out separating interface from implementation. I am having on final issue with a class that is meant to return an instance of another class.
In the interface definition, I do something like
struct IFoo
{
virtual const IBar& getBar() = 0;
}
and then in the concrete... | Use smart pointers.
These are pointers deleted when not used anymore (see for example http://www.boost.org/doc/libs/1_43_0/libs/smart_ptr/smart_ptr.htm).
|
3,327,316 | 3,331,624 | How can I overwrite the "next" slot in a QWizard? | I'm using a QWizard class, which contains several QWizardPage. For some pages, I need to do something when the "Next" button is clicked.
I tried to overwrite the next slot in my QWizard class; however, it seems this doesn't work. The program still went into the original next slot in the parent QWizard class instead of ... | The next slot cannot be overwritten. However, the validatePage function for QWizardPage can. This function will be called when the "Next" or "Finish" button is clicked.
|
3,327,627 | 3,327,649 | Finding vector opposite to another? | I need to know how to find a vector opposite to another, but the second vector is not necessarily the same magnitude as the first, but the direction is opposite. Ex:
I made a small diagram :)
alt text http://img688.imageshack.us/img688/5394/prettydiagram.png
Basically if I have the coordinates of A(-150,150) and I want... | It is simple, really.
B = -1/2 * A, or B.x = -1/2 * A.x, B.y = -1/2 * A.y, B.z = -1/2 * A.z. This talks about vectors, btw. You would want to shift the result. The formula is dead-simple. What am I missing?
EDIT
Your app knows the red dot location (let's abbreviate it as R vector). Your app also knows the A vector. It ... |
3,327,631 | 3,327,659 | Casting with multiple inheritance | If you have a void* pointer to Derived class that inherits from both BaseA and BaseB, how does the compiler cast the void* pointer to BaseA* (or BaseB*) without knowing that the void* pointer is of type Derived?
| It doesn't. The only guarantee when casting to and from a void* using a static_cast is:
A value of type pointer to object converted to "pointer to cv void" and back to the original pointer type will have its original value (C++03 §5.2.9/10).
For example, the following code is incorrect because the void* is cast to a... |
3,327,709 | 3,327,717 | how do I open and read a file using ifstream in C++? | I would like to open a file and read a line from it. There will be only one line in the file so I don't really need to worry about looping, although for future reference it would be nice to know how to read multiple lines.
int main(int argc, const char* argv[]) {
// argv[1] holds the file name from the command pro... | A couple of things:
You can read a number with the >> stream extraction operator: ifs >> number.
The standard library function getline will read a line from a file, if you want a full line of text.
To check if the file opened, just write if (ifs) or if (!ifs). Leave out the == NULL.
You don't need to explicitly close ... |
3,327,751 | 3,327,766 | Creating a global FILE* object? | I'm building a program that has several functions that need to read data from a file. Since the functions are used fairly frequently, opening and closing the file for each call would be too time consuming, so my plan was to make the FILE* object global, and have the file open the whole duration of the program. Apparent... | You almost got it right. Try this:
#include <fstream>
FILE * yhtit;
int main() {
yhtit = fopen("thefile.txt","r");
//Do your thing here.
fclose(yhtit);
return 0;
}
|
3,327,754 | 3,327,803 | intersection of n lists | I have been trying out to figure out a way to find intersection of N lists in c++.
The method that is clicking me is sort, merge and iterate.
Is there any other way too ?
Please share your suggestions.
| A solution using unsorted lists would be messier. Presumably, you'd have an 'answer' list, initially empty. Then you'd identify two lists, and step through one; for each element, you'd scan the other list to see if it is present in that list - storing the element in the answer if there's a match. Then you'd create a... |
3,327,824 | 3,327,829 | How to store SDL_Color in C++ array? | SDL_Color normColor = {255,255,255};
SDL_Color redColor = {255,0,0};
SDL_Color blackColor = { 0,0,0 };
etc.
What kind of array do I need to do something like:
typeofarray mycolorArray[95] = {normColor, redColor, blackColor..............};
....
mycolorArray[65] = redColor // to change the color
| SDL_Color sdlColors[] = {normColor, redColor, blackColor..............};
|
3,327,917 | 3,327,930 | Linked-lists versus array in performance when dealing with sequentially accessed objects? | I am currently designing a game in which a maximum of approximately 10,000 objects will be used per level. Each frame all of the objects will be accessed in a sequential order at least once, sometimes twice or more. Right now I am using arrays but I am very curious as to if linked-lists would be better suited to hand... | Unless you are very frequently inserting and removing elements in the middle of a sequence, an array will all but certainly outperform a linked list (though, there are a handful of scenarios in which linked lists are useful).
With a linked list, you lose all the benefits of prefetching at the CPU level, since each node... |
3,328,022 | 3,328,037 | Confused with C++ Inheritance | I'm so confused with the output of the following code:
#include <iostream>
using namespace std;
class Parent
{
public:
Parent() : x(2) { }
virtual ~Parent() { }
void NonVirtual() { cout << "Parent::NonVirtual() x = " << x << endl; }
private:
int x;
};
class Child : public Parent
{
public:
Child... | The code above illustrates the fact that, in C++, only functions marked virtual are overriden. What you have here is overshadowing, not overriding. In overriding and inheritance, the behavior is based on runtime type which is the normal inheritance behavior you expect, but if you don't declare it virtual, then the beha... |
3,328,053 | 3,328,088 | Is it true that there will always be a .lib(import library) associated with the .dll you build? | Or do I need to instruct the compiler explicitly ?
| With a user name like "ieplugin" the answer would probably be No. COM servers don't have .lib files. For regular DLLs, the .lib file is produced by the linker, not the compiler. The /IMPLIB option generates them.
|
3,328,168 | 3,328,193 | implementation of IntSetLIst | here is implementation IntSetList in c++
#include <iostream>
using namespace std;
class IntSetList{
private:
int n;
struct node{
int val;
node *next;
node(int v,node *p){val=v;next=p;}
};
node *head,*sentinel;
node *rinsert(node *p,int t){
if (p->val<t){
... | No output at all? I suspect that it is outputting at least one number, since sizeof(v) is at least as big as sizeof(v[0]), but probably only just as big, since a pointer is the same size as an int on most 32-bit computers.
The sizeof(v)/sizeof(v[0]) trick only work on arrays, not pointers. A common trick to get around ... |
3,328,240 | 3,328,258 | Shift and ctrl prevent events from happening? (Winapi) | My application redraws the screen every time the mouse moves. I have not at all handled WM_KEYDOWN and I noticed that when I press shift or ctrl, it does not redraw on mouse mouse, nor does it seem to really do anything else. What could cause such a thing? If I press any other key like Z or X it does exactly what it sh... | No, they certainly don't prevent events from happening. But they seem to be preventing your code from recognizing them.
There's a handful of flags included with the event code, and they represent pressed keys/buttons. You'll probably notice the same effect with Alt or a pressed mouse button. My guess would be that you'... |
3,328,451 | 3,328,475 | Why I can't use unsigned short in switch/case? | I have two static member declarations in ClsA, like this:
class ClsA {
public:
static unsigned short m_var1;
static unsigned short m_var2;
};
unsigned short ClsA::m_var1 = 1001;
unsigned short ClsA::m_var2 = 1002;
In ClsB, I use those static member declarations from ClsA like this:
unsigned short var1; // assum... | C++ requires the case to have a constant-expression as its argument. What does that mean? It means that the only operands that are legal in constant expressions are:
Literals
Enumeration constants
Values declared as const that are initialized with constant expressions
sizeof expressions
In your case, if you declared ... |
3,328,593 | 3,328,614 | Why doesn't playSound actually output any sound using FMOD on windows? | FMOD_RESULT result;
FMOD::System *system;
result = FMOD::System_Create(&system);
if (result != FMOD_OK)
{
printf("FMOD error! (%d) %s\n", result, FMOD_ErrorString(result));
}
result = system->init(100, FMOD_INIT_NORMAL, 0);
if (result != FMOD_OK)
{
printf("FMOD error! (%d) %s\n", result, FMOD_ErrorS... | While the code looks fine to me, note that playSound() is asynchronous. If you're exiting directly afterwards, the sound will never have time to play. E.g.:
int main() {
// ...
sytem->playSound(FMOD_CHANNEL_FREE, sound, false, &channel);
// playSound() returns directly, program exits without sound being hea... |
3,328,617 | 3,328,726 | Can Doxygen be integrated with Netbeans C++? | I've been reading up on Doxygen online, and I think I'd like to try it out on my Netbeans C++ projects. The problem is, I cannot find any tutorials/guides anywhere to how to get Doxygen working with Netbeans. I've found some blog posts that seem to be about using Doxygen in Netbeans, but they seem semi-feature requesty... | There is no need for support from IDE to use Doxygen, you can use them separately. To create Doxygen documentation you just need a source code and Doxygen compiler.
However IDE can serve some kind of support. Netbeans allows you quickly create a comment (see here). That's the only support I know.
There is also plug-in ... |
3,328,976 | 3,329,118 | Accurate continuous timer callback | Ive got an application where I want to display a frame every x milliseconds.
Previously I did it like this:
class SomeClass
{
boost::thread thread_;
boost::timer timer_;
public:
SomeClass() : thread_([=]{Display();})
{
}
void Display
{
double wait = 1.0/fps*1000.0;
... | Remember that the accuracy with which a frame is displayed is limited by the refresh rate of your display (typically 17 ms for a 60 Hz display, or 13 ms for a 75 Hz display). If you're not syncing to the display refresh then you have an indeterminate latency of 0 - 17 ms to add to whatever timing method you use, hence ... |
3,329,120 | 3,329,304 | Sometimes I get EXEC_BAD_ACCESS (Access violation) when reversing an array | I am loading an image using the OpenEXR library.
This works fine, except the image is loaded rotated 180 degrees. I use the loop shown below to reverse the array but sometimes the program will quit and xcode will give me an EXEC_BAD_ACCESS error (Which I assume is the same as an access violation in msvc). It does not h... | And here's how you can optimize this code, to save memory and for cycles:
Rgba* readRgba(const char filename[], int& width, int& height)
{
Rgba* pixelBuffer = new Rgba[width * height];
Rgba tempPixel;
// ....EXR Loading code....
// Flip the image to conform with OpenGL coordinates.
for (int i = ... |
3,329,159 | 3,329,177 | Including C headers inside a C++ program | I have a C++ program (.cpp) inside which I wish to use some of the functions which are present inside the C header files such as stdio.h, conio.h, stdlib.h, graphics.h, devices.h etc.
I could include the stdio.h library inside my cpp file as : #include <cstdio>.
How do I include the other library files?
How do I add th... | For a list of C standard C headers (stdio, stdlib, assert, ...), prepend a c and remove the .h.
For example stdio.h becomes cstdio.
For other headers, use
extern "C"
{
#include "other_header.h"
}
|
3,329,214 | 3,329,464 | Is it possible to force a function not to be inlined? | I want to force a little function not to be compiled as inline function even if it's very simple. I think this is useful for debug purpose. Is there any keyword to do this?
| In Visual Studio 2010, __declspec(noinline) tells the compiler to never inline a particular member function, for instance:
class X {
__declspec(noinline) int member_func() {
return 0;
}
};
edit: Additionally, when compiling with /clr, functions with security attributes never get inlined (again, th... |
3,329,216 | 3,329,226 | Where can I learn how to make a C++ program interact with the Operating System (Linux) | I am a C++ beginner.
I'd like to create small programs that interact with the operating system (using Kubuntu Linux). So far, I have not been able to locate any tutorial or handbook to get C++ to interface with the OS.
In PHP, I can use the command exec() or the backtick operator to launch commands typically executed i... | You can use the system() command in stdlib to execute system commands:
#include <stdlib.h>
int main() {
system("ls -l");
}
system() returns an int as its return value, but the value of the int is system-dependent. If you try and use a command that doesn't exist, you'll get the standard "no such command" output bac... |
3,329,281 | 3,329,309 | Container that doesn't require its elements to be default and copy constructible | I'm looking for a C++ container-like class that wraps a typed array of objects that are not necessarily initialized and don't have to be default-constructible or copy-constructible. This would be interesting for RAII objects that have no well-defined copy semantics. Such a container-like class seems to be fairly easy t... |
Such a container-like class seems to
be fairly easy to write (using an
allocator to allocate uninitialized
memory and placement new).
And that is exactly what std::vector does. To use placement new, you would have to make a copy.
void store(const T& value)
{
new (storage) T(value); //<-- invokes copy constr... |
3,329,383 | 3,329,413 | Calculating the Moment Of Inertia for a concave 2D polygon relative to its orgin | I want to compute the moment of inertia of a (2D) concave polygon. I found this on the internet. But I'm not very sure how to interpret the formula...
Formula http://img101.imageshack.us/img101/8141/92175941c14cadeeb956d8f.gif
1) Is this formula correct?
2) If so, is my convertion to C++ correct?
float sum (0);
for (in... | #include <math.h> //for abs
float dot (vec a, vec b) {
return (a.x*b.x + a.y*b.y);
}
float lengthcross (vec a, vec b) {
return (abs(a.x*b.y - a.y*b.x));
}
...
do stuff
...
float sum1=0;
float sum2=0;
for (int n=0;n<N;++n) { //equivalent of the Σ
sum1 += lengthcross(P[n+1],P[n])*
(dot(P[n+1],P[n+1]... |
3,329,524 | 3,329,609 | Thunk and ATL Thunk? | Can someone explain to me what a Thunk is?
and an ATL Thunk?
I know a thunk has something to do with the vtbl and execution of code to find the right function pointer. Am I right?
| It is a generic term for a piece of adapter code that fundamentally changes the execution environment. I saw it first being used during the 16-bit to 32-bit Windows transition, a thunk was used to allow code that was running in 16-bit mode to call 32-bit code.
Something similar for ATL thunks. It knows how to turn a ... |
3,329,628 | 3,329,638 | Exception within function returning value for constructor | Let's say I have class that acts as a "smart pointer" and releases some kind of system resource when destroyed.
class Resource{
protected:
ResourceHandle h;
public:
Resource(ResourceHandle handle)
:h(handle){
}
~Resource(){
if (h)
releaseResourceHandle(h);//external funct... | Arguments are evaluated before any function call -- in this case the constructor --.
Therefore, the exception is thrown before the constructor call
|
3,329,699 | 3,330,651 | "Multiple occurrences" exception for boost program_options | I am writing the following code on boost's program_options (version 1.42). This seems straight-forward and taken pretty much as is from the tutorial. However, I get a "multiple_occurrences" error. Further investigation discovers that it's (probably) the "filename" parameter that raises it.
The parameters I am giving ar... | EDIT:
the second parameter to po::positional_options_description::add is the max count, not the position. The position is implied in the order you specify the positional options. So
p.add("motif_size", 0).add("prob", 1).add("filename", 2).add("repeats", 3);
should be
p.add("motif_size", 1).add("prob", 1).add("filenam... |
3,329,718 | 3,329,861 | utfcpp and Win32 wide API | Is it good/safe/possible to use the tiny utfcpp library for converting everything I get back from the wide Windows API (FindFirstFileW and such) to a valid UTF8 representation using utf16to8?
I would like to use UTF8 internally, but am having trouble getting the correct output (via wcout after another conversion or pla... | The Win32 API already has a function to do this, WideCharToMultiByte() with CodePage = CP_UTF8. Saves you from having to rely on another library.
You cannot normally use the result with wcout. Its output goes to the console, it uses an 8-bit OEM encoding for legacy reasons. You can change the code page with SetConso... |
3,329,827 | 3,329,877 | C++ ifstream UTF8 first characters |
Why does a file saved as UTF8 (in Notepad++) have this character in the beginning of the fstream I opened to it in my c++ program?
´╗┐
I have no idea what it is, I just know that it's not there when I save to ASCII.
UPDATE: If I save it to UTF8 (without BOM) it's not there.
How can I check the encoding of a file (AS... | When you save a file as UTF-16, each value is two bytes. Different computers use different byte orders. Some put the most significant byte first, some put the least significant byte first. Unicode reserves a special codepoint (U+FEFF) called a byte-order mark (BOM). When a program writes a file in UTF-16, it puts t... |
3,329,956 | 3,329,962 | Do STL iterators guarantee validity after collection was changed? | Let's say I have some kind of collection and I obtained an iterator for the beginning of it. Now let's say I modified the collection. Can I still use the iterator safely, regardless of the type of the collection or the iterator?
To avoid confusion, here is the order of operations I talk about:
Get an iterator of the c... | Depends on the container. e.g. if it's a vector, after modifying the container all iterators can be invalidated. However, if it's a list, the iterators irrelevant to the modified place will remain valid.
A vector's iterators are invalidated when its memory is reallocated. Additionally, inserting or deleting an elemen... |
3,330,239 | 3,330,251 | Header inclusion and compiler errors | In my CPP file I have a call that is:
pt.x = mDownPoint.x + FSign(pt.x-mDownPoint.x) *
FMax( FAbs(pt.x-mDownPoint.x), FAbs(pt.y-mDownPoint.y) );
I get compiler errors for FSign, FMax, FAbs, but I include the header file where they are at.
So I don't see why it would not find it, unless I have done something wr... | All the function are within FxMathFunctions, so it should be:
pt.x = mDownPoint.x + FxMathFunctions::FSign(pt.x-mDownPoint.x) *
FxMathFunctions::FMax( FxMathFunctions::FAbs(pt.x-mDownPoint.x),
FxMathFunctions::FAbs(pt.y-mDownPoint.y) );
But this is what namespaces are for, I don't think you actually w... |
3,330,296 | 3,330,317 | C++ Type casting order / Proper code-formatting? |
Possible Duplicates:
Declaring pointers; asterisk on the left or right of the space between the type and name?
what is the difference between const int*, const int * const, int const *
I've been wondering what is the difference between:
float const &var
const float &var
And which one of these is the correct way of... | All are equally valid. There is no one correct way; you should do whichever you find most readable (for your own code) or follow the prevailing style (if working with others).
Putting const first (e.g., const float & rather than float const &) is more common in my experience.
The positioning of & and * depends on progr... |
3,330,360 | 3,330,477 | Order a container by member with STL | Suppose I have some data stored in a container of unique_ptrs:
struct MyData {
int id; // a unique id for this particular instance
data some_data; // arbitrary additional data
};
// ...
std::vector<std::unique_ptr<MyData>> my_data_vec;
The ordering of my_data_vec is important. Suppose now I have another ve... |
Create a map that maps ids to their index in my_data_ids.
Create a function object that compares std::unique_ptr<MyData> based on their ID's index in that map.
Use std::sort to sort the my_data_vec using that function object.
Here's a sketch of this:
// Beware, brain-compiled code ahead!
typedef std::vector<int> ... |
3,330,399 | 3,330,438 | Best way to implement performing actions on tree nodes, preferably without using visitors | I have a user interface with a tree view on the left, and a viewer on the right (a bit like an email client). The viewer on the right displays the detail of whatever I have selected in the tree on the left.
The user interface has "add", "edit" and "delete" buttons. These buttons act differently depending on what "nod... | Visitor is useful when you have many operations and few types. If you have many types, but few operations, use normal polymorphism.
|
3,330,568 | 3,330,662 | Processing a binary file - templated functions problem | I've created a small tool which is used to process binary files. All the functions involved in reading the files and processing them are templated and are similar to this:
template <class T> void processFile( const char* fileName );
The template parameter T is used to determine the size of data which will be read and ... | If I understand your question correctly, the answer is yes: you should be able to specialize your template function with a suitable POD type. However you'll need to define a member operator<() in order to be able to use std::sort().
The following POD might be useful to you in the general case (it will certainly sort be... |
3,330,593 | 3,331,023 | Creating a swatch library | Hey all, I'm working on cleaning up my code from previous semesters.
Previously I created a 151 color swatch library in c++. However because of my time crunch and lack of experience, I created it entirely as a block of define statements. Which, for hard coding values into spots worked fine. However there are some obvio... | Use a lookup table:
/************* .h *************/
enum color{
red,
blue,
green,
colors_count
}
const vec3 &getColor(color c)
{
extern const vec3 colors_table[colors_count];
return colors_table[c];
}
/************* .cpp *************/
extern const vec3 colors_table[colors_count] = {
v... |
3,330,629 | 3,330,658 | "address not from malloc()" error using electric fence | I've been writing a test case program to demonstrate a problem with a larger program of mine,
and the test case has a bug that the original program does not.
Here's the header file:
// compiled with g++ -I/usr/local/bin/boost_1_43_0 -Wall -std=c++0x -g test.cpp
#include <bitset>
#include <boost/shared_ptr.hpp>
#includ... | yarl::level::Level l;
You instantiate an automatic Level variable, which, in its constructor constructs its member pathfinder like so:
pathfinder(new path::Pathfinder(this))
Then in the Pathfinder constructor, it takes the Level pointer that you pass in and assigns that to a shared_ptr. The shared_ptr then takes own... |
3,330,794 | 3,330,802 | Manipulating data members (C++) | I have a method that takes an object as an argument.
Both the caller and argument have the same members (they are instances of the same class).
In the method, particular members are compared and then, based on this comparison, one member of the argument object needs to be manipulated :
class Object {
// members
p... | This is because you are passing by value (which equates to passing a copy. Think of it as making somebody a photocopy of a document and then asking them to make changes, you still have the original so the changes they make won't be reflected in your copy when you get it back. But, if you tell them where your copy is ... |
3,331,019 | 3,331,061 | Capturing keyboard input on a List View control, C++ | How do I capture key presses when a list view control has focus?
My window creation code looks like
// Window creation
HWND hwnd = CreateWindowEx(WS_EX_TOPMOST | WS_EX_APPWINDOW, g_szClassName, "Test", WS_VISIBLE | WS_BORDER | WS_CAPTION | WS_DLGFRAME | WS_POPUP | WS_SYSMENU, CW_USEDEFAULT, CW_USEDEFAULT, 209, 351, 0, ... | You'll need to take a look at control subclassing, http://msdn.microsoft.com/en-us/library/bb773183%28VS.85%29.aspx.
If you're using MFC, it's a bit less painful. (Back in the day when Borland was still alive, it was a breeze in OWL, but that's ancient history.)
|
3,331,189 | 3,331,199 | what does allocator mean in STL | I'm using list class in c++ and i don't know what does allocator mean here
template < class T, class Allocator = allocator<T> > class list;
if i have list <int> mylist would it mean allocate integer type of memory using the allocator when an element is added to list? and when do you want a custom allocator?
| Yes. An allocator is a way of factoring the allocation of memory from the use of memory. If a container needs some memory, instead of:
// too rigid, cannot allow custom allocation schemes
void* mem = ::operator new(someAmount);
You get:
// flexible, allows custom allocation schemes
void* mem = myallocator.allocate(so... |
3,331,416 | 3,331,471 | Problem with linker/joystick input | I'm trying to wrap my head around getting user input from a joystick/mouse, which doesn't seem all that complicated, but I've run across this simple showstopper: calling joyGetNumDevs() gives me an unresolved external symbol error. I've included the necessary Windows.h and MMSystem.h, so I don't have any idea what may ... | Have you tried linking in winmm.lib?
|
3,331,453 | 3,331,562 | Overloading + Operator With Templates | Hey, I'm getting a linker error LNK2019: unresolved external symbol when trying to use an overloaded + operator. I'll show you snip-its from the class, and how I'm using it in main. If you need to see more, let me know, I'm just going to try and keep things concise.
/** vec.h **/
#ifndef __VEC_H_
#define __VEC_H_
#in... |
In order to befriend a template, I think you'll need to declare that template before the class definition in which you want to befriend it. However, for this declaration to compile, you'll need to forward-declare the class template. So this should work:
template<typename T>
class vec;
template<typename T>
vec<T> o... |
3,331,682 | 3,331,721 | Change wallpaper programmatically using c++ and windows api | I've been trying to write an application, using Qt and mingw32, to download images and set them as the background Wallpaper. I have read several articles online about how to do this, in VB and C#, and to some extent how to do it in c++. I am currently calling the SystemParametersInfo with what seems to be all the corre... | It could be that SystemParametersInfo is expecting an LPWSTR (a pointer to wchar_t).
Try this:
LPWSTR test = L"C:\\Documents and Settings\\Owner\\My Documents\\Wallpapers\\wallpaper.png";
result = SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, test, SPIF_UPDATEINIFILE);
If this works (try it with a few different files... |
3,331,905 | 3,332,164 | error LNK2019: unresolved external symbol SHInitExtraControls referenced? | How can i resolve this error:
Error 1 error LNK2019: unresolved external symbol SHInitExtraControls referenced in function "public: virtual int __cdecl CTestApp::InitInstance(void)" (?InitInstance@CTestApp@@UAAHXZ) Test.obj
thanks
| You need to link against aygshell.lib. Note that the MSDN page for SHInitExtraControls() says that aygshell.lib is the required library to use it.
A LNK2019 usually means that you forgot to provide a definition of something. In this case, the definition of SHInitExtraControls() is located in aygshell.lib. Without it, t... |
3,331,939 | 3,338,232 | Customize the buttons in a QWIzard? | QWizard have some options related to the buttons as follows:
NoDefaultButton
NoBackButtonOnStartPage
NoBackButtonOnLastPage
DisabledBackButtonOnLastPage
HaveNextButtonOnLastPage
HaveFinishButtonOnEarlyPages
NoCancelButton
CancelButtonOnLeft
HaveHelpButton
HelpButtonOnRight
Now t... | If you call the follwing function:
QAbstractButton * QWizard::button ( WizardButton which ) const
with following argument:
QWizard::NextButton
then you should get a pointer to the "Next" button.
The only thing left to do is to call setVisible(bool) function of the button when you are one the last but one (pre-last) ... |
3,332,063 | 3,332,255 | Why is my static library so huge? | I have a C++ compiled static library of about 15 classes and their member functions and stuff, and compiled, it's almost 14 megabytes. It links to Google's dense hash table library and MPIR, which is like GMP for Windows, but I did that in a plain exe and it was a few kilobytes. Why is it so massive? What can I do to r... | The static library is a considerably different format the finished binary; partially because it has quite a bit more information. Essentially, the static library acts like a ZIP of all the .obj files generated from your translation units. This allows the linker to throw out unused functions, and if you're using LTCG, i... |
3,332,095 | 3,332,138 | How can boost::bind does not match the signature provided but works fine? | My confuse is like this code:
#include "stdafx.h"
#include <boost/bind.hpp>
using namespace std;
void fool(std::string s)
{
std::cout<<s<<endl;
}
void fool2()
{
std::cout<<"test2 called\n"<<endl;
}
void fool3(std::string s1,std::string s2)
{
std::cout<<"test3 called\n"<<endl;
}
typedef boost::function<void(std... | One of the neat things about Boost.Bind is exactly it's ability to "massage" a function into a slightly different signature.
For example, you can make your fool3 example work by explicitly giving a value for the second parameter:
mywait(boost::bind(fool3, _1, "extra parameter"));
// or even:
mywait(boost::bind(fool3, "... |
3,332,257 | 3,333,154 | How do I properly implement a "minimize to tray" function in Qt? | How do I properly implement a "minimize to tray" function in Qt?
I tried the following code inside QMainWindow::changeEvent(QEvent *e), but the window simply minimizes to the taskbar and the client area appears blank white when restored.
if (Preferences::instance().minimizeToTray())
{
e->ignore();
this->setVisi... | Apparently a small delay is needed to process other events (perhaps someone will post the exact details?). Here's what I ended up doing, which works perfectly:
void MainWindow::changeEvent(QEvent* e)
{
switch (e->type())
{
case QEvent::LanguageChange:
this->ui->retranslateUi(this);
... |
3,332,440 | 3,332,483 | Safe conversion from double to unsigned 64 bit integer | On my platform this prints 9223372036854775808.
double x = 1e19;
std::cout << static_cast<unsigned __int64>(x) << '\n';
I tried Boost.NumericConversion, but got the same result.
Splitting x into 2 equal part, then adding together converted halves give the correct result. But I need a generic solution to use in a templ... | Seems like it works well with gcc, but it is problematic in Visual Studio. See Microsoft's answer regarding this issue:
Our floating-point to integer
conversions are always done to a
signed integer. In this particular
case we use FIST instruction which
generates 800..00 as you described.
Therefore, there is ... |
3,332,550 | 3,332,570 | More concise way to write the following statement | Is there a more concise way to write the following C++ statements:
int max = 0;
int u = up();
if(u > max)
{
max = u;
}
int d = down();
if(d > max)
{
max = d;
}
int r = right();
max = r > max ? r : max;
Specifically is there a way to embed the assignment of the functions return inside the if statement/ternary ope... | Assuming that:
The idea was to remove the local variables (i.e. you don't need u, d, r later on)
Evaluation order doesn't matter
... then you can just use std::max:
int m = max(max(max(0, up()), down()), right());
If this is the return value of the function:
return max(max(max(0, up()), down()), right());
Note that... |
3,332,726 | 3,334,759 | complex number types in mixing C(99) and C++ | I'm writing a math library, the core of it is in C++. Later it may be implemented in pure C (C99 I suppose). I think I need a C like API so that I can get Python and matlab and the like to use the library. My impression is that doing this with C++ is painful.
So is there a good or standard or proper way to cast between... | The C99 and C++0x standards both specify that their respective double complex types must have the same alignment and layout as an array of two doubles. This means that you can get away with passing arguments as a void * and have your routines be (relatively) easily callable from either language, and this is an approac... |
3,332,777 | 3,332,883 | What is the most basic class in C++ | I hope this question is not too silly, but what is the most basic class in standard C++?
object? Object?
class MyObject : public object{ ...
and I get "Expected class-name before token{"
Is there any map, diagram or image that shows standard c++ classes inheritance?
Something like this but for C++ ?
| In Cocoa, the NSObject class is fundamental to the framework but not to the Objective-C language itself. In Objective-C, it is possible to create a root class by not deriving from anything (but in order to make it work you'll probably have to hack your way through runtime calls).
Similarly, some C++-based frameworks ma... |
3,332,803 | 3,333,772 | False sharing and stack variables | I have small but frequently used function objects. Each thread gets its own copy. Everything is allocated statically. Copies don't share any global or static data. Do I need to protect this objects from false sharing?
Thank you.
EDIT: Here is a toy program which uses Boost.Threads. Can false sharing occur for the field... | False sharing between threads is when 2 or more threads use the same cache line.
E.g. :
struct Work {
Work( int& d) : data( d ) {}
void operator()() {
++data;
}
int& data;
};
int main() {
int false_sharing[10] = { 0 };
boost::thread_group threads;
for (int i = 0; i < 10; ++i)
... |
3,333,097 | 3,337,340 | RTSP Client with Qt GUI | does somebody have instructions, how do to make a RTSP client with Qt? I have already heard of live555, but I don't know how to link it with Qt.
Is there another way?
I would like to do it with Qt, so that it also runs under Linux and other platformens.
| To have a RTSP client, you need to process the RTSP protocol one way or another.
Live555 is one way to do that, it is just a C++ library that can be linked with other applications, including Qt. It is certainly possible to link Live555 with Qt.
Another way would be to write your own RTSP client based off the RFC spec ... |
3,333,247 | 3,333,268 | Is it OK to have a single configuration, rather than separating Debug and Release (in our case)? | We develop a product for internal customers. We don't have a QA team, and don't use assertions. Performance is important, application size isn't.
Is it a good idea to have a single configuration (instead of separating Debug and Release), which will have the debug information (pdbs), and will also do the performance opt... | Keep both. There is a reason for having two configurations! Use the Debug one for debugging and the Release one for every-day use.
THe cons of "merging" configurations are obvious - you wont get the best optimizations you could with clean Release configuration and debugging will be awkward. The few seconds (or minutes)... |
3,333,293 | 3,337,663 | Allocate chunk of memory for array of structs | I need an array of this struct allocated in one solid chunk of memory. The length of "char *extension" and "char *type" are not known at compile time.
struct MIMETYPE
{
char *extension;
char *type;
};
If I used the "new" operator to initialize each element by itself, the memory may be scattered. This is how I tried ... | I'll put aside the point that this is premature optimization (and that you ought to just use std::string, std::vector, etc), since others have already stated that.
The fundamental problem I'm seeing is that you're using the same memory for both the MIMETYPE structs and the strings that they'll point to. No matter how y... |
3,333,361 | 3,333,565 | How to cancel waiting in select() on Windows | In my program there is one thread (receiving thread) that is responsible for receiving requests from a TCP socket and there are many threads (worker threads) that are responsible for processing the received requests. Once a request is processed I need to send an answer over TCP.
And here is a question. I would like to... | You need to use something similar to safe-pipe trick, but in your case you need to use a pair of connected TCP sockets.
Create a pair of sockets.
Add one to the select and wait on it as well
Notify by writing to other socket from other threads.
Select is immediately waken-up as one of the sockets is readable, reads al... |
3,333,459 | 3,333,561 | Embeddable formula interpreter | I need something to embed in my C/C++ program to interpret formulas of the like x*log(x) or sin(x). I would like something small and simple, otherwise I can just embed Python, or Ch, or Scheme, or you name it. But all I need is simple formulas. I have searched the web without luck. Although I don't require it, performa... | Lua - is by far the simplest to embed and use and there is a very small and very fast version with a JIT: http://luajit.org/
|
3,333,524 | 3,334,235 | Visual Studio 2008: Use external Debug-DLL for Debug-Run and external Release-DLL for Release-Run | Short version:
If running a program from VS2008 in Release mode, I want it to use
pathA\externaldll.dll.
If running a program from VS2008 in Debug mode, I want it to use
pathB\externaldll.dll
Long version:
I have a programm that is linked against external dll-files (VTK). I have built the external application myself ... | Actually there is a built-in and easy way:
The "Environment"-Variable within "project settings"/Debugging.
So setting the Environment-Variable to
PATH=C:\Paraview\ParaView-3.8.0\gen\bin\$(ConfigurationName);%PATH%
for the project to be exectued does the trick.
The question was answered several times here, I just didn'... |
3,333,567 | 3,333,635 | CPP templated member function specialization | I'm trying to specialize the member function moment() only (not the hole class) like this:
template<class Derived, class T>
class AbstractWavelet {
public:
[...]
template<bool useCache>
const typename T::scalar moment(const int i, const int j) const {
return abstractWaveletSpecialization<Derived, T, useCache... | Can you try that->template momentImpl<true>(i, j); please ?
It's a way to tell the compiler "Hey, the thing after -> is a templated call"
|
3,333,604 | 3,333,790 | Load c++ memory file into Python | I have a file that in C++ I load into array using below code:
int SomeTable[10000];
int LoadTable()
{
memset(SomeTable, 0, sizeof(SomeTable));
FILE * fin = fopen("SomeFile.dar", "rb");
size_t bytesread = fread(SomeTable, sizeof(SomeTable), 1, fin);
fclose(fin);
}
The file is binary code of 10000 inte... | Let's write an array into a file using a short C code:
int main ()
{
FILE * pFile;
int a[3] = {1,2,3};
pFile = fopen ( "file.bin" , "wb" );
fwrite (a , 1 , sizeof(a) , pFile );
fclose (pFile);
return 0;
}
The binary file can be loaded directly into a python array
Python 2.6.5 (r265:79063, Apr 16 2010, 13:0... |
3,333,636 | 3,333,671 | Should I use an API/ABC when designing a class used by several in C++? | I am about to add a class X that will be used by my three previously designed classes (A, B and C).
The new class X will contain data and functions for new features as well as provide services to the classes that use it to hide lower layers. The problem is that A, B and C will use class X quite differently, that is, u... | Are you sure all these functions belong to the same class X? Think about separating different functionality into different classes:
http://en.wikipedia.org/wiki/Low-Coupling_/_High-Cohesion_pattern
But without knowing what the functions of X are it is difficult to help further.
|
3,333,976 | 3,873,901 | How can I return a temporary from my specialized std::max? | Hallo!
I want to specialize std::max for a platform-specific fraction type.
The prototype for the system-specific max I want to use looks like this:
fract builtin_max(fract a, fract b);
My idea for a specialized std::max looks like this:
template <> inline
const fract& std::max<fract>(const fract& a, const fract& b) {... | My solution was to do it just like this:
fract std::max(fract a, fract b) {
return builtin_max(a, b);
}
Super simple, and works just like I want it :)
|
3,333,981 | 3,356,836 | web page in C++ desktop application | I have a Borland C++ application and I am new to desktop applications.
I would like in one of the pages to embed a web page of another application of mine that the URL is something like:
www.mysite.com/thepage
In HTML I can use <IFrame>. How can I do it in Borland C++?
| The VCL in Borland/CodeGear/Embarcadero C++Builder has a native TCppWebBrowser component that is a wrapper for the Internet Explorer ActiveX control. Or you can embed the control manually. If you do not want to rely on Internet Explorer, FireFox has a similar control available, IIRC. Or there are third-party VCL web... |
3,334,011 | 3,727,290 | Compiling Quantlib via SWIG for C# | Anyone have any experience using SWIG? I am currently researching QuantLib and saw that C# code can be generated using SWIG. We are exploring options to create a combined library of financial functions using QuantLib and a proprietary closed source library (which will probably be made available as .Net dlls). The idea... | So it would seem that the C# bindings for SWIG are available. One needs to browse the SVN repository or list of files on SouceForge to find them.
The SWIG folder contains several subfolders, depending on your language of choice, in my case C# was the one that interested me. You will need to download SWIG first and it t... |
3,334,093 | 3,334,129 | Use of declarations in C++ templates? | In a template-declaration, explicit specialization, or explicit instantiation the init-declarator-list in the declaration shall contain at most one declarator. When such a declaration is used to declare a class template,no declarator is permitted.
Any one explain this ?
For me it is necessary that i need to check the ... | That means you cannot write
template <class T> class A{} a, b;
or similarly
template <class T> A<T>::a=0, A<T>::b=1;
(imagine what would a, b be in the first case). For a more thorough explanation of declarators, see chapter 8 of the standard.
|
3,334,170 | 3,341,261 | Is there Python Clang wrapper in the vein of pygccxml which wraps GCC-XML? | For a long time now I've been using pygccxml to parse and introspect my C++ source code: it helps me to do some clever code-generation during our build process.
Recently I've read a lot about the benefits of the LLVM stack, and especially the benefits that the LLVM Clang parser brings to C++ compilation. I am now wond... | After further digging I found that in the LLVM 2.7 release there could be the beginings of something useful:
In the LLVM 2.7 time-frame, the Clang team has made many improvements....
CIndex API and Python bindings: Clang now includes a C API as part of the CIndex library. Although we make make some changes to the API ... |
3,334,285 | 3,334,297 | compiling error with vector in c++ | I'm stuck! I have this very simple test code and I can't get it to compile! I have used the same code many times before but now it won't work!
I have this simple program
#include <vector>
#include <iostream>
#include "Rswap.h"
using namespace std;
int main(){
Rswap test();
cin.get();
return 0;}
And then the rswap.... | At the point you #include "Rswap.h", you haven't declared using namespace std; yet, so the reference to vector in Rswap.h must be qualified with a namespace. Simply declare the vector with a namespace prefix.
class Rswap{
public:
std::vector<int>V;
Rswap();
};
Also, I suggest you #include <vector> from Rswap.h rat... |
3,334,293 | 3,396,583 | ORPG Engine Development, structuring the code (C++, 2D) | I've been working on a game 2d ORPG Engine with a friend of mine, however we're having some troubles organizing and structuring the code.
I could use some pointers, guides, tutorials, etc. on how to keep the code flexible, extendible and maintainable.
Thanks for your time, Xeross
| I'll just mark this as correct as the subject is too vague, my apologies, thanks for everyone replying though :)
|
3,334,464 | 3,334,655 | Pass a non static Function Pointer of a Class as Parameter | I need a Function like that:
class Class_A
{
...
bool ShowVariableConstituents( CString ( * ValueOutput )( double ) );
...
}
bool Class_A::ShowVariableConstituents( CString ( * ValueOutput )( double ) )
{
double dUncalculatedValue;
....
if( ValueOutput )
{
CString strValue = Val... | To make it possible to pass pointers to member functions you should modify your function as follows:
bool ShowVariableConstituents( CString ( Class_A::* ValueOutput )( double ) )
But it will not help since you want to pass the pointer to Class_B::ValueOutput and Class_A doesn't know anything about Class_B.
Your option... |
3,334,645 | 3,334,690 | How to change programming layout after setting it at the first execution? | When starting Visual Studio 2008 you are asked to choose a programming layout (preset?), which can be C++ or C# (or generic?). Few months ago I choose the C++ preset because I was working on a C++ project, while now I'm working to a C# project. Is there a way to reset the Visual Studio layout to C#?
| Go to:
Tools > Import and Export Settings
Import selected environment settings
Yes, save my current settings (if you want to backup current settings; No, if you don't want to)
Choose one of the following under Default Settings:
General
JavaScript
Visual Basic
Visual C#
Visual C++
Web Development
Web Development (Code... |
3,334,984 | 3,335,334 | How to take pair-like function arguments | I'm writing a class which will be used to perform some calculations on a set of values, with scaling based on a per-value weight. The values and weights are supplied to the class' constructor. The class will be part of an internal library, and so I want to put as few restrictions as possible on the clients data structu... | Iterators are fine. However, relying on the types having public members called first and second is a pretty big restriction.
In C++0x, access to std::pair members will be unified with the access patterns of std::tuple, via a get function. This would allow you to overload and specialize the get function for arbitrary ty... |
3,335,274 | 3,336,042 | Extend the Visual Studio C++ Build Process | A found an article (Extend the Visual Studio Build Process) that explained how to override build targets in a C# project file. I tested this, and it seems to work well. However, what I really want to do is override a build target in a C++ project (with Visual Studio 2005). The problem is that C++ projects use differ... | In Visual Studio 2005 there are no build "targets" for C++ builds as the C++ build system does not use MSBuild.
However, VC++2005 defines the Pre-Build, Pre-Link, Post-Build Events as well as the ability to add a Custom Build Step for non-standard files.
You may be able to achieve what you want using these settings.
No... |
3,335,309 | 3,335,468 | Windows Mobile Native Code - jstring to LPCTSTR | I have a Java app which needs to interact with the camera on a Windows Mobile device. I have written the Java Code and the Native code and it all works fine. The problem I am having now is that I want to start passing variables from Java to the Native code, e.g. the directory and file name to use for the photo.
The n... | I think you should try GetStringChars() instead of GetStringUTFChars()
According to this page it returns the Unicode String.
WindowsCE and Windows mobile use UNICODE exclusively so LPCTSTR
is actually LPCWSTR (Long Pointer to Const WideChar String)
SHCAMERACAPTURE shcc;
ZeroMemory(&shcc, sizeof(shcc));
shcc.cbSize = ... |
3,335,847 | 3,340,900 | Reading single byte with Asio::read | Is it possible to read a single byte via asio::read?
I'm getting a single byte response and it seems wasteful to use the current buffering code:
//Read the 1 byte reply
char buffer[1];
size_t bytesRead = asio::read(s, asio::buffer(buffer, 1));
if(bytesRead < 1) return false;
Thanks.
| No, passing a buffer of a single byte is the only way.
Also it isn't wasteful. What is it that you're concerned about wasting?
|
3,335,951 | 3,336,008 | How to get handles to all windows of another application | in my application i have timer, in TimerProc i want to get handles of all windows(main and child) of the another application that has focus. I have no idea how to do that because i don't understand functions like GetNextWindow or GetParent and Z-oder of windows and i can't find anywhere very detailed explanation of how... | Use GetForegroundWindow() function - it returns the HWND of the window the user currently is working with.
Then having this handle you can retrieve childs in such a way:
HWND a_hWnd = (HWND)hParent;
HWND a_FirstChild = NULL;
a_FirstChild = ::GetWindow(a_hWnd, GW_CHILD);
if (a_FirstChild != NULL)
{
HWND a... |
3,336,054 | 3,336,174 | Building C++ CLR app for Platform Toolset v90 in VS2010 requires Visual Studio 2008 | I've got a shiny new laptop with the latest Dev tools installed such as Visual Studio 2010.
Now I've got a task to build a C++ CLR app targeting the 2.0 runtime (this is well outside my comfort zone). So I've specifed the v90 Platform Toolset but when I build I get:-
error MSB8010: Specified platform toolset (v90) re... | Part of the problem is that VS2010 redid how compiling in c++ (cli or not) works. It now uses the MSBuild structure but I believe what you are trying to do will need the VCBuild framework that is not in 2010.
You may be able to get away with using the Visual Studio 2008 express to build. If not you should only nee... |
3,336,198 | 3,336,242 | Segfault on using transform on a vector of pointers to an abstract class | I experience a segfault on the following code:
I have an abstract class A with a method
virtual bool Ok() const;
Now, I have the following vector
std::vector<A*> v;
filled with several pointers to existing child objects. I want to accumulate the results of the Ok() method as follows:
std::vector<bool> results;
std::t... | The results vector is empty, and transform does not know that you want the results pushed onto it rather then overwriting an existing sequence.
Either initialise the results vector with the correct size:
std::vector<bool> results(v.size());
or use a "back insert" iterator to push the results onto the empty vector:
std... |
3,336,231 | 3,337,247 | Set an icon for a file type | I have used Qt Creator and created my.exe file and a new extension ".newext" and have manually associated .newext files to the my.exe like this.
The exe file has as its icon which is square figure and named myIcon.ico. I have described in myapp.rc file the icon like this:
IDI_ICON1 ICON DISCARDABLE ... | I don't know if it is possible at all. I haven't seen any application doing that. What you would have to do is to discover how the Windows creates these icons and run this mechanism to create one, then associate generated icon to your file type. It may be somewhere deep inside the Windows.
My advise is not don't do thi... |
3,336,261 | 3,371,509 | Why might ProcessMessages throw a C++ Exception? | While maintaining an old product, I came across an error that results in the screen being filled up with hundreds of message boxes saying 'C++ Exception' and nothing else. I traced the problem to the following line:
Application->ProcessMessages();
I understand the purpose of this line, to process all the messages in ... | This is mostly a guess, but from what I see, it's a problem caused by a large back log of messages. During the large computation, the application becomes unresponsive for number of seconds while a large number of messages are thrown on the queue (many of these are timer events). When the computation finishes and Proc... |
3,336,385 | 3,336,452 | "case sequence" in python implemented with dictionaries | i have implemented a function:
def postback(i,user,tval):
"""functie ce posteaza raspunsul bazei de date;stringul din mesaj tb sa fie mai mic de 140 de caractere"""
result = {
1:api.PostDirectMessage(user,'Trebuie sa-mi spui si marca pe care o cauti'),
2:postmarket(user,tval),
3:api.Pos... | It executes all three cases because you define the result dict that way! You call all three functions and assign them to the keys 1, 2, 3.
What you should instead is something like this:
functions = {
1: lambda: api.PostDirectMessage(user,'Trebuie sa-mi spui si marca pe care o cauti'),
2: lambda: postmarket(use... |
3,336,389 | 3,338,050 | Is there a way to detect when all child items within a QTreeWidgetItem have been marked 'hidden'? | Is there a preferred way to detect when all of a QTreeWidgetItem's children are marked as hidden? Currently, I'm iterating over all of them every time any of them are hidden.
| Keep a counter of hidden items and change the value of the counter if an item changed its state of hidden-ness. So each time you use the information you do not iterate over all items!
|
3,336,408 | 3,336,504 | How to understand everything regarding a Simple Program creation? | I have referred quite a few books on C, C++, etc. in fact i have even read the Dragon book on Compilers.
But my basic doubt remains,
is there any link or book i can read which explains a simple C program creating from writing source code in a Editor to Compilation to Linking?
Would appreciate an internet link is provi... | As example this is for *nix OS: http://www.thegeekstuff.com/2009/09/how-to-write-compile-and-execute-c-program-on-unix-os-with-hello-world-example/. (there are source code edited by text editor, not by IDE)
I found this link using google with "C hello world howto" request. You can try similar requests If you need Windo... |
3,336,499 | 3,336,521 | virtual desctructor on pure abstract base class | I have
struct IMyInterface
{
virtual method1() = 0;
virtual method2() = 0;
};
GCC insists that I have
struct IMyInterface
{
virtual method1() = 0;
virtual method2() = 0;
virtual ~IMyInterface(){};
};
I dont see why. A pure interface is all about the interface (duh). The destructor is part of the intern... | According to the C++ spec, yes.
You need to declare the destructor virtual because otherwise, later
IMyInterface * ptr = getARealOne();
delete ptr;
won't call the destructor on the derived class (because the destructor isn't in the VTable)
It needs to be non-pure because base class destructors are always calle... |
3,336,555 | 3,336,568 | Using QtMobility/Location, a Symbian Qt C++ application runs in emulator but not on device | I have a Symbian Qt C++ mobile application that runs fine in the emulator but when the application is compiled into a SIS file and installed on the phone, it installs successfully but does not start and fails silently without any message.
The application uses QtMobility 1.0.1 to access the Location API.
| Found that the issue I'm facing is related to the following bug: https://bugreports.qt.io/browse/QTMOBILITY-360
which is caused by using Qt Mobility 1.0.1 APIs, which are linked against a library (LBT) that is not available on Symbian 5th edition devices (but will be available on Symbian^3)
When I reverted to using the... |
3,336,859 | 3,337,218 | Testing a c++ class for features | I have a set of classes that describe a set of logical boxes that can hold things and do things to them. I have
struct IBox // all boxes do these
{
....
}
struct IBoxCanDoX // the power to do X
{
void x();
}
struct IBoxCanDoY // the power to do Y
{
void y();
}
I wonder what is the 'best' or maybe its jus... | If you are using the 'I' prefix to mean "interface" as it would mean in Java, which would be done with abstract bases in C++, then your first option will fail to work....so that one's out. I have used it for some things though.
Don't do 'd', it will pollute your hierarchy. Keep your interfaces clean, you'll be glad y... |
3,337,104 | 3,338,959 | I'm about to open source a C++ project on Sourceforge. Can I get some tips on code organization? | I'm about to upload a project I've been working on onto Sourceforge under the GPL, and was hoping to get some advice on how to organize the code in a fashion that is easy to understand and use by any developers that might look at it, that works well with git, and the way Sourceforge presents things.
My projects is a cr... | In general, separate your work from that of third parties. On the most basic level, your root folder could look like:
|- GUI
|- Library
|- Third-party
|- lib
|- source
I separated the "third-party" folder into two subfolders for the purposes of license compliance and ease of use. How exactly you distribute t... |
3,337,126 | 3,337,192 | In C++ why can't I write a for() loop like this: for( int i = 1, double i2 = 0; | or, "Declaring multiple variables in a for loop ist verboten" ?!
My original code was
for( int i = 1, int i2 = 1;
i2 < mid;
i++, i2 = i * i ) {
I wanted to loop through the first so-many squares, and wanted both the number and its square, and the stop condition depended on the square. This code seems to ... | int i = 1, double i2 = 0; is not a valid declaration statement, so it cannot be used inside the for statement. If the statement can't stand alone outside the for, then it can't be used inside the for statement.
Edit:
Regarding your questions about comma operators, options 'A' and 'B' are identical and are both valid. ... |
3,337,493 | 3,337,631 | Display PNG on Visual Studio form | I'm working on a C++ application in Visual Studio (non-MFC) and was surprised to find that I can't add a PNG image to a dialog in the designer which seems a little backward as I can in most other IDEs that I've used. So either a) there is something I'm missing or b) there is a way to do it with code. I'm hoping that it... | Calling the dialog template editor a "designer" would be rather a stretch. It hasn't changed in the past 15 years or so, neither has the underlying API. An API that doesn't support PNGs, only BMPs. Getting PNG support is possible, GDI+ is available on any Windows version since 2000. But you have to code it yourself... |
3,337,989 | 3,338,043 | Add elements and clear a vector of pointers in C++ | I would like to add 2 elements to a vector<Node*> and then clear all the elements and release the memory.
Does this code do that in a right way?
#include <stdlib.h>
#include <iostream>
#include <vector>
using namespace std;
class Node {
public:
int value;
// ...and some other fields and methods...
};
int mai... | It looks fine to me. There are a few things that I'd change (subjectively):
*i = NULL; // This is unnecessary.
Then I'd avoid reusing n (actually, I'd avoid it entirely):
v.push_back(new Node);
v.back()->value = 20;
v.push_back(new Node);
v.back()->value = 52;
Also, you may want to consider smart pointers to track ... |
3,338,151 | 3,338,204 | Creating a C++ COM client for C# COM server | I have a C# ComServerProject that implements an out-of-proc COM server, and I've selected the option "Make assembly COM-visible" on server project's "Assembly Information" dialog. In the same solution I have a C++ ComClientProject that should use the COM interface defined in ComServerProject. However, I don't know how... | Use Tlbexp on the generated assembly to create the .tlb.
Something like:
tlbexp ComServerProject.dll /out:ComServerProject.tlb
|
3,338,172 | 3,341,881 | How commonly used are the xilinx chips? | I'm beginning to learn embedded with C (and maybe some C++) and someone from the office said they're willing to donate a free xilinx chip they've got sitting on their shelf. I was thinking more along the lines of an Arduino, especially that the Arduino tutorials and sample projects are abundant.
Can someone confirm h... | You are comparing chalk and cheese. Xilinx is a company, not a chip and Arduino is an open development platform based on Atmel AVR microcontroller.
Also 'a chip' alone is probably useless to you; it will have to be assembled onto a development board with subsidiary components and power supplies etc.
Xilinx make FPGAs ... |
3,338,756 | 3,338,797 | erase max element from STL set | This is a follow-up on a previous question I had ( Complexity of STL max_element ).
I want to basically pop the max element from a set, but I am running into problems.
Here is roughly my code:
set<Object> objectSet;
Object pop_max_element() {
Object obj = *objectSet.rbegin();
set<Object>::iterator i = objectSe... | You're pretty close, but you're trying to do a little too much in that iterator assignment. You're applying the post-decrement operator to whatever end returns. I'm not really sure what that does, but it's almost certainly not what you want. Assign the result of end to i, and then decrement it to get the last element o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.