question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
4,687,134 | 4,687,441 | Header Directories in VS2010 | Let's say I have a solution/project called myTest, which just has a myTest.cpp file. In some completely separate folder (a Subversion folder on my desktop, for example), I have a myTest.h file.
In Xcode, I can drag myTest.h into the "Groups and Files" pane and I will be able to use myTest.h by putting #include "myTest... | you can add additional include directories in the C/C++ page of your project-properties.
then you can use #include "...".
|
4,687,166 | 4,687,237 | what does ::operator() do? | struct reserved_memory
{
void *safety;
size_t safety_size;
reserved_memory(size_t size) : safety_size(size)
{
init();
}
bool use() {
if (safety) {
::operator(safety);
safety=0;
return true;
} else
return false... | Seems pretty obvious that whoever wrote that code intended to call ::operator delete(safety)
(evidence: safety is a pointer; it was initialised with ::operator new(safety_size), and after they erroneously call ::operator(safety) they reset it to zero).
As for the purpose of the code as a whole, I have no idea -- looks ... |
4,687,310 | 4,687,324 | Memory allocation in C++ | I am confused about the memory allocation in C++ in terms of the memory areas such as Const data area, Stack, Heap, Freestore, Heap and Global/Static area. I would like to understand the memory allocation pattern in the following snippet. Can anyone help me to understand this.
If there any thing more apart from the var... | "Heap" and "stack" are outmoded, inaccurate and confusing terms relating to storage duration.
Objects with "automatic storage duration" are what silly people call "stack objects". They're the ones that you will define inside a function as "local variables". They go out of scope when their enclosing block ends.
Objects ... |
4,687,392 | 4,687,442 | counting frequency of integers take together | I need to count the frequencies of different integers together in a binary file, how can I do this? I do not wish to convert to string, because that would slow down my program down.. I think...
vector<uint32_t> buf(2);
map<uint32_t, uint32_t> mymap;
if(file.is_open())
{
while (file.read(reinterpret_cast<char*>(&bu... | One option might be to have the map use pair<uint32_t, uint32_t>s as keys. That way you're explicitly mapping from pairs of uint32_ts to the frequency with which they appear.
|
4,687,423 | 4,687,590 | Trying to understand strtok | Consider the following snippet that uses strtok to split the string madddy.
char* str = (char*) malloc(sizeof("Madddy"));
strcpy(str,"Madddy");
char* tmp = strtok(str,"d");
std::cout<<tmp;
do
{
std::cout<<tmp;
tmp=strtok(NULL, "dddy");
}while(tmp!=NULL);
It works fine, the output is Ma. But by modifying the ... | It seems you forget that you have call strtok the first time (out of loop) by delimiter "d".
The strtok is working fine. You should have a reference here.
For the second example(strtok("ay")):
First, you call strtok(str, "d"). It will look for the first "d", and seperate your string. Specifically, it sets tmp = "Ma", a... |
4,687,430 | 4,687,507 | C++: Calculating Moving FPS | I would like to calculate the FPS of the last 2-4 seconds of a game. What would be the best way to do this?
Thanks.
Edit: To be more specific, I only have access to a timer with one second increments.
| Near miss of a very recent posting. See my response there on using exponential weighted moving averages.
C++: Counting total frames in a game
Here's sample code.
Initially:
avgFps = 1.0; // Initial value should be an estimate, but doesn't matter much.
Every second (assuming the total number of frames in the last seco... |
4,687,520 | 4,687,600 | Problem in printing array of char pointer passing from Python | My following C code works quite well, till my Python code trying to pass an array of char pointer to it.
The output I obtain is
The file_name is python-file
Another 3 string is not being printed out. Anything I had missed out?
C Code
#include <iostream>
#include "c_interface.h"
int foo(const char* file_name, const ... | Using and compiling your C++ code, I can only repeat the code I already stated in my last answer:
In [1]: import ctypes
In [2]: lib = ctypes.CDLL("libfoo.so.1.0")
In [3]: names = (ctypes.c_char_p*4)()
In [4]: names[0] = "NAME0"
In [5]: names[1] = "NAME1"
In [6]: names[2] = "NAME2"
In [7]: names[3] = 0
In [8]: li... |
4,687,643 | 4,687,665 | How do games like GTA IV not fragment the heap? | I'm interested in the type of memory management a game like GTA IV might use given that it needs to create and delete lots of objects very quickly. How do the avoid fragmenting the heap and other things. If someone could point me in the right direction I'd really appreciate it.
| They use things like memory pooling, specialized allocators, and specialized container classes.
The Hoard Memory allocator for multi-threaded programs.
EA's version of the STL. Contains allocators, containers,
|
4,687,731 | 4,687,741 | Access violation C++ (Deleting items in a vector) | I'm trying to remove non-matching results from a memory scanner I'm writing in C++ as practice. When the memory is initially scanned, all results are stored into the _results vector.
Later, the _results are scanned again and should erase items that no longer match.
The error:
Unhandled exception at 0x004016f4 in
.ex... | Erasing elements from a std::vector<T> will invalidate the it iterator since the std::vector<T> object will shift elements around to keep the underlying array contiguous after deleting an item.
Fortunately, vector<T>::erase() returns a new, valid iterator so that you don't end up trying to dereference an invalid iterat... |
4,687,747 | 4,687,768 | Is there a way to cout a #defined term? | #define BLAH word
cout << BLAH;
Is there any way to do this?
|
'cout' is not something you do. It is a global variable, which is an instance of the std::ostream type. You could say e.g. "output to cout".
#define does textual substitution. It is basically the same as if you used search-and-replace in your text editor to replace BLAH with word. Thus, the line cout << BLAH; turns in... |
4,687,901 | 4,687,917 | Writing C# GUI over a C++ dll or C++ exe | I have a C++ console Exe which does some progamming. Now i wanted to write a C# GUI which does some of the programming that the C++ exe does. I was thinking of few approaches,
Write the C# GUI with all programming in C++ done from scratch.(I do not want to do this for the amount of rework it entails)
Build a C++ dll w... | Building a C++/CLI dll really isn't that hard. You basically use unmanaged C++ code except that you define a "public ref class" which hosts the functions you want the C# code to see.
What kind of data are you returning? Single numbers, matrices of numbers, complex objects?
UPDATE: Since it has been clarified that the... |
4,688,043 | 4,688,060 | Time Function Syntax | Why is the time function usually used like this:
time_t currentTime;
currentTime = time( NULL );
instead of this:
time_t currentTime;
time( ¤tTime );
Is the first method used more just because it is arguably more readable? Or is there another reason?
Thanks.
Edit: Also, why was the time function even designed t... | It always seems to make more sense to return a value from a function than pass a paramter that is changed.
This might be because we learned on languages where functions and subroutines were different, don't know about these youngsters today.
|
4,688,055 | 4,688,150 | create menus in command line | How can one create menus in the command line program? I've tried stuff like:
cin >> input;
switch (input) {
case (1):
// do stuff
case (2):
// ...
}
but then I've had the problem of sub-menus, and going back to the same menu, etc. The first program I wrote (apart from exercises) that tried to use the switc... | If I tried to count the ways in which one might create a 1,2,3 menu, we'd both be dead before I'd iterated 1/2 of them. But here's one method you could try to get you started (untested, you may need to clean up a couple things):
struct menu_item
{
virtual ~menu_item() {}
virtual std::string item_text() const = 0;
... |
4,688,138 | 4,688,402 | Initializing the base class to a derived base class? | I don't think this is possible, but if it is, I'd find it very usseful.
I'm making a Gui API where the user does the paint event. Lets say I want to make a Numeric TextBox. Well it would only seem good practice for it to inherit from TextBox. The problem with this, is that the user is then stuck to reimplement the pain... | As I say in my comment, I think the bridge pattern is actually what you want, but since you're trying to insert a user's class as a base class for your NumericField thing the way you'd do THAT is to:
template < typename Base = TextField >
struct NumericField : Base
{
...
void paint() { Base::paint(); draw_circle(); ... |
4,688,177 | 4,688,258 | How does iterator category in C++ work? | I tried to understand iterator implementation, and while playing around with the source, I saw this statement:
typedef output_iterator_tag iterator_category;
I don't understand how this typedef work within the class? What's the side effect does it provide? Can anyone walk me through this?
| You need to read up on generic programming because you're not likely to get this answer.
"Output Iterator" is a concept that certain iterators match. Each iterator that is a realization of this concept has certain functionality associated with it. It's sort of like inheritance, but it isn't.
C++ doesn't have any such... |
4,688,385 | 4,688,681 | Use of Factory Method pattern in C++ | I am looking for an actual example of the use of Factory method pattern in C++. Is there any source code example that gives a good illustration.
| I like what does Codeproject teaches:
http://www.codeproject.com/KB/architecture/FactoryPattBasics.aspx
class CUIFrameWork
{
public:
// Instead of hard coding we write factory methods which
// perform the task of object creation.
virtual CDataComponent* MakeDataComp()
{
return new CDataComponen... |
4,688,448 | 4,688,544 | C++ sqrt returns -1.#IND000000000000 | In specific:
Im doing some math operations, and the application keeps crashing because a double that is widely used happens to get the value: -1.#IND000000000000 when "some" numbers are sqrt'ed...
What is this? Indefinite? Infinite? Too big to fit? Not a perfect Square Root? Is there any way to solve this?
Thanks in ad... | Actually, the string -1.#IND000000000000 is not a value, returned by a function, but it is one of a common representations of a QNaN, Quiet Not-a-Number, the special IEEE-754 value representing the invalid number, that won't cause the exception (there are also SNaN, Signalling NaN, which would cause the floating point ... |
4,688,564 | 4,689,400 | Accessing GetValue() from wxWindow class | Is there any way to access the GetValue() member of a GUI control under wxWidgets, if it is declared as a wxWindow rather than a wxCheckBox or wxRadioButton etc?
Thanks.
| An object declared as WxWindow is NOT a GUI control. A pointer declared as a WxWindow* might point to a wxStaticText object or a wxCheckBox object. You'd have to do a dynamic_cast< > to find out. Once you know it's a wxCheckBox, you can call wxCheckBox::GetValue. Similarly, if it's a wxRadioButton, you can call wxRadio... |
4,688,860 | 4,692,157 | C++: Dependency injection, circular dependency and callbacks | Consider the (highly simplified) following case:
class Dispatcher {
public:
receive() {/*implementation*/}; // callback
}
class CommInterface {
public:
send() = 0; // call
}
class CommA : public CommInterface {
public:
send() {/*implementation*/};
}
Various classes in the system send messages via the d... | I realized that where many classes use the Dispatcher instance, only the Dispatcher instance uses the CommA instance. Therefore the Dispatcher's dependency on CommA should not be externalized, i.e. CommA object should not be "injected" to the Dispatcher any more than any other internally defined variable within Dispatc... |
4,689,144 | 4,689,302 | Diamond problem with interfaces | I am using many abstract classes which define only pure virtual functions plus a virtual (non pure) destructor.
Is it still ok to have a diamond inheritance structure without using virtual inheritance? (I'd like to make sure that there are no problems even if some programmer does not know he should use virtual inherita... | You can't. Without virtual inheritance, the inheritance graph just isn't a diamond. If Derived inherits from Left and Right, and both derive non-virtually from Base, then there will be two Base subobjects per Derived object.
|
4,689,274 | 4,689,306 | Heap corruption detection tool for C++ | Is there any tool to help me detect heap corruption in C++? I can't provide source code because it's a big project. I can use any tool that works with Visual Studio or with xcode. The tool should work fine with multithreading. The problem is not very common, it appears after a long time and only in very special cases(t... | Valgrind is the defacto tool for doing memory instrumentation for native code. It, however, does not run on Windows (OS X is fine).
There are a few commercial tools which do run on Windows, and while they feature a GUI, are in my opinion inferior to Valgrind.
|
4,689,430 | 4,689,468 | Function call operator |
Possible Duplicates:
C++ Functors - and their uses.
Why override operator() ?
I've seen the use of operator() on STL containers but what is it and when do you use it?
| That operator turns your object into functor. Here is nice example of how it is done.
Next example demonstrates how to implement a class to use it as a functor :
#include <iostream>
struct Multiply
{
double operator()( const double v1, const double v2 ) const
{
return v1 * v2;
}
};
int main ()
{
... |
4,689,756 | 4,689,782 | Java-like annotations in C++ | Is there something like Java's annotations in C++ ?
For example, the @Override annotation marks a function that it overrides another function, and if it wouldn't, it would give an error at compile time.
I am looking for something like this in C++.
| C++0x will have this feature, where you can explicitly specify whether a member function is meant to override a base class' function, use a default implementation generated by the compiler and much more.
|
4,689,835 | 4,689,948 | Pointer vs variable in class | I know what is the difference and how they both work but this question is more about coding style.
Whenever I'm coding I make many classes, they all have variables and some of them are pointers and some are normal variables. I usually prefer variables to pointers if that members lasts as long as the class does but then... | First of all it is bad form to expose member variables.
Second your class should probably never container pointers.
Slight corolary: Classes that contain business logic should never have pointers (as this means they also contain pointer management code and pointer management code should be left to classes that have n... |
4,689,873 | 4,689,891 | Is there a way to constify of a variable after declaring it? |
Possible Duplicate:
Is there some ninja trick to make a variable constant after its declaration?
Sometimes in C or C++ we have a variable that might be const, but we have to take some lines of code to initialize it.
Is there a way to tell the compiler that, from some point in a function, some already constructed var... | Yes.
Put the initialization in a function.
int getInitCValue(int const& someVar)
{
// the value of c is initialized here
switch(someVar)
{
case foo: return 3;
case bar: return 4;
default : return 42; // what else?
}
}
int const c = getInitCValue(someVar);
Edit: To answer the mo... |
4,690,078 | 4,690,136 | access const variables accross translation units | In C++, const variables are implicitly hidden from other translation units. Is is possible to prevent that?
| Yes, prefix the definition with extern eg.
extern const int x = 10;
|
4,690,119 | 4,690,128 | Complex number printing program malfunctioning | I have started working on C++ language.I am very new to it.The program takes a complex number from the user and prints it out.But its giving me many errors like,
prog.cpp: In function ‘int main()’:
prog.cpp:26: error: ‘GetReal’ was not declared in this scope
prog.cpp:26: error: ‘SetReal’ was not declared in this scope
... | Since GetReal() et al are declared as part of the complex class, you should call them on the object you created:
complex comp;
comp.SetReal(comp.GetReal());
comp.SetImag(comp.GetImag());
comp.print();
Similarly, you need to scope the implementation of the complex constructor:
complex::complex()
{
real=0;
imag=0;
}... |
4,690,199 | 5,564,377 | Several Direct3D devices and Intel GMA945 | I have created 16 Direct3D devices with size approximately 320x200 pixels. I invoke IDirect3DDevice9::Present for each device in a separate thread every 40 ms. On laptops with Windows XP and integrated Intel GMA945 graphics part of devices is not updated if system tooltip or Start menu are shown. IDirect3DDevice9::Pres... | I've distributed DirectX software for a couple of years and along the way learnt that Intel graphics chipsets have incredibly crap drivers. Once I even saw a driver revision that couldn't render a quad properly. So when you have a problem with an Intel chipset, if you're on the latest driver version, you pretty much ... |
4,690,346 | 4,691,627 | WinApi, getting text from a control, invisible text and visible text show nothing | So since i can't make a peace with myself as i really want to dig deep here and understand how this works i am in the middle of trouble. Why is this control not showing any text in visible text or visible text area.
It constantly streams text but its never available to a tool like spy++.
so i figure using some comman... | The Windows Controls (in User32.dll and Comctl32.dll) are just one possible way of building the user interface of an application. When using those controls (or a UI library, such as MFC, which makes use of them), the application communicates with the control elements through window messages, such as the WM_GETTEXT you ... |
4,690,352 | 4,690,406 | Casting to int or float depending on is_integer | I have some type T, and in some cases it may be, for example char, but I want to output its integral value, not the character. For this is have the following:
typedef ( std::numeric_limits< T >::is_integer ? int : float ) FormatType;
os << static_cast< FormatType >( t );
However this fails to compile, stating "error C... |
What am I missing here?
You are trying to use types as expressions. C++ simply doesn’t allow this. You can instead use so-called “compile-time if” via metaprogramming. For example, I believe Boost offers the following:
typedef if_<std::numeric_limits< T >::is_integer, int, double>::type FormatType;
os << static_cast... |
4,690,384 | 4,690,613 | How do I apply both RTP and UDP protocols to achieve audio streaming? | How do I write a C++/MFC program to make a server as a bridge for clients to stream their audio? I have been told to use UDP and RTP protocol but due to my lack knowledge of media streaming, I couldn't make it work. What is relationship between UDP and RTP and steps needed for server to listen, accept and handle packet... | As unwind said, generally RTP runs on top of UDP. It's called a conectionless protocol.
This is the specification of UDP: http://www.ietf.org/rfc/rfc768.txt
An this is the specification of RTP: http://www.ietf.org/rfc/rfc1889.txt
You can find very useful information about RTP on this site. There are different libraries... |
4,690,467 | 4,692,003 | Maemo 5 Qt: how to capture frame (RGB) from first and second camera? | So (I havent tried yet) but it somehow seems that video for linux 2 will work... But I wonder is it possible to do such thing with for pure qt libs?
| Install Qt Mobility QtMultiMediaKit extension (libqtm-multimedia-dev package) and then use QCamera in conjunction with QCameraImageCapture to capture frames. To activate the front-facing secondary camera, construct your camera like this:
QCamera *camera = new QCamera(QCamera::availableDevices()[1]);
|
4,690,472 | 4,690,753 | ERROR_INVALID_HANDLE on TerminateProcess (VS C++) | Disclaimer: This is part of the requirement of the program, so it's not meant for anything bad. Feel free to point out any misuse if you spot one. I'm a beginner in C++.
Basically, I'm trying to restart Outlook.exe on Windows using C++.
And this is the code I used to restart Outlook.
#include <TlHelp32.h>
void RestartO... | I found the culprit.
The reason lies in this line:
HANDLE process = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
According to http://msdn.microsoft.com/en-us/library/ms684880(v=vs.85).aspx, PROCESS_ALL_ACCESS is too large for Windows XP/NT system, or more details:
The size of the PROCESS_ALL_ACCESS flag increased on W... |
4,690,545 | 4,715,246 | How do I prevent/suppress SIGFPE in C++? | I'm trying to convert a double to float as well as various integer types inside a dll, which is used as a Game Maker extension. I don't need a sensible result if the double doesn't fit the range of the target types, so I simply used a static_cast.
Everything works as intended when I call this code from my own test C++ ... | The good solution is to perform the conversion correctly by ensuring that the source value is within the range of the target type before casting. So my code from the question could be corrected like this:
ValueType converted;
if(value >= std::numeric_limits<ValueType>::max()) {
converted = std::numeric_limits<Value... |
4,690,591 | 4,690,634 | G++/GCC: how to make your app tell OS to download libs it needs into system? | So for example I am creating some app that uses boost or openCV and on my developer machine all that is installed so app compiles without any problem. But I wonder how to make app tell OS to download libs I use on first run? Is it possible? (sorry - I am linux noob)
| This is what package managers are for. What you do is you compile your project, and then you build a package (e.g. .deb or .rpm), using the appropriate tools. While doing so, you can specify where the various files in your package should go, but also which other packages your package relies on. These are known as "depe... |
4,690,800 | 4,690,818 | How to profile memory usage? | I am aware of Valgrind, but it just detects memory management issues. What I am searching is a tool that gives me an overview, which parts of my program do consume how much memory. A graphical representation with e.g. a tree map (as KCachegrind does for Callgrind) would be cool.
I am working on a Linux machine, so wind... | Use massif, which is part of the Valgrind tools. massif-visualizer can help you graph the data or you can just use the ms_print command.
|
4,690,886 | 4,690,919 | is the `synonym` in a `typedef` mandatory? | I encountered this in a code review:
typedef struct C { int i; };
It compiles.
Apart from it being C-style, where structs are in a separate 'namespace', and need to be typedeffed in order to use later on, I found it weird that there is nothing defined with this typedef...
So: doesn't typedef require a type argument an... | Yes, typedef requires another argument. That typedef won't do anything.
Anyway it's not an error, just a deprecate usage of typedef.
C standard (n1256 in 6.7.7) talks about typedef. It doesn't say this usage is deprecated, but compilers report it is, since such statement has no effect.
|
4,690,935 | 4,690,950 | howto examine c++ .o file under linux? | how can i examine a c++ .o file unter linux? is there any program with which i could easy examine it?
| objdump is the command to analyze object files.
What do you want to check, exactly?
|
4,690,987 | 4,691,021 | When should objects be dynamically or automatically instantiated? | For example, should I use:
Foo* object = new Foo ;
or should I just use
Foo object ;
If I messed up the code one either of those, please correct. It is early and I am a beginner.
| In the first case you allocate your Foo object in heap, while in the second it's allocated in stack.
Usually things are allocated in heap if:
Foo is so big that it wouldn't fit in the stack.
You don't know when to allocate your object (you only need to allocate it under some circumstances).
You need to extend the life... |
4,691,039 | 4,691,117 | Making Xerces parse a string instead of a file | I know how to create a complete dom from an xml file just using XercesDOMParser:
xercesc::XercesDOMParser parser = new xercesc::XercesDOMParser();
parser->parse(path_to_my_file);
parser->getDocument(); // From here on I can access all nodes and do whatever i want
Well, that works... but what if I'd want to parse a str... | Create a MemBufInputSource and parse that:
xercesc::MemBufInputSource myxml_buf(myxml.c_str(), myxml.size(),
"myxml (in memory)");
parser->parse(myxml_buf);
|
4,691,056 | 4,691,274 | Why won't this c++ lamba function compile? | Why does this fail to compile:
int myVar = 0;
myVar ? []()->void{} : []()->void{};
with following error msg:
Error 2 error C2446: ':' : no conversion from 'red_black_core::`anonymous-namespace'::< lambda1>' to red_black_core::anonymous-namespace::< lambda0>
While this complies correctly:
void left()
{}
void rig... | Rules for conditional operator in the draft n3225 says at one point
Otherwise, the result is a prvalue. If the second and third operands do not have the same type, and either
has (possibly cv-qualified) class type, overload resolution is used to determine the conversions (if any) to be
applied to the operands (13.3... |
4,691,273 | 4,693,832 | Get signal from PS/2-mouse in C++? | Does anyone know how to get the signal from a PS/2-style mouse by using some c++ code?
What I want to do is the following: I took an old mouse for PS/2 port and want to use the light barrier of the middle wheel for some measurement purposes. It would be nice to get the information about any change of the middle wheel, ... | The msdn is decent for this topic, although this may give you higher level information than you're looking for and won't be specific to a particular ps2 port, but will be for any mouse connected to the system. If you want specific information from only the ps/2 port you'll probably have to look at writing your own dev... |
4,691,332 | 4,691,336 | Constant Member Functions | After reading this, it is my understanding that declaring a method as const prevents it from accidentally modifying the class's member variables.
Are const methods commonly used?
Should they be used for everything that shouldn't modify member variables?
| Yes, const should always be used, when appropriate.
It lets your compiler check your application logic, statically asserting const-correctness for free!
Some people even say that const should be the default, and you should be forced to use mutable for what is non-constant.
|
4,691,608 | 4,691,703 | Copying non null-terminated unsigned char array to std::string | If the array was null-terminated this would be pretty straight forward:
unsigned char u_array[4] = { 'a', 's', 'd', '\0' };
std::string str = reinterpret_cast<char*>(u_array);
std::cout << "-> " << str << std::endl;
However, I wonder what is the most appropriate way to copy a non null-terminated unsigned char array, l... | std::string has a constructor that takes a pair of iterators and unsigned char can be converted (in an implementation defined manner) to char so this works. There is no need for a reinterpret_cast.
unsigned char u_array[4] = { 'a', 's', 'd', 'f' };
#include <string>
#include <iostream>
#include <ostream>
int main()
{... |
4,691,657 | 4,693,493 | Is it possible to "store" a template parameter pack without expanding it? | I was experimenting with C++0x variadic templates when I stumbled upon this issue:
template < typename ...Args >
struct identities
{
typedef Args type; //compile error: "parameter packs not expanded with '...'
};
//The following code just shows an example of potential use, but has no relation
//with what I am actu... | Another approach, which is slightly more generic than Ben's, is as follows:
#include <tuple>
template <typename... Args>
struct variadic_typedef
{
// this single type represents a collection of types,
// as the template arguments it took to define it
};
template <typename... Args>
struct convert_in_tuple
{
... |
4,691,686 | 4,691,760 | Classes Using their Own Getters/Setters | Let's say I have the following class:
class MyClass
{
private:
int Data;
public:
MyClass(int Init)
{
Data = Init;
}
int GetData() const
{
return Data;
}
};
Now, let's say I want to add a method that checks if Data is equal to zero. There are two ways to accompli... | I don't really like getters/setters for reasons that I won't go into here. They're covered in other questions. However, since you've asked about them, my answer will assume that I use getters/setters; it will not visit all the possible alternatives.
I'd use the getter, for the maintenance reasons to which you allude. I... |
4,691,968 | 4,694,360 | How can I marshal an out-of-process COM reference across process boundaries? | I have an out-of-process COM server that needs to keep an eye on things. This server runs as a service and is, internally, a singleton. For simplicity sake, I will call him BossCom.
I have another out-of-process COM server that is a worker. It is, for system stability, a single-use server (meaning that if you create... | As per the comments, this does indeed work out of the box. There is one additional detail though that makes it work.
Originally when I was looking at C# interfaces that dealt with copying interfaces, the argument type was IntPtr. Well, an IntPtr is just a long so it transfers the value as is and, as such, doesn't wor... |
4,692,118 | 4,692,171 | How do i use the Thread Local Storage (TLS)? | If I have thread handlers, how do i put them into TLS? MSDN doesn't provide any examples.
| Read this on MSDN, there is a link to example code in the article.
|
4,692,148 | 4,692,185 | Is there any online material for real world examples of Object oriented design problems? | I want to practice solving Object oriented design problems in C++.
Is there any online material with sample real world problems and solutions using design patterns ?
I searched but i couldn't get online material. Pls help me.
| https://stackoverflow.com/questions/tagged/design
|
4,692,297 | 4,692,386 | What size should the ImageList for a ListView be? | I have a ListView, and I don't know how big to make the ImageLists for large and small, and group header icons. How big should they be?
| I would suggest
32x32 pixels for large and group header
ex. in MFC
// The pointer to my image list.
extern CImageList* pmyImageList;
pmyImageList->Create(32, 32, ILC_COLOR8, 0, 4);
small might be 16x16.
see here for possible insight into Microsoft's sizing recommendations.
http://msdn.microsoft.com/en-us/library/ms997... |
4,692,337 | 4,692,363 | C++: Can boost::scoped_ptr be initialized inside a constructor? | Can a class member of type boost::scoped_ptr be initialized inside the class' constructor? How?
(Not in the initialization list)
| Yes. you can use reset() member function.
class foo {
public:
foo()
{
p.reset(new bar());
}
private:
boost::scoped_ptr<bar> p;
};
|
4,692,426 | 4,699,937 | largest memory map allocation size? | My System:
Physical memory: 3gb
Windows XP Service Pack 3 (32bit)
Swap file size: 30gb
Goal: To find the largest possible memory map size I can allocate on my machine.
When I run the following code to allocate 2gb memory map file, the call fails.
handle=CreateFileMapping(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE|SEC_CO... | The problem is file fragmentation. Physical memory (RAM) has nothing to do with anything here. In a virtual memory system, 'memory' is allocated from the file system. Physical memory is just an optimization to speed access to memory.
When you request a memory-mapped file with write access, the system must have a file w... |
4,692,468 | 4,692,582 | Can an x64 program access an x86 COM object on Windows x64? |
Possible Duplicate:
Access x86 COM from x64 .NET
I have a COM object which is only x86.
My program runs native x64 (not through WOW64 emulation).
Is it possible that my program can access the x86 COM object?
Or do I need to port the x86 COM object to x64?
| Yes, you can, but only in out-of-proc mode.
|
4,692,485 | 4,692,583 | What are the advantages of Managed Memory if .NET Bloats an App's Footprint? | I haven't been programming for very long and am new to C/C++. I've always used C# in the past, but I've switched to native code to write my first Win32 API application. I started in C but became increasingly maddened by trying to work without classes.
I've started porting some of the C to C++. Initially, I had the p... | Some of the memory footprint you are seeing will belong to the .Net Framework's runtime too.
Garbage collection helps eliminate a lot of programming overhead such as remembering to dealloc memory or to release objects. I've programmed a lot in C, Objective C and C# and I can certainly say that whilst garbage collection... |
4,692,547 | 4,726,550 | How can I build the 64-bit version of the Crypto++ dll? | I'm currently working on implementing the crypto++ libs into a c# app. It's all working fine in 32 bit.
However when I tried to build the c++ DLL in 64 bit, I got this error:
Error 1 error PRJ0019: A tool returned an error code from "Performing Custom Build Step" cryptopp cryptopp
I then changed the project settings ... | The problem was with the custom build step options under the project preferences. Just change the leading output directory folder from 'Win32' to 'x64' with x64 as your target platform. =/
|
4,692,656 | 4,692,798 | Parsing 32 bit integer in C program | I have a 32 bit integer, split into parts like this:
--------------------------------------
| Part1 | Part2 | Part 3 |
--------------------------------------
Part 1 higher 16 bits. (Part 2 + Part 3) = lower 16 bits.
Part 2 is 10 bits and Part 3 is 6 bits
I need help on how do we read and update part 1, ... | The theory to be used behind this are and, or and shift operations with masks.
To access some bits of the integer, first create a mask where there are ones in the bits you want to be used. Now apply and and(&) operation between the mask and the integer. According to the behavior of the & the bits where the mask is 0 wi... |
4,692,717 | 4,693,129 | Win32 reset event like synchronization class with boost C++ | I need some mechanism reminiscent of Win32 reset events that I can check via functions having the same semantics with WaitForSingleObject() and WaitForMultipleObjects() (Only need the ..SingleObject() version for the moment) . But I am targeting multiple platforms so all I have is boost::threads (AFAIK) . I came up wit... | A few things that you'll want to check/fix (note - I'm by no means saying that these are the only things - I've only had a quick look):
in your wait() function, you don't reset on an already signaled event if it's set up for auto_reset:
void wait()
{
boost::unique_lock<boost::mutex> LOCK(mx_flag);
if (flag) {
... |
4,693,014 | 4,693,060 | A variable seems to be de-referencing when I use it in a dynamic array (C++) | Here we are once again good people of the internet.
This is the code I'm using:
//This is what is in the header file
int *myArr[]; // A two-dimensional array representing holding the matrix data
//This is what is in the definition file
Matrix::Matrix(int n, int m)
{
myRows = n;
myColumns = m;
initialize();... | int *myArr[];
This is wrong! You've to tell the compiler the size also, of your array of pointer. How about if you declare int a[]. You're telling the compiler to create an array of int, of unknown size, which is not allowed in C++. That is why you cannot do that.
I would suggest you to do this:
int **myArr;
void Mat... |
4,693,028 | 4,693,084 | What does this Method declaration/definition mean? (something to do with passing an array?) | Hi I was stumbling through legacy code, and I came across a wierd method definition/declaration. I have an educated guess of what it does, but I cannot be 100% sure yet.
declaration:
const SomeEnumeratedId (&SomeMethod() const)[SOME_CONSTANT_VALUE];
definition
const SomeEnumeratedId (&SomeClass::SomeMethod() const)[SO... | It's the declaration of a const member function taking no parameters and returning a reference to an array of SOME_CONSTANT_VALUE const SomeEnumeratedIds.
It looks easier to understand with a typedef.
typedef const SomeEnumeratedId SomeArrayType[SOME_CONSTANT_VALUE];
SomeArrayType& SomeClass::SomeMethod() const
{
... |
4,693,300 | 4,693,807 | Do Bluegene systems support ltdl or any other kind of dlopen() support? | so I have some code that uses dlopen for loading libraries, and I want it to work on a bluegene system, but I don't have a bluegene to test things on, and I've never directly worked with one. Does bluegene support ltdl.h, or does it use something else? if so, what does it use?
| BlueGene/L does not support dynamic linking or loading of libraries. This is explained in the redbook in chapter 5.
Although Blue Gene/L uses the IBM XL
compilers, there are differences with
respect to all other IBM servers. In
particular, in the case of the IBM
pSeries Linux programming model, some
of the d... |
4,693,602 | 4,693,667 | Run some code in the main thread from a worker thread | I have to signal the Main thread to run some code from one of the worker thread.
That code must run in the main thread because of some COM issue( running it on the thread just fail).
I was starting to implement it with messages and event (i need to wait the code to be executed before going foward) when i remebered ther... | You can use PostThreadMessage WinAPI function to send WM_USER message to main thread. Then you can handle WM_USER in main thread and do some necessary actions.
|
4,693,747 | 4,693,857 | What is the performance of STL bitset::count() method? | I searched around and could not find the performance time specifications for bitset::count(). Does anybody know what it is (O(n) or better) and where to find it?
EDIT By STL I refer only to the Standard Template Library.
| I read this file (C:\cygwin\lib\gcc\i686-pc-cygwin\3.4.4\include\c++\bitset) on my computer.
See these
/// Returns the number of bits which are set.
size_t
count() const { return this->_M_do_count(); }
size_t
_M_do_count() const
{
size_t __result = 0;
for (size_t __i = 0; __i < _Nw; __i++)
__result += __... |
4,693,769 | 4,694,840 | USB proxy driver or equivalent solution? | Problem: Mediate USB traffic/data
I would like to accept inbound traffic on a specific USB port and replicate it exactly as outbound traffic on another specific USB port, in effect accomplishing a USB proxy. By extension, then, the connections need to be two-way. An additional requirement is that the port must be able ... | At my work we have used this Beagle USB Analyzer. It sits between device and host and captures all traffic without interruption. It works in windows and linux and functions even with USB 2.0 highspeed ports.
http://www.totalphase.com/products/beagle_usb480/
Highly recommended.
|
4,693,819 | 4,693,944 | C++ template string concatenation | I'm trying to define some variadic template like that:
typedef const char CCTYPE[];
template<CCTYPE X, CCTYPE... P> struct StringConcat { ... };
so that I could write sth like:
char foo[] = "foo"; char bar[] = "bar";
std::cout << StringConcat<foo, bar>;
and it printed foobar.
How can I do this, if it's possible in C+... | #include <boost/mpl/string.hpp>
#include <boost/mpl/insert_range.hpp>
#include <boost/mpl/end.hpp>
#include <iostream>
using namespace boost;
template < typename Str1, typename Str2 >
struct concat : mpl::insert_range<Str1, typename mpl::end<Str1>::type, Str2> {};
int main()
{
typedef mpl::string<'hell', 'o'> str1... |
4,693,852 | 4,694,173 | Something like a deque on large numbers of items, but small memory usage on small numbers? | I have a whole bunch of objects of a certain type, each of which may allocate a deque to hold other objects of that same type. I am using a deque because I need fast access at both ends, and because any particular object could possibly refer to many other objects.
However, it's likely the case that many or even most o... | You don't mention if you need other capabilities of vector or deque like random access iterators. If you don't this actually sounds like a good candidate to use list. It has good performance inserting and removing from both ends.
|
4,693,886 | 4,693,973 | Quick memory allocation / scope question | For example this class:
class RTPIPv4Address{
public:
RTPIPv4Address(int a, int b);
}
Silly question but... I just stumbled on code which initialized a class instance like that with for example
RTPIPv4Address adr(2,2);
Now I am wondering, is this just another syntax for the usual
RTPIPv4Address* adr ... | Yes, the first example is stack-allocated and will have it's destructor called and be deallocated as soon as the variable loses scope. For a local variable, this usually happens when the function returns, though you can force it to lose scope earlier with curly braces.
function
{
RTPIPv4Address adr(2,2);
ret... |
4,693,951 | 4,694,035 | Source directories in Visual Studio 2010 | I am using OF in my project and I want to use some add-ons but I have to add .cpp files to my project in order to compile them. I don't like it. Is there any option so I could specify a folder to scan for source files and compile every .cpp file it finds?
I thought it might be Source Directories in VC++ Directories sec... | If you want to compile sources using Visual Studio, you will have to add them to your project.
There is nothing wrong about adding external sources to your project in a nice filter.
You can also create a makefile to be used by Visual Studio which will list sources you need.
|
4,694,012 | 4,694,245 | CreateFileMapping() name | Im creating a DLL that shares memory between different applications.
The code that creates the shared memory looks like this:
#define NAME_SIZE 4
HANDLE hSharedFile;
create(char[NAME_SIZE] name)
{
hSharedFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 1024, (LPCSTR)name);
(...) //Other ... | I suppose you should increase NAME_SIZE value.
Do not forget that array must be at least number of chars + 1 to hold \0 char at the end, which shows the end of the line.
LPCSTR is a pointer to a constant null-terminated string of 8-bit Windows (ANSI) characters and defined as follows:
LPCSTR defined as typedef __nullte... |
4,694,181 | 4,694,311 | template-id does not match any template delcaration | I'm getting a frustrating compiler error I can't seem to work around. It's to do with the template specialization but I can't see what's wrong...
../../include/thread/lock_guard.inl:23: error: template-id 'lock_guard<>' for 'thread::lock_guard<thread::null_mutex>::lock_guard(thread::null_mutex&)' does not match any tem... | A full class template specialization is not a template any more, it is a regular class. Hence you don't need template<> when defining its members:
lock_guard<null_mutex>::lock_guard(null_mutex&)
{
/* do nothing */
}
lock_guard<null_mutex>::~lock_guard()
{
/* do nothing */
}
|
4,694,301 | 4,694,388 | Resources for UI Menu Development | My apologies if this isn't the right exchange for this type of question. I was wondering if there are any resources on best practices and techniques for designing a custom full screen UI like that used on an ATM.
For example problems like supporting multiple resolutions, used fixed vs relative locations for text and bu... | I think that Qt Quick (aka QML) is the one that should suit your needs.
There are few good examples how QML works Here
QML is very effective and very easy to create. It can be used as standalone QML application, where business logic is done with javascript, or you can use it with C++ where you have very good control ov... |
4,694,631 | 4,701,183 | How to implement async file download in C# ActiveX | I'm doing a reimplementation of a C++ ActiveX control in C#.
The C++ Version uses a property class which inherits from CDataPathProperty. How should the following code look in C#?
class CFileProperty : public CDataPathProperty
{
DECLARE_DYNAMIC(CFileProperty )
...
}
Any references appreciated.
What I'm actually t... | I couldn't find a CDataPathProperty conterpart in C#. So I was looking for an alternative approach.
In order to handle the object tag with content type and data attributes correctly one can implement IPersitMoniker. The only relevant method is Load.
public void Load(int fFullyAvailable, IMoniker pmk, IBindCtx pbc, ui... |
4,694,857 | 4,695,653 | Ordered and unordered STL containers | What are differences between ordered and unordered STL containers?
| The ordered and unordered apply to containers transitively.
What you are interested in is the Sequence, that is the order in which elements will appear when you iterate over (possibly a slice of) the container.
Sequence are more general though, so for this kind of concept I'll refer to the Martin Broadhurst's copy of t... |
4,694,892 | 4,695,012 | Communicating with ports with c++ or c#? | I'm starting to write a program which communicates with serial/parallel ports. I'm not sure whether I should write it with C# or C++.
I prefer C# because it's my preferred language and I have written applications (high level) with it. But I'm not sure if it can handle port communication in all circumstances. (For exa... | Since you need fine control over the port (ie, the ability to bit-bang and send raw data), then you need an extra component to do this in .NET. See http://www.lvr.com/parport.htm for an example.
There is no managed way to do this, but by using external components, you can develop in your familiar environment. This is... |
4,695,021 | 4,695,686 | Sharing data generated by one thread with an array of other threads | Having a thread that from time to time (thread with one function in infinite loop, data is generated when function finishes) generated some data (for example random int).
And heaving 3 other threads that need to get that generated data from time to time (threads with one function in infinite loop, data is required when... | Here is a primitive example, that demonstrate how to create a thread that produces random numbers and puts them in a queue, and three consumer thread which extract random numbers from the queue and print them if the random numbers are odd only. This example can be vastly improved, and many best practices are not follow... |
4,695,212 | 4,695,331 | memcpy() safety on adjacent memory regions | I recently asked a question on using volatile and was directed to read some very informative articles from Intel and others discussing memory barriers and their uses. After reading these articles I have become quite paranoid though.
I have a 64-bit machine. Is it safe to memcpy into adjacent, non-overlapping region... | Safe, yes. Performant, no- in this limited example, at least. Remember that one cache line cannot be in two cores at once. You will force core A to wait while core B writes to the buffer, and then wait while the memory is transferred, and then write to it. Multi-core memory copies should be very large in size to avoid ... |
4,695,448 | 4,695,557 | C# ASCII GetBytes how to set which character is used for unrecognizable conversion? | I am porting some code from native C++ to C# and I need to do the following:
ASCII.GetBytes when it encounters a unicode character it does not recognize it returns to me character with decimal number 63 (question mark) but in my C++ code using WideCharToMultiByte(CP_ACP, ... when it encounters a character it doesn't kn... | In C#, you can use the DecoderFallback/EncoderFallback of an encoding to decide how it will behave. You can't change the fallback of Encoding.ASCII itself, but you can clone it and then set the fallback. Here's an example:
using System;
using System.Text;
class Test
{
static void Main()
{
Encoding ... |
4,695,766 | 4,695,783 | const variable paradox | if I have some expression on c++:
const int x = 3;
can I say that x is a variable? It seems very strange cause x is not variable cause I can't change it, thanks in advance for any expanations
Edited
P.S. thanks for all answers, I understood that by definition of C++, answer for my question may be yes, do You know some... | Yes. x is a variable, even though you cannot (legitimately) change its value.
Effectively, in C++, an object that has a name is a "variable."
|
4,695,843 | 4,695,901 | Does this C++ casting to enum have problems? | Given the following code:
enum Options
{
Surf = 0x01,
Out = 0x02
};
Options all = (Options) ( Surf | Out);
Does this casting have problems?
If this casting make sense, then why?
Based on my understanding, Options only defines two variables. How does the value 0x03 makes sense?
|
Does this casting have problems?
No.
If this casting make sense, then why? Based on my understanding, Options only defines two variables, how the value 0x03 makes sense?
The enumeration type Options has two named enumerators, but the range of values that it represents is large enough that it can be used as a bitfie... |
4,695,896 | 4,698,222 | CodeBlocks, GCC: change project language c and c++? | When I select console project to start with, it lets you to select C or C++. But once its created, I can't figure out how to change it. Plus, when you create a Win32 GUI application, it doesn't give you the option at all and its default is C++.
Where can I change to C? I have been looking in all the project settings fo... | The only tangible difference between selecting C vs C++ when you create a project is which compiler is invoked for the translation units during a build. Code::Blocks currently does not provide a way to directly change this after project creation. That is to say you would have to change each source file one at a time t... |
4,696,006 | 4,696,269 | How to create this animated arrow? | I have just installed a program on my pc and after that, an animated arrow is appeared on the screen showing me a new element on the bar:
How can I create this animated arrow ? What API do I have to use ?
| It can be made with a window that has a custom shape. One of my colleagues documented how to do this in .NET here:
http://www.atalasoft.com/cs/blogs/jake/archive/2008/05/09/beauty-is-only-skin-deep-skinning-your-winforms-application.aspx
http://www.atalasoft.com/cs/blogs/jake/archive/2008/05/19/beauty-is-only-skin-dee... |
4,696,007 | 4,696,098 | c++ How to save the use of a temporary variable | I have the following code in C++:
string str="a b c";
stringstream sstr(str);
vector<string> my_vec((istream_iterator<string>(sstr)),
istream_iterator<string>());
Is there any way to save the use of sstr, something like the following?
vector<string> my_vec((istream_iterator<string>(str)),
... | istream_iterator's argument needs to be able to bind to a non-const reference, and a temporary cannot. However, (as Alf points out), ostream happens to have a function, flush(), that returns a non-const reference to itself. So a possibility is:
string str="a b c";
vector<string> my_vec(istream_iterator<string>(
... |
4,696,285 | 4,696,699 | Update cell in QTableView with new value | I'm new, I'm learning to program in Qt and my English is not very good, my problem is that when I update a cell in a QTableView to use its value in another cell, it uses the previous value and not the new, I show them the code as I am doing, thanks.
bool MainWindow::eventFilter(QObject * watched, QEvent * event)
{
... | This seems to be quite ditry approach to do this for several reasons:
If you want the same value to be presented in different columns, or you have a column that depends on the value of another column, then you should probably design accordingly the model that feeds the view.
setData that you are calling is a pure virt... |
4,696,360 | 4,696,511 | Ping broadcast on Win XP SP3 | I'm trying to ping the broadcast address 255.255.255.255 on WinXP SP3.
If I use the command line, I get host error:
C:\>ping 255.255.255.255
Ping request could not find host 255.255.255.255. Please check the name and try again.
If I try a C++ program using the iphlpapi, IcmpSendEcho() fails and GetLastError returns 1... | This doesn't work in Windows as I know. In Linux OS you can ping 255.255.255.255, but routing protocol will not relay 255.255.255.255 broadcasts outside of the local network.
What are you trying to achieve? Are you ready that every computer on the connected earth will respond? I'm scared...
By the way, you should be ... |
4,696,551 | 4,696,591 | Random characters displayed when printing array of characters | This is my problem. I am reading a file in binary mode, appending the bytes to an int array, and printing the values after. My problem is, when I cout my results, random characters are being attached in the stream.
comp.txt:
this text is a testt1
main.cpp:
#include <iostream>
#include <fstream>
#include <time.h>
usi... | When you read in temp, you overwrite all 4 characters with data, leaving you without a NULL terminator. cout.operator<<(char*) expects a null-terminated string, so it's printing as many characters as it can until it reaches a null terminator. Making temp be 5 characters long, all '\0', but keeping number of bytes read ... |
4,696,653 | 4,699,978 | Attaching a Xerces-C DOMElement from a Xerces-C DOMDocument to another one | I questioned before about a similar problem in RapidXml, I want to know, now, the same but using Xerces-C.
I am working on a c++ application that needs to parse xml.
Consider the following:
xml file: file1.xml
<root>
<node1>value1</node1>
<node2>value2</node2>
</root>
xml file: file2.xml
<anotherroot>
<anothe... | DOMDocument::importNode is a DOM Level 2 function that was designed to solve this exact problem:
DOMElement * el1Imported = doc2->importNode(el1, true);
el2->appendChild(el1Imported); // element is now in right document
|
4,696,907 | 4,697,103 | zlib c++ and extracting files | I have started to use zlib 1.2.5 and I do not see any routine to extract from a zip file? I read about a minizip application, part of the distribution.
Is that how it is supposed to be done?
| Yes, it does it well. (But if ever you don't like C code, you should look at 7-zip SDK that have code in C++ and C#.)
All the functions to browse and uncompress the files from a zip archive are in unzip.h
All the functions to compress and add files to a zip archive are in zip.h
(look at contrib\minizip\unzip.h and co... |
4,696,953 | 4,697,018 | Can all cases of tstring be replaced with wstring | For example, I am updating an old project and I am wondering can I CTRL+H and replace all tstring with wstring? Is this ok? Thanks.
| tstring is just a typedef based upon whether the build is unicode or not. It will translate to wstring if the build unicode or simple string if it is not. So if your build will always be unicode then you can replace all the instances of tstring with wstring.
|
4,697,180 | 4,697,356 | Template function as a template argument | I've just got confused how to implement something in a generic way in C++. It's a bit convoluted, so let me explain step by step.
Consider such code:
void a(int) {
// do something
}
void b(int) {
// something else
}
void function1() {
a(123);
a(456);
}
void function2() {
b(123);
b(456);
}
vo... | In order to solve this problem with templates, you have to use a template template parameter.
Unfortunately, you cannot pass template template function as a type, because it has to be instantiated first. But there is a workaround with dummy structures. Here is an example:
template <typename T>
struct a {
static vo... |
4,697,188 | 4,697,202 | How to properly create an entry point on an external .dll resource written in C++ consumed in C# | Long time reader, first time poster. One day I hope to be answering questions on here...
So it's kind of similar to: "Unable to find an entry point named [function] in dll" (c++ to c# type conversion)
But I can't seem to apply the same solution...
Basically, I wrote a new Method:
Defined in the header file of the C++ p... | You are encountering C++ name mangling. Declare the C++ functions as extern "C". So, in your C++ module...
extern "C" __declspec(dllexport) bool IsDataValid();
You really don't need the entry point specification attribute either. Your C# declaration will be:
[DllImport("CarChipSDK_C_Sharp.dll")]
[return: MarshalAs(... |
4,697,264 | 7,416,987 | Writing a 3D rendering browser plugin | I understand that it's possible to write a plugin for a browser which lets you render to the browser window, so you can effectively run a normal app within the browser. NOT using JS or client technology, but a plugin which basically wraps your application - in our case C++ which does 3D rendering using DirectX or OpenG... | FireBreath is a great cross-platform, cross-browser library for developing C++ browser plugins.
|
4,697,349 | 4,697,382 | what hash function is being used by boost c++ unordered_map? | what hash function is being used by boost c++ unordered_map ? I meant what kind of hash algorithms being used by boost::hash, for example
template<> struct hash;
Thanks
| It depends on the type you are using, if you look here the boost::hash template class is specialised:
template<> struct hash<bool>;
template<> struct hash<char>;
template<> struct hash<signed char>;
template<> struct hash<unsigned char>;
template<> struct hash<wchar_t>;
template<> struct hash<short>;
temp... |
4,697,419 | 4,697,554 | C/C++: Float comparison speed | I am checking to make sure a float is not zero. It is impossible for the float to become negative. So is it faster to do this float != 0.0f or this float > 0.0f?
Thanks.
Edit: Yes, I know this is micro-optimisation. But this is going to be called every time through my game loop, and I would like to know anyway.
| Consider, for entertainment purposes only:
Only 2 floating point values compare equal to 0f: zero and negative zero, and they differ only at 1 bit. So circuitry/software emulation that tests whether the 31 non-sign bits are clear will do it.
The comparison >0f is slightly more complicated, since negative numbers and 0 ... |
4,697,440 | 4,697,458 | How would i go about creating a WebPage Copier Application | Hi i do a lot of research on the web but at most cases i don't have the connectivity to the WWW at all of time of my research. So i would like to get started on creating a Website Copier Application... I am aware of HHTrack Website Copier but that program has it's limitations for example it cant copy any of the Wikiped... | Wget --mirror http://example.com
|
4,697,540 | 4,697,588 | C/C++: Float Arithmetic Question | If a float is repeatedly multiplied by a number that is less than one, is it plausible that the the float could become zero?
Here is an example:
float number = 1.0f;
for ( int i = 0; i < ONE_BILLION; ++i )
{
number *= 0.01f;
}
But please don't limit your answer to the example.
Thanks!
| Yes, when the result of the multiplication would be smaller than the representable number closest to zero, it will become zero. With IEEE floating point, this will happen for any multiplier less than or equal to 0.5f (but greater than zero); however, if the multiplier is even slightly larger than 0.5f (for instance, 0... |
4,697,584 | 4,698,357 | Sparse O(1) array with indices being consecutive products | I'd like to pre-calculate an array of values of some unary function f.
I know that I'll only need the values for f(x) where x is of the form of a*b, where both a and b are integers in range 0..N.
The obvious time-optimized choice is just to make an array of size N*N and just pre-calculate just the elements which I'm go... | There doesn't seem to be a lot of structure to take advantage of here. If you're asking if there is a way to arrange to arrange the table such that you can avoid storage for entries that can't happen (because they have a prime factor larger than N), you can't save much. There is a theory of smooth numbers which state... |
4,697,628 | 4,697,645 | Where are Windows Messages such as WM_LBUTTONDOWN, WM_COMMAND, and WM_CLOSE defined in the win32 C/C++ API? | I'm running through theForger's Win32 API Programming Tutorial. On page 4 he suggests it would be handy to find the list of #define statements in the API header files which list all the WM_* messages. I decided it probably would be worth my while to take a gander at them all, so I tried to find them, but was unsuccessf... | Try winuser.h in the platform SDK include folder.
|
4,697,648 | 4,697,661 | Why does the order of destruction for data member matter? | I see in some book that the destruction order of data members in class should be in the reverse order of their construction order. What is the reason of this rule? Any examples are appreciated.
| This is, in large part, for consistency. When multiple objects are created in sequence, they are always destroyed in the reverse order. For example, consider the following example with automatic variables:
{
A a;
B b(a);
} // b.~B() is called, then
// a.~A() is called
Here, b uses a. By guaranteeing ... |
4,697,859 | 4,798,180 | Mac OS X and static boost libs -> std::string fail | I'm experiencing some very weird problems with static boost libraries (Boost 1.45.0-2 from MacPorts, compiled as fat/universal (x86/x86_64) libraries) under Mac OS X 10.6.6 with GCC 4.5.
The error message is
main(78485) malloc: *** error for object 0x1000e0b20: pointer being freed was not allocated
*** set a breakpoint... | The problem was that Boost has been built using Apple's GCC 4.2.1, whilst I've been building the project using a different compiler.
As I tried to link the static Boost libraries, also the GCC 4.2.1 libstdc++ was put into the binary.
However, at the same time the other GCC version was linking in its libstdc++ and name ... |
4,697,989 | 4,698,014 | c++ assignment deletes source of assigned value | I have a class (simplified):
class a {
private:
std::vector<a> arguments;
public:
std::vector<a> getargs() { return arguments; }
};
Suppose, the class has a member function:
void a::bubble() {
arguments = arguments[0].getargs();
}
Is this kosher (in that the source of the data, arguments[0], is deleted ... | Yes, it is ok. The getargs() function is done before the assignment. It creates a temporary that exists for the lifetime of the complete instruction statement (everything to ;). That temporary is used in the call to the assignment operator for std::vector (works for raw types too though). Everything is kosher and w... |
4,698,098 | 4,698,184 | C++ char array to int and int to char array | I've been trying to do this but I wasn't able to find any good source for it.
Basicly, I want to convert a char* variable (byte array) into an int and vis-versa.
Thanks.
| If you're trying to convert a byte array into an int it is sufficient to use a reinterpret_cast. Technically, this is UB, but if you know the bytes are in the right format, it usually results in exactly what you're asking for.
This is while noting the difference between a char* STRING and a char* BYTE ARRAY.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.