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 |
|---|---|---|---|---|
2,242,966 | 2,242,989 | MIDL doesn't want me to define a HRESULT-less function! | I'm writing a custom ATL ActiveX component, but I'm having this little weeny problem: Visual Studio insists that every function defines in the *.idl file has to have a HRESULT return type, even though I want to have a ULONG return type.
[id(3), helpstring("method addh3h3")] ULONG addh3h3([in] ULONG x, [in] ULONG y);
I... | Add the [local] attribute to either the interface or the method. (from http://support.microsoft.com/kb/192626).
|
2,243,786 | 2,243,792 | Initializing members with members | This is a problem I come across often. The following examples illustrates it:
struct A {
int m_SomeNumber;
};
struct B {
B( A & RequiredObject );
private:
A & m_RequiredObject;
};
struct C {
C( );
private:
A m_ObjectA;
B m_ObjectB;
};
The implementation of the constructor of C looks something... |
Since the order of initialization is not defined
On the contrary, it is well-defined. The order of initialization is equal to the order in which the member variables are declared in your class (and that’s regardless of the actual order of the initialization list! It’s therefore a good idea to let the initialization l... |
2,243,814 | 2,253,538 | Is it possible to use different tags files for omnicomplete and general tag browsing in Vim? | I've been using ctags in Vim for years, but I've only just discovered omnicomplete. (It seems good.)
However, I have a problem: to get omnicomplete working properly I have to use the --extra=+q option when generating the tags, which is fine, but this then changes the behaviour of general tag browsing in ways that I do... | OK, I think I've actually come up with an answer to my own question.
Firstly, I generate two tags files: tags_c_vim and tags_c_omni.
In my _vimrc I have:
let tags_vim='tags_c_vim'
let tags_omni='tags_c_omni'
exe "set tags=".tags_vim
to setup some variables pointing to the different tags files, and to set the "vim" ta... |
2,243,819 | 2,243,899 | Is multiple inheritance acceptable for nodes in a tree? | I was wondering:
With a tree, the root can have multiple children and no id. All nodes (except the root) have an id and the leaf nodes can not have children. It is fixed what type must be used for each depth. So the leaves are always of the same type and so are the parents of the leaves.
Since the root and the nodes ca... |
Or is there a better way to implement this?
IMHO, your design creates classes for stuff that are best treated as object instances. At a class level I do not see the need to differentiate between Level1 nodes and Level2 nodes.
Use a design that is simple. Ask yourself, if this design has any potential benefits or not ... |
2,243,953 | 2,244,996 | Memory allocation for _M_start and _M_finish in a vector | I'm defining a vector as:
vector< int, MyAlloc< int> > *v = new vector< int, MyAllooc< int> > (4);
MyAlloc is allocating space for only 4 ints. Memory for _M_start, _M_finish, and _M_end_of_storage is being allocated on the heap before the memory for the 4 ints. But who is allocating this memory for _M_start, _M_finis... | When you create the vector, it allocates room for the vector's member variables (the _M ones) wherever you place the vector. If you use new, it allocates space for these variables on the heap. With local variables, the compiler makes space for them in the current stack frame. If you make the vector a member of a class,... |
2,244,010 | 2,244,119 | Moving C++ objects, especially stl containers, to a specific memory location | I am working with a memory manager that, on occasion, wants to defragment memory. Basically, I will go through a list of objects allocated by the memory manager and relocate them:
class A {
SomeClass* data; // This member is allocated by the special manager
};
for(... each instance of A ...)
a.data = memory_man... | Everytime you insert a new key,value pair the map will allocate a node to store it. The details of how this allocation takes place are determined by the allocator that the map uses.
By default when you create a map as in std::map<K,V> the default allocator is used, which creates nodes on the heap (i.e., with new/delet... |
2,244,135 | 2,244,178 | Initialize array variable in structure | I ended up doing like this,
struct init
{
CHAR Name[65];
};
void main()
{
init i;
char* _Name = "Name";
int _int = 0;
while (_Name[_int] != NULL)
{
i.Name[_int] = _Name[_int];
_int++;
}
}
| Give your structure a constructor:
struct init
{
char Name[65];
init( const char * s ) {
strcpy( Name, s );
}
};
Now you can say:
init it( "fred" );
Even without a constructor, you can initialise it:
init it = { "fred" };
|
2,244,580 | 2,248,090 | Find Boost BGL vertex by a key | I am looking for a way to access vertex properties by using a key instead of vertex reference itself.
For example, if I have
class Data
{
public:
std::string name;
unsigned int value;
};
typedef boost::adjacency_list< boost::vecS, boost::vecS, boost::directedS, Data > Graph;
typedef boost::graph_traits<Gra... | I think I have found such mechanism. It is called labeled_graph and is a part of BGL.
Instead of using adjacency_list, one can use a predefined wrapper labeled_graph:
typedef boost::labeled_graph<
boost::adjacency_list< boost::vecS, boost::vecS, boost::directedS, Data >,
std::string
> Graph;
After defining a g... |
2,244,599 | 2,247,119 | Building an FPS in OpenGL: My gun is being clipped agains the frustum | I'm building a first person shooter using OpenGL, and I'm trying to get a gun model to float in front of the camera. I've ripped a model from Fallout 3 using a resource decompiler (converted to .obj and loaded in).
However, this is what it looks like on the screen:
Half the gun's triangles are clipped to what appears... | From the perspective (no pun intended) of OpenGL, the frustrum is just another matrix. You should be able to push the projection matrix, call gluPerspective (or glFrustrum, if you're adventurous) to set znear to a very small value, draw the gun, then pop the projection matrix and draw the rest of the scene (beware, how... |
2,244,863 | 2,245,025 | trying to make a simple grid-class, non-lvalue in assignment | I'm implementing a simple C++ grid class. One Function it should support is accessed through round brackets, so that I can access the elements by writing mygrid(0,0). I overloaded the () operator and i am getting the error message: "non-lvalue in assignment".
what I want to be able to do:
//main
cGrid<cA*> grid(5, 5);... | As Bill remarked, the operator shouldn't be const. I believe this is the reason for the compilation error (even if the error reported seems different). The compiler only encounters the error at the assignment line because it is a template class.
To be clear, you can't have a const method return a reference to a non-c... |
2,244,890 | 2,254,350 | Qt - QScrollArea widget clipping contents | I'm trying to add scrolling to a drag and drop example source that I modified. The example simply draws several draggable QLabel widgets. I was modifying it in a way that a larger number of various different length widgets would be created.
I made a class that would be called by main and would contain the scrolling wid... | The minimum size of the widget inside the scroll area was smaller than its content, so only what's inside that area is drawn. I used larger values for setMinimumSize() and the problem was solved.
|
2,245,100 | 2,245,227 | Dynamic programming algorithm N, K problem | An algorithm which will take two positive numbers N and K and calculate the biggest possible number we can get by transforming N into another number via removing K digits from N.
For ex, let say we have N=12345 and K=3 so the biggest possible number we can get by removing 3 digits from N is 45 (other transformations w... | The trick to solving a dynamic programming problem is usually to figuring out what the structure of a solution looks like, and more specifically if it exhibits optimal substructure.
In this case, it seems to me that the optimal solution with N=12345 and K=3 would have an optimal solution to N=12345 and K=2 as part of t... |
2,245,233 | 2,245,570 | iterator_range in header file | I want to specify in a header file that the input to a function will be an iterator_range, and the iterator can be dereferenced to obtain an int. What is the best way to do this? I do not want to say iterator_range<std::vector<int>::iterator> as this binds the implementation to use std::vector<int>.
Would appreciate an... | A common way to do this is to make the range a template parameter and then let the usage you make of it be the "concept check":
template<class SinglePassRange>
void func(SinglePassRange const & nums)
{
typedef typename boost::range_iterator<SinglePassRange>::type It;
for(It it = nums.begin(), e = nums.end(); it !... |
2,245,322 | 2,245,408 | how to do this in c++gui | I want to write a program for UNIX in C++ with GUI (planning it to be Qt). I haven't learned the Qt library yet btw. I want the program to be like a world map that will be divided into many cells like a grid(the grid shouldn't be visible) and when i start to ping some IP it will show me that IP location on the world ma... | It actually is pretty easy. Using Qt and its GraphicsView framework. Just display a big world map and draw a dot where you want.
However, converting lon:lat coordinates to x:y needs some basic maths (you can find formulaes by googling. It will depend on the projection of your map).
Another possiblity is to use existing... |
2,245,330 | 2,245,459 | C++ Pass by value/reference | I have the following code snippet:
vector<DEMData>* dems = new vector<DEMData>();
ConsumeXMLFile(dems);
if(!udp_open(2500))
{
}
I want the ConsumeXMLFile method to populate the vector with DEMData objects built from reading an XML file. When ConsumeXMLFile returns, the dems vector is empty. I think I'm run... | Are you at any point reassigning the pointer that is passed into the function? In other words, does your function look anything like this:
void ConsumeXMLFile(vector<DEMData>* dems)
{
// ... some code ...
dems = new vector<DEMData>();
// ...more code...
}
This is a common mistake that I see beginning C++ p... |
2,245,341 | 2,245,440 | C++ / templates / GCC 4.0 bug? | Provided the code below:
template<class _ResClass, class _ResLoader=DefaultLoader>
class Resource
: public BaseResource
{
private:
_ResClass data_;
public:
explicit Resource(const std::string& path)
: data_( _ResLoader::load< _ResClass >( path ))
{ };
};
Why would it fail but this one will work?:
tem... | load is a dependant name, so
data_( _ResLoader::template load< _ResClass >( path ))
for the same reason as typename is needed when a dependant name is a type.
|
2,245,344 | 2,245,496 | c++ fatal error c1083 project was fine before, what now? | I have a (com) c++ project, which uses a (.net) c++ dll. The project was compiling and running ok.
Now, all I did was make changes to the dll, and I'm getting a fatal error c1083- cannot open include file stdafx.h - when recompiling my (com) project.
What can this mean?
| Look for your stdafx.h. Here are the possibilities:
If it isn't missing, try restarting you machine. You could also use sysinternals' handle.exe to find out who's holding that file.
If it is missing, create it.
On the other hand, it may be possible that your project did not originally use pre-compiled headers and the ... |
2,245,464 | 2,272,743 | boost local_date_time math wrong? | I'm using Boost's datetime library in my project. I was very happy when I discovered that it has time duration types for hours, days, months, years, etc, and they change their value based on what you're adding them to (i.e. adding 1 month advances the month part of the date, it doesn't just add 30 days or somesuch). ... | I think the problem is in the asker's conception of what a day is. He wants it to be a 'date' day here, rather than 24 hours, but that is not a reasonable thing to ask for.
If working in local time, one is bound to encounter peculiar effects. For example, what do you expect to happen if, in a timezone that puts clocks ... |
2,245,577 | 2,245,681 | Mapping a thread number to a (non sequential) position in an array | I would like to map a thread_id. This in C/CUDA but it is more an algebraic problem that I am trying to solve.
So the mapping I am trying to achieve is along the lines:
Threads 0-15: read value array[0]
Threads 16-31: read value [3]
Threads 32-47: read value [0]
Threads 48-63: read value [3]
Threads 64-79: read valu... | This will work in C:
3 * ((n>>4 & 1) + (n>>5 & ~1))
where n is the thread number.
I made the assumption here that the pattern continues beyond 128 as: 0,3,0,3,6,9,6,9,12,15,12,15,etc.
Edit:
This form, without bitwise operations, may be easier to understand:
6 * (n/64) + 3 * ((n/16) % 2)
It will give the same results.... |
2,245,648 | 2,245,679 | Function argument already initialized in function declaration C++ | So here's my question in the function declaration there is an argument and it is already initialized to a certain value. What are the procedures to call this function and use that default value, or is it just a way to document code, telling other programmers what you expect them to use as a value for the parameter? Th... | If I understand your question correctly, simply calling SetSection with no parameters will do.
SetSection();
The above call gets translated (for lack of a better term) to:
SetSection(XML);
|
2,245,664 | 2,245,983 | What is the type of string literals in C and C++? | What is the type of string literal in C? Is it char * or const char * or const char * const?
What about C++?
| In C the type of a string literal is a char[] - it's not const according to the type, but it is undefined behavior to modify the contents. Also, 2 different string literals that have the same content (or enough of the same content) might or might not share the same array elements.
From the C99 standard 6.4.5/5 "String... |
2,245,780 | 2,245,863 | Order of operator overload resolution involving temporaries | Consider the following minimal example:
#include <iostream>
using namespace std;
class myostream : public ostream {
public:
myostream(ostream const &other) :
ostream(other.rdbuf())
{ }
};
int main() {
cout << "hello world" << endl;
myostream s(cout);
s << "hello world" <<... | rvalues can't be bound to non-const reference. So in your example the temporary of type ostream can't be the first argument of free operator<<(std::ostream&, char const*) and what is used is the member operator<<(void*).
If you need it, you can add a call such as
myostream(cout).flush() << "foo";
which will transform... |
2,246,096 | 2,246,125 | How can I turn off ASSERT( x ) in C++? | I suspect some ASSERTION code is having side effects. I'd like to switch off ASSERT without making any other changes to how my code is compiled. I'm using MSVS2008. Switching from debug to release won't do as that will alter how memory is initialised.
| Put this at the top of your header files after the inclusions of cassert (or a include that includes cassert)
#undef assert
#define assert(x) ((void)0)
Which redefines the assert marco so that it expands to nothing.
|
2,246,104 | 2,246,282 | Auto-generating C++ code in a pre-build event using Visual Studio | I'm trying to use a pre-build event in Visual Studio (VS 2005 to be specific) to run a Python script which will automatically generate a .cpp file. The trouble I'm running into is that the compiler doesn't seem to know that this file is dirty and needs to be rebuilt until after the build has finished, which means that... | I use msvc 6.
Try...
Put the python script into the project
give it a custom build step that invokes python on it,
to create the cpp file.
Add the cpp file to your project and do a rebuild all.
This is how we do it with the Oracle Pro*C preprocessor.
It works fine.
|
2,246,220 | 2,247,624 | Debugging and killing apps on Mac OS X? | Hey all, I'm in the process of debugging a C++ app on mac os 10.5. Occasionally, I'll do something bad and cause a segfault or an otherwise illegal operation. This results in the app hanging for a while, and eventually a system dialog notifying me of the crash. The wait time between the "hang" and the dialog is signifi... | There's the CrashReporterPrefs app that comes with XCode (search for it with Spotlight; should be in /Developer/Applications/Utilities). That can be to set to Server Mode to disable the application 'Unexpectedly Quit' dialog too.
Here's another suggestion:
sudo chmod 000 /System/Library/CoreServices/Problem\ Reporter.... |
2,246,228 | 51,732,462 | Set Range of Bits in a ushort | Lets say I have a ushort value that I would like to set bits 1 to 4 inclusive (assuming 0 is the LSB and 15 is the MSB).
In C++ you could define a struct that mapped out specific bits:
struct KibblesNBits
{
unsigned short int TheStart: 1;
unsigned short int TheMeat: 4;
unsigned short int TheRest: 11;
}
Then ... | The fixed type answers here helped me get to a generic solution as originally requested. Here's the final code (with a getter bonus).
/// <summary>Gets the bit array value from the specified range in a bit vector.</summary>
/// <typeparam name="T">The type of the bit vector. Must be of type <see cref="IConvertible"/>.<... |
2,246,259 | 2,246,314 | Is there a way to have a single static variable for a template class (for all types) without breaking encapsulation | I need a way to have a single static variable for all kinds of types of my template class
template <class T> class Foo { static Bar foobar;};
Well, the line above will generate a Bar object named foobar for every type T, but this is not what i want, i basically want a way to declare a variable of type Bar, so every ... | Perhaps inherit the static member?
class OneBarForAll
{
protected:
static Bar foobar;
};
template <class T>
class Foo : public OneBarForAll
{
};
Lots of Foo<T>'s will be made, but only one OneBarForAll.
One potential problem with this is that there's nothing stopping other users of the code from inheriting from On... |
2,246,502 | 2,246,529 | C++ key input in Windows console | I'm currently developing various console games in Windows that won't really work using regular input via cin.
How can I (In a simple way using only standard windows libraries available in MSVC):
Make the program wait for a (specific?) key press and return the key ID (It would have to work for all keys including the ar... | AFAIK you can't do it using the standard C runtime. You will need to use something such as the Win32 function GetAsyncKeyState.
|
2,246,663 | 2,246,717 | Why is the 'this' keyword not a reference type in C++ |
Possible Duplicates:
Why ‘this’ is a pointer and not a reference?
SAFE Pointer to a pointer (well reference to a reference) in C#
The this keyword in C++ gets a pointer to the object I currently am.
My question is why is the type of this a pointer type and not a reference type.
Are there any conditions under which t... | See Stroustrup's Why is this not a reference
Because "this" was introduced into C++ (really into C with Classes) before references were added. Also, I chose "this" to follow Simula usage, rather than the (later) Smalltalk use of "self".
|
2,246,715 | 2,247,145 | Problems inheriting from a class in the same namespace in C++ | I was happily working in C++, until compilation time arrived.
I've got several classes inside some namespace (let's call it N); two of these classes correspond to one base class, and other derived from it. Each class has its own pair of .hpp and .cpp files; I think it'd look like:
namespace N{
class Base{
};
... | Derived.hpp:n: error: invalid use of incomplete type ‘struct N::Base’
This makes me think that you didn't #include "Base.hpp in the Derived.cpp source file.
EDIT: In your Derived.cpp, try changing the order of #includes to:
#include "base.hpp"
#include "derived.hpp"
// .. rest of your code ..
Like this:
// Derived.h... |
2,246,996 | 2,247,016 | C++ const : how come the compiler doesn't give a warning/error | Really simple question about C++ constness.
So I was reading this post, then I tried out this code:
int some_num = 5;
const int* some_num_ptr = &some_num;
How come the compiler doesn't give an error or at least a warning?
The way I read the statement above, it says:
Create a pointer that points to a constant integer
... | The problem is in how you're reading the code. It should actually read
Create a pointer to an integer where the value cannot be modified via the pointer
A const int* in C++ makes no guarantees that the int is constant. It is simply a tool to make it harder to modify the original value via the pointer
|
2,247,094 | 2,247,109 | What's the difference between C header files (.h) and C++ header files (.hpp)? | I noticed that the boost library uses header files of (.hpp).
I am curious since most source files I see use normal .h header files.
Could there be any special instances which warrant use of .hpp instead of .h ?
Thanks
| Just convention, nothing special. You can use any extension on include files, actually.
|
2,247,188 | 2,247,298 | Get number of bits in char | How do I get the number of bits in type char?
I know about CHAR_BIT from climits. This is described as »The macro yields the maximum value for the number of bits used to represent an object of type char.« at Dikumware's C Reference. I understand that means the number of bits in a char, doesn't it?
Can I get the same re... | If you want to be overly specific, you can do this:
sizeof(char) * CHAR_BIT
If you know you are definitely going to do the sizeof char, it's a bit overkill as sizeof(char) is guaranteed to be 1.
But if you move to a different type such as wchar_t, that will be important.
|
2,247,270 | 2,247,446 | Access violation exception when calling a method | I've got a strange problem here. Assume that I have a class with some virtual methods. Under a certain circumstances an instance of this class should call one of those methods. Most of the time no problems occur on that stage, but sometimes it turns out that virtual method cannot be called, because the pointer to that ... | Heap corruption is a likely candidate. The v-table pointer in the object is vulnerable, it is usually the first field in the object. A buffer overflow for some kind of other object that happens to be adjacent to the object will wipe the v-table pointer. The call to a virtual method, often much later, will blow.
Anot... |
2,247,289 | 2,247,348 | Best way to detect grouped words | A word is grouped if, for each letter in the word, all occurrences of that letter form exactly one consecutive sequence. In other words, no two equal letters are separated by one or more letters that are different.
Given a vector<string> return the number of grouped words.
For example :
{"ab", "aa", "aca", "ba", "bb"}... | Just considering one word, here is an O(n log n) destructive algorithm:
std::string::iterator unq_end = std::unique( word.begin(), word.end() );
std::sort( word.begin(), unq_end );
return std::unique( word.begin(), unq_end ) == unq_end;
Edit: The first call to unique reduces runs of consecutive letters to single lette... |
2,247,465 | 2,247,506 | Does using large libraries inherently make slower code? | I have a psychological tic which makes me reluctant to use large libraries (like GLib or Boost) in lower-level languages like C and C++. In my mind, I think:
Well, this library has thousands of
man hours put into it, and it's been
created by people who know a lot more
about the language than I ever will.
Their... |
Even if I only use one or two features of a large library, by linking to that library am I going to incur runtime performance overheads?
In general, no.
If the library in question doesn't have a lot of position-independent code, then there will be a start-up cost while the dynamic linker performs relocations on the l... |
2,247,558 | 2,247,607 | find string of N 1-bits in a bit-array | As the title sais I want to find a successive run of n one-bits in a bit-array of variable size (M).
The usual use-case is N <= 8 and M <= 128
I do this operation a lot in an innerloop on an embedded device. Writing a trivial implementation is easy but not fast enough for my taste (e.g. brute force search until a solut... | int nr = 0;
for ( int i = 0; i < M; ++i )
{
if ( bits[i] )
++nr;
else
{
nr = 0; continue;
}
if ( nr == n ) return i - nr + 1; // start position
}
What do you mean by brute force? O(M*N) or this O(M) solution? if you meant this, then I'm not sure how much more you can optimize things.
It's tru... |
2,247,567 | 2,247,694 | How might I obtain an IShellFolder from the active IShellView? | I'm trying to enhance a CFileDialog, and we're using the older version of it (the non-vista one that doesn't use IFileDialog). The older one does allow me to obtain an IShellBrowser, as well as (from that) the active IShellView.
What I cannot seem to come up with is a way to get "What IShellFolder does that IShellView... | I think I may have solved it in a round about fashion: I'm using CDM_GETFOLDERIDLIST, which returns the current PIDL, which is all I need. :D
|
2,247,697 | 2,286,076 | Fast asymmetric cypher for C++ application | I'm looking for a fast asymmetric cypher algorithm to be used in C++ program.
Our application accesses read-only data stored in archive (custom format, somewhat similar to tar), and I would like to prevent any modifications of that archive by asymmetrically encrypting archive index (I'm aware that this isn't a perfect ... | Okay, I've found what I've been looking for, and I think it is better than OpenSSL (for my purposes, at least).
There are two libraries:
libtomcrypt, which implements several cyphers (including RSA), and libtommath, that implements bignum arithmetics. Both libraries are in public domain, easy to hack/modify and have si... |
2,247,942 | 2,248,114 | Working program gets an Illegal instruction fault on 'clean machine'? | I have a program that works correctly on my development machine but produces an Illegal instruction fault when tested on a 'clean machine' where only the necessary files have been copied.
The program consists of my shared library, built from C++ sources and a C wrapper sample program that demonstrates the libraries usa... | You could try to compile explicitly for the i686 architecture (using -march=i686 option for gcc). Just in case you have some Core2-Specific instructions generated by the your compiler...
|
2,247,982 | 2,248,063 | c++ deque vs queue vs stack | Queue and Stack are a structures widely mentioned. However, in C++, for queue you can do it in two ways:
#include <queue>
#include <deque>
but for stack you can only do it like this
#include <stack>
My question is, what's the difference between queue and deque, why two structures proposed? For stack, any other struc... | Moron/Aryabhatta is correct, but a little more detail may be helpful.
Queue and stack are higher level containers than deque, vector, or list. By this, I mean that you can build a queue or stack out of the lower level containers.
For example:
std::stack<int, std::deque<int> > s;
std::queue<double, std::list<double>... |
2,248,009 | 2,248,182 | Qt: Defining a custom event type | I have created a custom event in my Qt application by subclassing QEvent.
class MyEvent : public QEvent
{
public:
MyEvent() : QEvent((QEvent::Type)2000)) {}
~MyEvent(){}
}
In order to check for this event, I use the following code in an event() method:
if (event->type() == (QEvent::Type)2000)
{
...
}
I ... | If the event-type identifies your specific class, i'd put it there:
class MyEvent : public QEvent {
public:
static const QEvent::Type myType = static_cast<QEvent::Type>(2000);
// ...
};
// usage:
if(evt->type() == MyEvent::myType) {
// ...
}
|
2,248,038 | 2,251,372 | QWebElement manipulation of a QWebPage in a separate thread | I have a QWebPage created in the main thread (you can't create it anywhere else). I would like to manipulate this page using the QWebElement API introduced in Qt 4.6, but in a separate thread. So that thread would acquire a reference to the page and perform the necessary tree walking and attribute changes I need.
As th... | I do think you're right, and it is safe. At least, you have me convinced :)
|
2,248,136 | 2,248,150 | set map implementation in C++ | I find that both set and map are implemented as a tree. set is a binary search tree, map is a self-balancing binary search tree, such as red-black tree? I am confused about the difference about the implementation. The difference I can image are as follow
1) element in set has only one value(key), element in map has two... | Maps and sets have almost identical behavior and it's common for the implementation to use the exact same underlying technique.
The only important difference is map doesn't use the whole value_type to compare, just the key part of it.
|
2,248,262 | 2,248,270 | Array boundaries and indexes | I had an earlier post link textwhere someone said I had my pointer initialized to the wrong element which I don't quite see why, other than they are right and it works with their correction. So here is the basic problem:
If I declare an array from 0 to 30 with
#define ENDPOINT 15
int record[2 * ENDPOINT + 1];
// and w... | record[ENDPOINT] is the 16th element- the array's indices start at 0, so record[0] is the 1st element, record[1] is the 2nd element... and record[ENDPOINT] (is record[15]) is the 16th element.
You have 2*15+1 or 31 elements in your array. Adding 14 to ENDPOINT (15) yields 29, and record[29] is the 30th element in the a... |
2,248,512 | 2,251,227 | Qt build that can link statically out of the box? | I have used Qt to build a small application. It turns out that I need to reconfigure and Qt from scratch in order to be able to link statically. I've done it before, and I remember that it was a very long process.
So does anyone know a Qt SDK installer that provides the ability for static linking out of the box?
| In addition to Martin Beckett's answer.
Be careful with licenses!
If you use Qt under (L)GPL license terms and distribute your own app under (L)GPL too, than everything is OK.
Of course if you want to make proprietary software than the situation is more complicated. Very roughly, the end user should be able to (modify... |
2,248,547 | 2,248,562 | Understanding Factories and should I use them? | I have never used Factories before for the simple reason, I don't understand when I need them. I have been working on a little game in my spare time, and I decided to implement FMOD for the sound. I looked at a wrapper designed for OpenAL(different sound setup) and it looked something like...
SoundObject*
SoundObjectMa... | Think of Factory as a "virtual constructor". It lets you construct objects with a common compile time type but different runtime types. You can switch behavior simply by telling the Factory to create an instance of a different runtime type.
|
2,248,623 | 2,248,634 | C++ "dynamic" arrays | I've got some problems/misunderstandings with arrays in C++.
int myArray[30];
myArray[1]=2;
myArray[2]=4;
This is spitting out a lot of compiler errors. I don't think it is necessary to include them here as this is an easy question for everybody with experience in C(++) I guess
Why doesn't this work?
Is there a way t... | I'm guessing you have that outside of a function.
You are allowed to define variables outside of a function. You can even call arbitrary code outside of a function provided it is part of a variable definition.
// legal outside of a function
int myArray[30];
int x = arbitrary_code();
void foo()
{
}
But you cannot h... |
2,248,784 | 2,248,827 | Choosing between static libs and dynamic libs/plugins? | I have been throwing stuff together in a small test game over the past 6 months or so, and right now everything is in the one project. I would like to learn more about creating an "engine" for reusability and I am trying to figure out the best way to do this.
Static Libs are obviously a tiny bit faster, as they are com... | If you are creating DLLs for re-usability it makes sense to split it up into self contained units of functions. Thus, if you have a general sound library that, for example, plays wav files, that could be separated out as sound.dll if you think lots of other programs might make use of that particular library. Likewise f... |
2,248,844 | 2,254,189 | Qt::How to lower the text in a QSpinBox | I'm using a spinbox with a custom font which looks too high in the spinbox. How do I move the text lower?
I have already reimplemented QStyle and made the font lower in another widget but I can't find where to do it with the spinbox. There must be a QRect somewhere where you can just move the top of it but I don't know... | Qt specifies a QStyle::SC_SpinBoxEditField, which appears to be what you want to modify. If I recall correctly from a few years ago when I was doing stuff with styles, you should be able to hook into getting options for that subcontrol, which would include the rect within which it is supposed to be drawn. Modifying t... |
2,248,936 | 2,257,214 | Qt4: QMap causing "strict-aliasing rules" compilation error | I'm trying to create the following data structure in Qt 4.5 in C++:
QMap<int, QMap<QString, QVector<QPointF> > > animation;
However, the inclusion of this line in my code results in the following error:
cc1plus: warnings being treated as errors
In file included from XXX/XXX/XXX/MainWindow.qt.C.tmp.C:113:
/usr/lib/qt4/... | The code you mention works fine with Qt 4.6.1 and GCC 4.4.1 on Intel/Mac OS X.
$ cat a.cpp #include <QtCore>
void foo (QMap<int, QMap<QString, QVector<QPointF> > > &map)
{ map.clear(); }
$ g++-4.4-fsf -c -DQT_CORE_LIB -DQT_SHARED -I/Library/Frameworks/QtCore.framework/Versions/4/Headers a.cpp -W -Wall -Werror -g -O3 ... |
2,248,992 | 2,249,013 | new returns NULL when initializing static global variable in windows? | I'm working on integrating rLog with our code base, and I'm noticing a problem on Windows that I don't have on linux. In a header file I have a static variable that gives me a "verbose" logging channel (one up from debug basically), defined thusly:
static RLogChannel *rlog_verbose = DEF_CHANNEL("verbose", Log_Debug);
... | are you sure its returning null. It might be the whole static initializer thing. The order of static initializer invocations is not defined from file to file. If you have static code that is using rlog_verbose then gRootCHannel might well be NULL simply because the initializer hasn't been called yet.
|
2,249,018 | 2,250,268 | using setw with user-defined ostream operators | How do I make setw or something similar (boost format?) work with my user-defined ostream operators? setw only applies to the next element pushed to the stream.
For example:
cout << " approx: " << setw(10) << myX;
where myX is of type X, and I have my own
ostream& operator<<(ostream& os, const X &g) {
return o... | Just make sure that all your output is sent to the stream as part of the same call to operator<<. A straightforward way to achieve this is to use an auxiliary ostringstream object:
#include <sstream>
ostream& operator<<(ostream& os, const X & g) {
ostringstream oss;
oss << "(" << g.a() << ", " << g.b() << ")"... |
2,249,108 | 2,249,281 | Can I return in void function? | I have to return to the previous level of the recursion. is the syntax like below right?
void f()
{
// some code here
//
return;
}
| Yes, you can return from a void function.
Interestingly, you can also return void from a void function. For example:
void foo()
{
return void();
}
As expected, this is the same as a plain return;. It may seem esoteric, but the reason is for template consistency:
template<class T>
T default_value()
{
return T();
}
... |
2,249,201 | 2,249,218 | Template / Namespace Interactions | I came across a compile.. oddity? recently that led me to believe that a template, when created, is created in the same namespaces (or, at least, using the same namespaces) as where is was declared. That is;
template<class T>
class bar
{
public:
static int stuff(){return T::stuff();}
};
namespace ONE
{
struct ... | That's not unexpected. You didn't qualify which foo you wanted, so your using declaration told the compiler where to find it.
The worst template gotcha I've seen in production code had to do with non-dependent name lookup. It's pretty complicated, so it's probably best to just point you at the C++ FAQ Lite (sections ... |
2,249,234 | 2,249,254 | A few questions about C++ classes | I have two basic questions. The first one is about function in other classes. If I have a header file with a class in it and I want to use that function in another class I have created, do I always have to construct a class object to run a function in that class like:
someclass class; <----object construction
class.s... | Functions should only be member functions if they act on an object of the class. Functions that don't act on an object should just be plain global functions (or class static):
// Global function
void foo() { /* do something */ }
// Static function
class Foo
{
public:
static void foo() { /* do something */ }
};
For... |
2,249,395 | 2,249,403 | New .h file in Eclipse yields a #define constant | So I'm chugging along in learning C++ and I'm starting to use Eclipse. As I create my .h files, I get this strange #define constant at the top:
#ifndef CLASSNAME_H_
#define CLASSNAME_H_
#endif /* CLASSNAME_H_ */
So, what gives? Am I supposed to use CLASSNAME_H_ for something?
(I should note that "classname" is just a... | This is a standard construct used to guard against re-inclusion of your header files, I think you are probably expected to rename CLASSNAME_H_ to something more unique.
or is your header file also called classname.h?
Edit: ok so I see now that classname wasn't the actual value, but rather an example.
In that case, NO,... |
2,249,571 | 2,249,580 | Acquire a lock on two mutexes and avoid deadlock | The following code contains a potential deadlock, but seems to be necessary: to safely copy data to one container from another, both containers must be locked to prevent changes from occurring in another thread.
void foo::copy(const foo & rhs)
{
pMutex->lock();
rhs.pMutex->lock();
// do copy
}
Foo has an S... | Impose some kind of total order on instances of foo and always acquire their locks in either increasing or decreasing order, e.g., foo1->lock() and then foo2->lock().
Another approach is to use functional semantics and instead write a foo::clone method that creates a new instance rather than clobbering an existing one.... |
2,249,587 | 2,249,739 | c++ transform with if_then_else control structure | I'm trying to change the integer values in a vector using transform and an if_then_else control structure from Boost Lambda. However my compiler is not appreciating my efforts. The code I am attempting is:
transform(theVec.begin(), theVec.end(), theVec.begin(),
if_then_else(bind(rand) % ratio == 0, _1 = bind... | if_then_else in your usage is incorrect, in the same way this is:
int i = if (some_condition){ 0; } else { 1; };
What you want is merely the ternary operator; however, this won't work in a lambda. You can simulate this with the the if_then_else_return structure instead. (i.e., you were close!)
The if_then_else is for... |
2,249,711 | 2,249,791 | How to use the boost lexical_cast library for just for checking input | I use the boost lexical_cast library for parsing text data into numeric values quite often. In several situations however, I only need to check if values are numeric; I don't actually need or use the conversion.
So, I was thinking about writing a simple function to test if a string is a double:
template<typename T>
bo... | Since the cast might throw an an exception, a compiler that would just drop that cast would be seriously broken. You can assume that all major compilers will handle this correctly.
Trying to to do the lexical_cast might not be optimal from a performance point of view, but unless you check millions of values this way it... |
2,249,716 | 2,249,753 | How to design a class where the user/caller has options to provide a custom behavior using a custom class | I encounters a problem where I want to have a class in which its behavior can be customized by another class, for example, Foo's constructor accepts a parameter of some type of class:
class Bar { //The default class that define behavior
};
template <typename T = Bar>
class Foo {
public:
Foo(T* t = 0) t_(t) {
... | You can't detect the difference between stack and heap allocation (the standard doesn't even mention a stack), but that's not the issue here.
Foo should not be deleting things that it does not own. If it wants a copy for itself then it should just make a copy:
template <class T = Bar>
class Foo
{
T t_;
public:
Foo(... |
2,250,397 | 2,250,448 | Interpretation of int (*a)[3] | When working with arrays and pointers in C, one quickly discovers that they are by no means equivalent although it might seem so at a first glance. I know about the differences in L-values and R-values. Still, recently I tried to find out the type of a pointer that I could use in conjunction with a two-dimensional arra... | First, you mean "typedef" not "typecast" in your question.
In C, a pointer to type T can point to an object of type T:
int *pi;
int i;
pi = &i;
The above is simple to understand. Now, let's make it a bit more complex. You seem to know the difference between arrays and pointers (i.e., you know that arrays are not poi... |
2,250,408 | 2,250,432 | Getting undefined class type error but I did create the class and defined it | Im working on an assignment for one of my classes. Simply I have a GumballMachine class and a bunch of State classes that change the state of the GumballMachine.
Here is the offending code:
class GumballMachine;
class State {
public:
virtual void insertQuarter() const = 0;
virtual void ejectQuarter() const = 0;
vir... | You cannot access any members of GumballMachine before you define the class, so you'll have to either split your file into several files, each containing one class, or define your NoQuarterState::insertQuarter method after the definition of the GumballMachine class:
class NoQuarterState : public State {
public:
... |
2,250,650 | 2,250,919 | Encryption of Objects stored to disk using C++ (for a Java Developer) | This is two questions in one but hopefully trivial to a C++ developer.
How can I seralize an object so that I can write it to disk and retrieve it later in C++ or if this is the wrong keyword how can I write an object as a binary stream and recreate it later? Can I use inheritance to make a hierarchy of classes serial... | Boost.Serialization is probably the best option for doing this in C++. If you want to save binary data you need to create a boost::archive::binary_oarchive and associate it to your file:
std::ofstream ofs("my_file.dat");
boost::archive::binary_oarchive oarch(ofs);
Any class you want to serialize must have a member fun... |
2,250,759 | 2,266,895 | How does a CRichEditCtrl know a paste operation has been performed? | It has methods like CRichEditCtrl::Copy(), CRichEditCtrl::Paste() which you can call, but I can't spot any messages the control is sent by Windows telling it to perform a paste operation. Does anyone know if such a thing exists? Or does CRichEditCtrl do something lower-level like monitoring WM_CHAR events? If so can I ... | Handle EN_PROTECTED message.
ON_NOTIFY_REFLECT(EN_PROTECTED, &YourClass::OnProtected)
// call this from the parent class
void YourClass::Initialize()
{
CHARFORMAT format = { sizeof(CHARFORMAT) };
format.dwEffects = CFE_PROTECTED;
format.dwMask = CFM_PROTECTED;
SetDefaultCharFormat(format);
SetEve... |
2,250,817 | 2,250,842 | function to return the windows installed drive? | i would like to know the function which returns the drive where the windows has been installed.
for example
if we run a program with following code in windows which is installed in "C:\"
temp_char = getWindowsInstalledDrive();
should return "C:\".
please point me to that function if you know. it should be a C/C++... | You can use GetSystemDirectory(): http://msdn.microsoft.com/en-us/library/ms724373%28VS.85%29.aspx and then take the first 3 letters.
|
2,250,872 | 2,250,993 | use class and enum with same name? | I've a class and an enum value which have the same name. Inside the class I want to use the enum which gives an error. Is there any way to use the enum without renaming or moving to a different namespace?
Example:
namespace foo {
enum bar {
BAD
};
class BAD {
void worse () {
bar... | This is one of those tricky parts of how the name lookup is performed.
There are two identifier scopes in C++, one for class types and general identifier scope. The enum value BAD resides in the general identifier scope, while the class type BAR resides in the class identifier scope. That is the reason why you are allo... |
2,250,970 | 2,251,266 | What's the correct way to create a subclass of a MFC control? | We layout dialogs using the resource editor. So say I have a RichEditCtrl called IDC_RICH. And I want to link it to an instance of a custom class CMyRichEditCtrl : CRichEditCtrl, without losing the ability to set properties on it in resource editor.
What's the right way? You can certainly get some functionality by crea... | The windows you put on a dialog with the resource editor are created using CreateWindow(Ex) with the first argument set to the class name that is specified in the .rc file. The DDX_ mechanism then associates this instantiated window with the dialog class member in DoDataExchange().
MFC is a layer over Win32 but MFC dev... |
2,251,201 | 2,260,748 | Visual Studio as Code Browser : How to preserve the directory structure? | I've downloaded source of an opensource C++ project. It is a Linux project. As Visual Studio is my favorite IDE I want to use it to browse & study the code. I created an empty C++ project and now want to add the source code to Solution explorer.
How can I add the directory structure to "Solution Explorer". Dropping th... | As you didn't seem to be getting any useful answers, I thought I'd post this. I don't use VS, but two possible alternative browsing tools (both free, open source) that do respect directory structures are:
Doxygen, which will give you a browser-based hyper-linked view of your source code.
Code::Blocks a C++ IDE (to add... |
2,251,212 | 2,275,665 | How to improve Visual C++ compilation times? | I am compiling 2 C++ projects in a buildbot, on each commit. Both are around 1000 files, one is 100 kloc, the other 170 kloc. Compilation times are very different from gcc (4.4) to Visual C++ (2008).
Visual C++ compilations for one project take in the 20 minutes. They cannot take advantage of the multiple cores because... | One thing that slows down the VC++ compiler is if you have a header file that initializes concrete instances of non-trival const value types. You may see this happen with constants of type std::string or GUIDs. It affects both compilation and link time.
For a single dll, this caused a 10x slowdown. It helps if you put ... |
2,251,361 | 2,251,483 | Boost.ASIO-based HTTP client library (like libcurl) | I am looking for a modern C++ HTTP library because libcurl's shortcomings are difficult to work around by C++ wrappers. Solutions based on Boost.ASIO, which has become the de-facto C++ TCP library, are preferred.
| The other day somebody recommended this on another thread:
http://cpp-netlib.github.com/
I think this is as high-level as you will find, but I'm not sure if it's mature enough yet (I would say it probably is since they've proposed it for Boost inclusion).
|
2,251,394 | 2,251,570 | How can I use templated typedefs, that are _in_ a class, from outside the class (e.g. by another class), in relation to boost::graph | I found a very useful answer on how to create templated graphs using boost::graph under Modifying vertex properties in a Boost::Graph
For me, this is very convenient as long as I do all the work on the graph in the Graph-class itself.
However, it might be necessary to access information from outside, e.g. one might wan... | But the typedefs are public, so you can access them from outside:
template<typename T>
class A
{
public:
typedef T type;
typedef unsigned data;
};
Now this is the following:
A<int>::type // int
A<int>::data // unsigned
Be careful, if T is not specified
template<typename T>
void func( A<T>& a )
{
typename ... |
2,251,608 | 2,251,723 | Problem inheriting member functions with similar signatures in C++ | I have an MFC C++ program that contains two classes, as follows;
struct MyStruct
{
'
'
};
class Class1
{
public:
virtual MyStruct *MyFunc(LPCTSTR x);
virtual void MyFunc(MyStruct *x);
'
'
};
class Class2 : public Class1
{
public:
virtual void MyFunc(MyStruct *x);
'
'
};
main()
{
'
'
CString Str = _T("WT... | This is by design to handle what is called the "fragile base class" problem.
Let's assume you have classes like this:
struct A
{
void MyFunc(long) {...}
}
struct B : A
{
void MyFunc(long) { ... }
}
....
B b;
b.MyFunc(5);
Here's we would call B:MyFunc(long) because ints silently convert to longs.
But say so... |
2,251,635 | 58,561,767 | How to detect change of system time in Linux? | Is there a way to get notified when there is update to the system time from a time-server or due to DST change? I am after an API/system call or equivalent.
It is part of my effort to optimise generating a value for something similar to SQL NOW() to an hour granularity, without using SQL.
| You can use timerfd_create(2) to create a timer, then mark it with the TFD_TIMER_CANCEL_ON_SET option when setting it. Set it for an implausible time in the future and then block on it (with poll/select etc.) - if the system time changes then the timer will be cancelled, which you can detect.
(this is how systemd does ... |
2,251,724 | 2,251,773 | error C2146: syntax error : missing ';' before identifier | i can't get rid of these errors... i have semicolons everywhere i checked...
the code is simple:
the error takes me to the definition "string name" in article.h...
main.cpp
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
#include "article.h"
int main()
{
string si;
c... | You should add:
#include <string>
to your "article.h" header file and declare name like this:
std::string name;
|
2,252,314 | 2,252,363 | In which memory area are exception classes instances created? | I could not find the information where are exception class instances created during exception handling ? In which memory area (stack, heap, static storage, etc.) ? I assume it is not on the stack because of stack-unwinding ...
| From the standard:
15.2.4: The memory for the temporary copy of the exception being thrown is
allocated in an unspecified way,
except as noted in 3.7.3.1.
And 3.7.3.1 says:
3.7.3.1: All objects which neither have dynamic
storage duration nor are local have
static storage duration. The storage
for these obj... |
2,252,372 | 2,252,399 | How do you make a program sleep in C++ on Win 32? | How does one "pause" a program in C++ on Win 32, and what libraries must be included?
| #include <windows.h>
Sleep(number of milliseconds);
Or if you want to pause your program while waiting for another program, use WaitForSingleObject.
|
2,252,389 | 2,253,563 | Using DirectX DLL (C++) from C# | I have a native C++ DLL using DirectX, that I want to be able to use through C# to be able to create content creation tools.
Adding COM would require quite an effort it seems.
Can P/Invoke be used to maintain classes using polymorphism, or would it require me to wrap most of the code to facilitate use of P/Invoke?
It t... | I always feel that C++/CLI is always the best option when doing C# to C++ interop. You can easily create thin wrappers for an unmanaged library that will look exactly like a managed library to your C# code. It also gives you more control over how marshaling and pinning is performed.
There are ways to automatically gen... |
2,252,452 | 2,252,478 | Does a getter function need a mutex? | I have a class that is accessed from multiple threads. Both of its getter and setter functions are guarded with locks.
Are the locks for the getter functions really needed? If so, why?
class foo {
public:
void setCount (int count) {
boost::lock_guard<boost::mutex> lg(mutex_);
count_ = count;
... | The only way you can get around having the lock is if you can convince yourself that the system will transfer the guarded variable atomicly in all cases. If you can't be sure of that for one reason or another, then you'll need the mutex.
For a simple type like an int, you may be able to convince yourself this is true,... |
2,252,579 | 2,253,775 | Permissions denied for directory - c++ | I'm trying to build ogre newton application from svn.
I have win7 && vs 2008.
There is inc directory which is included into resources (additional include directories).
But after compiling I get error:
fatal error C1083: Cannot open source
file: '*\newton20\inc': Permission
denied c1xx
What's wrong?
| It looks like the compiler is trying to open the inc directory as a source file.
|
2,252,745 | 2,252,787 | Entering a string of characters using arrays and pointers | Ok guys, i'm very beginner and trying to enter string to a char array using pointers..and then display what i've written.
There're two things i want to ask about. First , if i didn't want to specify a size for the array and just want it to expand to contain all string i've entered ..how is that ?
And second after i en... | 1) You need to either use a string object or new if you want to dynamically resize your string.
2) It doesn't contain the spaces because cin reads one words at a time. There are several ways to get around this. The one I would use is switch to using scanf and printf instead of cin and cout. Or, as vivin said, you ca... |
2,252,767 | 2,252,827 | Managing windows API differences between Windows XP and Vista/Server 2008 | I am trying to create a single executable of a simple Win32 application that has to be able to run on both Windows XP and Windows Vista/2008.
Due to some changes in the way Vista works some extra Win32 API calls have to be made to make the program function correctly as it did on XP.
Currently I detect if the applicatio... | You will have to use LoadLibrary() and GetProcAddress() to get the entry point for this function. On XP you'll get a NULL back from GetProcAddress(), good enough to simply skip the call. There's a good example in the SDK docs, the only tricky part is declaring the function pointer:
typedef BOOL (WINAPI *MYPROC)(HWN... |
2,252,793 | 2,279,194 | Is there a C++ MinMax Heap implementation? | I'm looking for algorithms like ones in the stl (push_heap, pop_heap, make_heap) except with the ability to pop both the minimum and maximum value efficiently. AKA double ended priority queue. As described here.
Any clean implementation of a double ended priority queue would also be of interest as an alternative, howe... | If you're looking for the algorithm implementation try searching Github.
|
2,252,848 | 2,253,180 | Reading Firefox Bookmarks | Apparently, latest Firefox versions stores its bookmarks in a file called 'places.sqlite'. Like a browser can import the bookmarks from another browser, I would want to import the bookmarks to a file, but I need to know what would you need to do it?
| SQLite is an embedded, serverless, relational database. Besides the mentioned ODBC drivers, it has its own C API.
|
2,252,981 | 2,253,013 | gdb error: Unable to execute epoll_wait: (4) Interrupted system call | I am unable to run my code in debug using gdb because of the following error:
Unable to execute epoll_wait: (4) Interrupted system call
Any ideas on how to solve this?
Thanks
| You should check the epoll_wait return value, then if it's -1 compare errno to EINTR and, if so, retry the system call. This is usually done with continue in a loop.
|
2,252,996 | 2,253,337 | C++ Recursion problems <confused> | I am working on understanding recursion, and I think I have it down alright... I'm trying to build a search function (like the std::string.find()) that searches a given string for another string for example:
Given (big) string: "ru the running cat"
search (small) string: "run"
I'm trying to return a index for th... |
Don't change any state variables. Your code should not include the operator ++ anywhere. You are not trying to loop over a datastructure and change your local variables in some fashion - you are trying to generate an entirely new but smaller problem each time. So, all those ++ operators - whether pre or post increm... |
2,253,168 | 2,254,183 | dynamic_cast and static_cast in C++ | I am quite confused with the dynamic_cast keyword in C++.
struct A {
virtual void f() { }
};
struct B : public A { };
struct C { };
void f () {
A a;
B b;
A* ap = &b;
B* b1 = dynamic_cast<B*> (&a); // NULL, because 'a' is not a 'B'
B* b2 = dynamic_cast<B*> (ap); // 'b'
C* c = dynamic_cast... | Here's a rundown on static_cast<> and dynamic_cast<> specifically as they pertain to pointers. This is just a 101-level rundown, it does not cover all the intricacies.
static_cast< Type* >(ptr)
This takes the pointer in ptr and tries to safely cast it to a pointer of type Type*. This cast is done at compile time. It... |
2,253,362 | 2,253,669 | How to install Microsoft.VisualStudio.Shell.dll on Client Computer | I am dealing with some code that won't install on client machines (NOT running Visual Studio) because is makes reference to VSConstants.S_OK, which is in Microsoft.VisualStudio.Shell.dll. Is there a redistributable that includes this, or do I need to have the code updated to use a different constant.
| Microsoft.VisualStudio.Shell.dll is parenthetically not a redistributable component. You'll find a list of the ones you can redistribute in the redist.txt file in the Visual Studio install directory.
Getting rid of this particular dependency isn't hard. It is a COM HRESULT value, S_OK = 0. You can find those values ... |
2,253,484 | 2,253,523 | Ideas for specific data structure in c++ | I need to do some task.
There are numbers give in two rows and they act like pairs of integers (a, b). I have to find the maximum 5 numbers of the a-row and then select the max of those 5 but this time from the b-row. Ex:
1 4
5 2
3 3
7 5
6 6
2 9
3 1
In this example, the pair i need is (6,6) because 6 (a) is in the top... | A priority queue holding pairs that does its order evaluations based on the first element of the pair would be appropriate. You could insert all the pairs and then extract the top 5. Then just iterate on that list of pairs looking for the max of the second element of each pair.
edit
I should say that it is a decent s... |
2,253,690 | 2,253,742 | What makes STL fast? | If one implements an array class the way it is commonly implemented, its performance is slower compared to its STL equivalent like a vector. So what makes STL containers/algorithms fast?
| STL algorithms like for_each take function objects that can be easily inlined. C, on the other hand, uses function pointers which are much more difficult for the compiler to optimize.
This makes a big difference in some algorithms like sorting in which the comparer function must be called many times.
Wikipedia has s... |
2,253,725 | 2,285,135 | How can I work around the GetParent/EnumChildWindows asymmetry? | I recently inspect a GUI with Microsoft's Spy++ and noticed a strange structure; it looked like this (warning, ASCII art ahead):
|
+ 002004D6 "MyRootWindow1" FooClassName
| |
| + 001F052C "MyChildWindow" ClassOfChildWindow
|
\ 001D0A8C "MyRootWindow2" SomeOtherClassName
There are two root windows, 002004D6 ... | The documentation for GetParent explains:
"Note that, despite its name, this function can return an owner window instead of a parent window. "
As you are not creating a child window i'm guessing you hit this case.
You should be able to call GetAncestor passing GA_PARENT as the documentation says:
"Retrieves the parent ... |
2,253,738 | 2,253,818 | C++ typedef interpretation of const pointers | Firstly, sample codes:
Case 1:
typedef char* CHARS;
typedef CHARS const CPTR; // constant pointer to chars
Textually replacing CHARS becomes:
typedef char* const CPTR; // still a constant pointer to chars
Case 2:
typedef char* CHARS;
typedef const CHARS CPTR; // constant pointer to chars
Textually replacing... | There's no point in analyzing typedef behavior on the basis of textual replacement. Typedef-names are not macros, they are not replaced textually.
As you noted yourself
typedef CHARS const CPTR;
is the same thing as
typedef const CHARS CPTR;
This is so for the very same reason why
typedef const int CI;
has the same... |
2,253,825 | 2,253,858 | C++ std::string InputIterator code to C code | I have some C++ code that I found that does exactly what I need, however I need it in C and I do not know how I could do it in C, so I am hoping someone can help me out.
The C++ code is:
std::string value( (const char *)valueBegin, (const char *)valueEnd );
This is using the string::string constructor:
template<class ... | // Get the number of characters in the range
size_t length = valueEnd - valueBegin;
// Allocate one more for the C style terminating 0
char *data = malloc(length + 1);
// Copy just the number of bytes requested
strncpy(data, valueBegin, length);
// Manually add the C terminating 0
data[length] = '\0';
|
2,253,878 | 12,785,369 | Why does C++ disallow anonymous structs? | Some C++ compilers permit anonymous unions and structs as an extension to standard C++. It's a bit of syntactic sugar that's occasionally very helpful.
What's the rationale that prevents this from being part of the standard? Is there a technical roadblock? A philosophical one? Or just not enough of a need to justify i... | As others have pointed out anonymous unions are permitted in standard C++, but anonymous structs are not.
The reason for this is that C supports anonymous unions but not anonymous structs*, so C++ supports the former for compatibility but not the latter because it's not needed for compatibility.
Furthermore, there's n... |
2,253,950 | 2,254,056 | Unit Testing Private Method in Resource Managing Class (C++) | I previously asked this question under another name but deleted it because I didn't explain it very well.
Let's say I have a class which manages a file. Let's say that this class treats the file as having a specific file format, and contains methods to perform operations on this file:
class Foo {
std::wstring fileN... | Basically, it sounds like you want a mock to make unit testing more feasible. The way you make a class targetable for unit testing independantly of the object hierarchy and of external dependencies is through dependency injection. Create a class "FooFileReader" like so:
class FooFileReader
{
public:
virtual std::o... |
2,253,969 | 2,254,057 | Proper vector memory management | I'm making a game and I have a vector of bullets flying around. When the bullet is finished, I do bullets.erase(bullets.begin() + i); Then the bullet disappears. However it does notseem to get rod of the memory. If I create 5000 bullets then create 5,000 more after those die off, memory stays the same, but if I create ... | The std::vector class automatically manages its internal memory. It will expand to hold as many items as you put into it, but in general it will not shrink on its own as you remove items (although it will of course release the memory when it destructs).
The std::vector has two relevant concepts of "size". First is the ... |
2,254,263 | 2,254,306 | Order of member constructor and destructor calls | Oh C++ gurus, I seek thy wisdom. Speak standardese to me and tell my if C++ guarantees that the following program:
#include <iostream>
using namespace std;
struct A
{
A() { cout << "A::A" << endl; }
~A() { cout << "A::~" << endl; }
};
struct B
{
B() { cout << "B::B" << endl; }
~B() { cout << "B::~" <<... |
In other words, are members guaranteed to be initialized by order of declaration and destroyed in reverse order?
Yes to both. See 12.6.2
6 Initialization shall proceed in the
following order:
First, and only for
the constructor of the most derived
class as described below, virtual base
classes shall be initialized ... |
2,254,293 | 2,254,367 | Drawing real coordinates | I've implemented a plotting class that is currently capable of handling integer values only. I would like to get advice about techniques/mechanisms in order to handle floating numbers. Library used is GDI.
Thanks,
Adi
| At some point, they need to be converted to integers to draw actual pixels.
Generally speaking, however, you do not want to just cast each float to int, and draw -- you'll almost certainly get a mess. Instead, you need/want to scale the floats, then round the scaled value to an integer. In most cases, you'll want to m... |
2,254,329 | 2,254,394 | How to port C++ to swf with Alchemy? | Alchemy allows users to compile C and C++ code that is targeted to run on the open source ActionScript Virtual Machine (AVM2). While this idea seems really promising has anyone had success with this - if so are there examples?
I was wanting to convert some old DOS programs to SWF so they could be ran in the browser.
| Most old DOS code isn't very portable, so running it on anything but DOS will take considerable work. Quite a bit of it makes direct use of DOS interrupts, absolute locations in the memory map, and so on. Getting these to run under AVM2 would basically not just require a C compiler, but a full emulation of MS-DOS, a BI... |
2,254,536 | 2,254,556 | bridge pattern vs. decorator pattern | Can anybody elaborate the Bridge design pattern and the Decorator pattern for me. I found it similar in some way. I don't know how to distinguish it?
My understanding is that in Bridge, it separate the implementation from the interface, generally you can only apply one implementation. Decorator is kind of wrapper, you... | The Decorator should match the interface of the object you're decorating. i.e. it has the same methods, and permits interception of the arguments on the way in, and of the result on the way out. You can use this to provide additional behaviour to the decorated object whilst maintaining the same interface/contract. Note... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.