question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
3,973,708 | 10,163,863 | XCode, standard C++ and ifstream file handling | Recently, I figured out that Xcode could be used to write normal C++ programs.
My problem is with the following code :
#include <iostream>
#include <fstream>
using namespace std;
int main (int argc, char *argv[]) {
char operation='0';
int operand=0;
//open file for reading
ifstream ifile;
ifile.op... | I did not figure out what it was, but reinstalling XCode solved the problem.
|
3,973,982 | 3,974,254 | How to tell if current thread is impersonating? | I have a c++ application in which threads could impersonate using LogonUser/ImpersonateLoggedOnUser, and then revert impersonation using RevertToSelf. I ran across the bug which caused thread to impersonate this way twice. I want to prevent this by testing if current thread is already impersonating and throw exception ... | You can use OpenThreadToken. If a thread has a token then it is impersonating; if it doesn't have a token then it is not impersonating.
|
3,973,991 | 3,973,997 | Display 0.999 as 0.99 | How can I display a float number = 0.999 as 0.99?
The code below keeps printing out 1.00 ? I thought using setprecision(2) specifies the number of digits after the decimal point?
#include <iostream>
#include <iomanip>
using namespace std;
int main(int argc, char** argv)
{
const float numberToDisplay = 0.999... | setprecision(2) will round to the nearest two-digit floating point number, in this case 1.0. If you wanted to truncate (i.e. get 0.99) you could always multiply the number by 100 (i.e. 10^[num-digits]), cast to an int, and then divide it back into a float. A little messy but it gets the job done.
const float numberToD... |
3,974,005 | 3,980,157 | How can I extract a std::string with boost.spirit? | Using boost.spirit I try to parse simple command line of the form command:param1 param2...
to do so I created this parser:
(+(char_ - ':'))[ref(cmd) = _1]
>> ':'
>> (*char_)[ref(params) = _1]
The attribute types of the two compounds parser is vector, so if cmd and params are of type vector this work. However if they a... | Sure, when you use semantic actions no automatic attribute propagation will happen. Both your parsers (+(char_ - ':') and *char_) expose a std::vector<char> as their attribute. Therefore, _1 refers to a std::vector<char> as well. If cmd and params are instances of std::string it will not compile as no assignment from a... |
3,974,070 | 3,974,213 | linking with a pragma with g++ | In Visual C++, one may link to a library in the code itself by doing #pragma comment (lib, "libname.lib"). Is something similar possible in g++?
| The Boost Config library has some support for autolinking, using the relevant compiler-specific code for the particular compiler. However, the docs note that the GCC toolchain doesn't support autolinking:
Auto-Linking
Most Windows compilers and linkers
have so-called “auto-linking support,”
which eliminates the se... |
3,974,111 | 3,974,210 | In C++, removing an object from a list | I'm writing a program which is more or less like this :
#include <list>
list<MyClass> things;
class MyClass {
// some stuff
void remove() {
things.remove_if(THING_IS_ME);
}
};
What do I need to write instead of THING_IS_ME?
In other words, I'm using a global STL list as a collection of things. At so... | (Originally a set of comments, but rewritten as an answer after discovering what the OP actually wanted to do.)
You do realize that the STL containers store copies of things you insert, right? That means instances of MyClass better be comparable (e.g. via operator==) - you can't just compare the addresses as they will ... |
3,974,168 | 3,974,691 | Overloading implicit in c++ | full disclosure - this is for a homework assignment. And I normally would not ask for homework help, but here it is.
I'm asked to provide 5 examples of "overloading implicit in c++". I'm sure he is referring to operator overloading for types such as char, int, float, etc in iostream and the types themselves.
I unders... | .
It's late. I'm tired. But this is intriguing...
"overloading implicit in c++" is far from clearcut.
This smacks of someone creating their own terminology. Perhaps they are merely unable to view their own writings from a third-party perspective and are therefore being obtuse. More than likely, your teacher is busy... |
3,974,281 | 3,974,499 | Thread pool shared resource locking problem | I have a UDP based application that is implemented using a thread pool.
Messages are pushed onto a queue and the thread pool is woken when there are things to do or messages on the queue. The thread pool processes each of the messages and hands them off to
session objects which hold some state. i.e. the UDP packets ar... | What I'm doing is making the resource an object.
A skeleton version looks
like this:
e.g.
class Resource
{
public:
enum {READ, WRITE};
void Open(int mode=READ)
{
if (mode == WRITE){
Lock();
// Access resource
} else if (mode == READ){
// Try to get read access (scoped version)
... |
3,974,293 | 3,974,441 | Windows 7 NotifyIcon GUID spoof-protection | I am currently working on learning some different aspects of WINAPI, including features introduced in windows 7.. One of those is using a GUID as identifier for a Notification icon.
As can be read on the MSDN, the GUID is bound to the executable by path, the first time the notification icon is added. This page in quest... | It's documented:
If the path must be changed, the
application should clear the existing
GUID registry information before
moving the binary file to a new
location and reregistering it with a
new GUID. Any settings associated with
the original GUID registration will be
lost.
This also occurs in the case of... |
3,974,622 | 3,974,628 | How can I manage bits/binary in c++? | What I need to do is open a text file with 0s and 1s to find patterns between the columns in the file.
So my first thought was to parse each column into a big array of bools, and then do the logic between the columns (now in arrays). Until I found that the size of bools is actually a byte not a bit, so i would be wast... | you can use std::vector<bool> which is a specialization of vector that uses a compact store for booleans....1 bit not 8 bits.
|
3,974,646 | 3,974,682 | How do I pass/catch/respond to Python's KeyboardInterrupt in C++? | I have a simple library written in C++ which I'm creating a Python wrapper for using boost.python. Some functions take a long time to execute (over 30 seconds), and I would like to make it interruptible so that when I hit ctrl-d to trigger KeyboardInterrupt in the python interpreter, I'm somehow able to respond to that... | Call PyErr_CheckSignals() every so often.
|
3,974,657 | 3,974,680 | Getting error reading from 0xfefefefe when destructor is called | I have made a c++ wrapper for an allegro bitmap. I create an AguiBitmap as a global variable for testing, then later I say,
bitmap = AguiBitmap("somepath");
after allegro has been initialized.
However, when I close the application, it crashes in the bitmap's destructor. If I do al_destroy_bitmap(0); its fine, but the... | You have not defined a copy constructor (edit: or copy-assignment operator).
bitmap = AguiBitmap("somepath");
That line constructs a temporary AguiBitmap which allocates the bitmap, then assigns to bitmap variable and the temporary is destroyed, releasing the bitmap. Therefore, any use of bitmap after this line is inv... |
3,974,796 | 3,974,851 | in c++ main function is the entry point to program how i can change it to an other function? | I was asked an interview question to change the entry point of a C or C++ program from main() to any other function. How is it possible?
| In standard C (and, I believe, C++ as well), you can't, at least not for a hosted environment (but see below). The standard specifies that the starting point for the C code is main. The standard (c99) doesn't leave much scope for argument:
5.1.2.2.1 Program startup: (1) The function called at program startup is named ... |
3,975,070 | 3,975,118 | Comparing pointers for self-assignment | I am trying to overload the = operator on a simple C++ class called Set that contains a dynamic array of ints. For the = operator, I first want to check for self assignment, so I wanted to compare 2 pointers to make see if they have the same memory address. Here's the code:
Set& Set::operator=(const Set& setEqual)
{
//... | To detect self-assignment you need
if(&setEqual == this)
you should never use
if(setEqual == *this)
for detecting self-assignment as the latter statement will invoke comparison of the objects, which might be overloaded in the way you don't expect and is likely slower as well.
|
3,975,122 | 3,975,140 | How to set FPS to 30 with opengl? | so how? my app is running at 60FPS, but i want 30.
| Assuming you have a target frame rate, you could measure how long its been since the last time you finished rendering. From there, you could sleep for targetMsPerFrame - timeElapsed.
|
3,975,313 | 3,975,401 | Translate error codes to string to display | Is there a common way in C++ to translate an error code to a string to display it?
I saw somewhere a err2msg function, with a big switch, but is that really the best way?
| Since C++ does not allow automatic 'translation' from enum values to enum names or similar, you need a function to do this. Since your error codes are not somehow defined in your O/S you need to translate it by yourself.
One approach is a big switch statement. Another is a table search or table lookup. What's best depe... |
3,975,551 | 3,976,311 | How to Disable Dynamic Frequency Scaling? | I would like to do some microbenchmarks, and try to do them right. Unfortunately dynamic frequency scaling makes benchmarking highly unreliable.
Is there a way to programmatically (C++, Windows) find out if dynamic frequency scaling is enabled? If, can this be disabled in a program?
Ive tried to just use a warmup phase... | In general, you need to do the following steps:
Call CallNtPowerInformation() and pass SystemPowerCapabilities to InformationLevel parameter, set lpInputBuffer and nInputBufferSize to NULL, then set lpOutputBuffer to SYSTEM_POWER_CAPABILITIES structure, and set nOutputBufferSize to the size of the structure. After thi... |
3,975,567 | 3,975,581 | Get a copy of "this" (current instance) in C++ | I want to have a copy of the currently running instance.
When i change a value in the copy, original object is also affected. The copy acts as an instance.
How to avoid this? I need to create an independent copy of the calling object.
Set operator+(Set s){
Set temp = *this;
for(int i=0; s... | The problem is that Set temp = *this; makes a shallow copy, not a deep copy. You will have to modify the copy constructor and assignment operators for the Set class so that they make copies of all the member/contained objects.
E.g:
class Set
{
public:
Set()
{
elements = new SomeOtherObject[12];
... |
3,975,624 | 3,975,712 | Should I use dynamic cast in the subject observer pattern with templates | By referring to article Implementing a Subject/Observer pattern with templates
template <class T>
class Observer
{
public:
Observer() {}
virtual ~Observer() {}
virtual void update(T *subject)= 0;
};
template <class T>
class Subject
{
public:
Subject() {}
virtual ~Subject() ... | The best would surely be not to have to cast at all. You could change your notify() function so that it takes the right argument:
void notify (T* obj)
{
std::vector<Observer<T> *>::iterator it;
for (it=m_observers.begin();it!=m_observers.end();it++)
(*it)->update(obj);
}
Now derived c... |
3,975,654 | 3,976,627 | How to convert ISO-8859-1 to UTF-8 using libiconv in C++ | I'm using libcurl to fetch some HTML pages.
The HTML pages contain some character references like: סלקום
When I read this using libxml2 I'm getting: ׳₪׳¨׳˜׳ ׳¨
is it the ISO-8859-1 encoding?
If so, how do I convert it to UTF-8 to get the correct word.
Thanks
EDIT: I got the solution, MSalt... | Have you seen the libxml2 page on i18n ? It explains how libxml2 solves these problems.
You will get a ס from libxml2. However, you said that you get something like ׳₪׳¨׳˜׳ ׳¨. Why do you think that you got that? You get an XMLchar*. How did you convert that pointer into the string above? Did you perhaps use a debugger... |
3,975,841 | 3,975,865 | Are standard library warnings normal? | I'm learning my way around visual studio at the moment. If I've turned set /Wall I'll be greeted with a seemingly unhealthy amount of warning messages although my application will compile just fine.
Is this normal? Changing the error level will stop the messages. It looks as if they are all related to the C++ STL or it... | With g++ -Wall does not turn on all warnings, just a practical subset. I suspect that with MSVC /Wall turns on more warnings than is practical. MSVC is very enthusiastic about warnings.
With MSVC use /W4 for high warning level.
You'll have to turn off MSVC sillywarnings; you can use my anti-MSVC-sillywarnings header fo... |
3,976,213 | 3,976,278 | C++ STL:: what's the difference between inplace_merge and sort | As far as I can tell, inplace_merge does the exact same thing as sort, except it only works in certain circumstances (When the container is already in two sorted parts).
In other words, is there an difference between these two:
int first[] = {1,3,5,7};
int second[] = {2,4,6,8};
vector<int> v(8);
vector<int>::iterator i... | Their complexity is not the same:
sort() has a worst case of O(N²), depending on the sorting algorithm used by your STL implementation.
inplace_merge() has a worst case of O(N*log(N)) and a best case of O(N-1), so it will never be slower than sort() (with the same inputs).
Also, as others have pointed out, inplace_me... |
3,976,251 | 3,976,359 | Retrieve a user's First and Last Name, given its login name, inside a windows server domain | Given that I am on a workstation, that is inside a Windows Server domain.
In my data, I have the login name of the operator who has created the data.
When I print a presentation of this data, I want to display the first and last name
of this operator, which may be logged on another workstation of the domain... or even ... | The Win32_UserAccount WMI class, has a FullName property which sounds like it might be a possibility.
Maybe a query like:
SELECT * FROM Win32_UserAccount WHERE Name='username'
And then you can query the results from that query for the FullNames.
This MSDN page has information about using WMI from C++: WMI C++ Applicat... |
3,976,622 | 3,977,138 | converting float to int: rounding in complex cases (ceil() and floor() not usable) | I want to convert a floating point value to its integer representation. As this will be used in comparisons, the default rounding mode (round_to_nearest) is not appropriate for me. As far as I know I can't specify the rounding mode to the FPU in a C++ standard compliant way (not even in C++0x). What are the other ways ... | If both 12.3 and 14.7 are floats then in IEEE 754 both 13.0 and 14.0 are floats (more generally: given two non-integer floats, all integers in between are floats as well). Therefore, under IEEE 754, floor and ceil always work correctly (note that x86 uses IEEE 754 representations).
If you're not under IEEE 754, note th... |
3,976,661 | 3,976,719 | Upgrading from C++ to C# | I have a large application written in C++, For various reasons I am going to rewrite it in C#, I have done plenty of Delphi to C#, VB to C# but C++ to C# I have never done, although I am competent in C++ I want this to be as smooth a conversion as possible.
Mainly what I am asking is what pitfalls await me in this conv... | Main pitfall - do not think it's an upgrade. These are DIFFERENT languages, and in many places you will need complete different approach to the problems. So you should think reimplementation with minimal code reuse.
This article is decent.
|
3,976,935 | 3,976,954 | best way to return an std::string that local to a function | In C++ what is the best way to return a function local std::string variable from the function?
std::string MyFunc()
{
std::string mystring("test");
return mystring;
}
std::string ret = MyFunc(); // ret has no value because mystring has already gone out of scope...???
| No. That is not true. Even if mystring has gone out of scope and is destroyed, ret has a copy of mystring as the function MyFunc returns by value.
|
3,977,188 | 3,978,061 | POSIX Threads behaviour different between HP-UX and Solaris 10 | I'm migrating a multi threaded application from HP-UX to Solaris and so far, everything is OK except for one thing! The application has a thread that is handling the signals and, when some of them are received, it runs some cleaning (logging, kill child processes and so on).
I've reduced the code as much as it was poss... | This is rather unorthodox way to handle signals. If you want to marry the signals and threads, better choice would be to have the usual signal handlers from where the signal is serialized internally to another thread which is responsible for the actual handling of the event.
That is also a better option, as it is undef... |
3,977,488 | 3,988,449 | vmime, libgnutls, and libgcrypt problem? Assertion failed! | I am developing an application in C++ to check the users email accounts. This application uses the vmime library to do the processing related to POP3/IMAP/SMTP protocols.
I designed the application to work continuously. So, it has to be stable enough!
Sometimes, the application suddenly stops giving this strange error:... | It seems that vmime has a bug related to the use of gnutls in the case of multi-threaded application.
I did what the documentation of gnutls says in the following page:
http://www.gnu.org/software/gnutls/manual/gnutls.html#Multi_002dthreaded-applications
I just the added the line:
gcry_control (GCRYCTL_SET_THREAD_CBS, ... |
3,977,564 | 3,977,733 | Member pointers or reference arguments? | I have the following problem.
I got a class PluginLoader which oversees loading of plugins. It divides sub-stages of work to other classes like Plugin. Plugin calls functions of PluginLoader in its processing. Let's call that function AddData. Here, PluginLoader has to check if the data it receives is duplicate. For th... | You could pass a ConflictResolver& to the PluginLoader constructor. You can now guarantee that the object is not null.
|
3,977,615 | 3,978,321 | Boost preprocessor: Sample not working | I tried to compile a sample from the Boost.Preprocessor library which is:
#include <boost/preprocessor/seq/insert.hpp>
#define SEQ (a)(b)(d)
BOOST_PP_SEQ_INSERT(SEQ, 2, c) // expands to (a)(b)(c)(d)
on Visual Studio 2008 and I get the error error C2065: 'b' : undeclared identifier
Is there a problem with the sample or... | Well, you are trying to compile a source file containing:
(a)(b)(c)(d)
I suppose you should either put this in a context where this code makes sense, or just run the preprocessor (without compiling the result).
|
3,977,688 | 3,978,198 | Cast-order for inherited classes? | I've got 3 classes:
class Super
{
virtual int getType() { return 1; }
}
class Special : public class Super
{
virtual int getType() { return 2; }
}
class SpecialSpecial : public class Special
{
virtual int getType() { return 3; }
}
And I've got a function which takes an std::vector<Super*> as argument:
vo... | 2 possible answers here:
1) If you think you need to know what type an object really is, then maybe your encapsulation is wrong. Perhaps handleClasses() should be calling a method on the object, and each class should provide a different implementation?
2) If this is one of the rare times when you really need to know t... |
3,977,806 | 3,978,133 | How to do C++ development on Windows with Eclipse and CDT? | I would like to do some C++ development on Windows using Eclipse and the CDT plugin. I use Eclipse Helios and have installed the CDT plugin. But after that I can still not create a C++ project from File > New > Project, there is still only Java Project available there.
How to solve this? and do I have to install anythi... | First, see if the C/C++ perspective is available. Go to Window > Open Perspective > Other... and you should see a C/C++ option. If so, select it. This will change the layout of the File > New menu by putting the C/C++ project options at the top level.
One other thing that has tripped me up before is the JRE that Ecl... |
3,977,817 | 3,977,960 | How can I "override" [] to accept two arguments in C++? | I am trying to create a bit-vector class in C++ to model some hardware. In most HDLs (hardware description langauges) that I know, specific bits are referenced like this:
my_vector[bit_position]
and sub-vectors are referenced like this:
my_vector[msb:lsb]
or
my_vector[msb,lsb]
I want to be able to do something simi... | The issue:
Apart from operator() all operators have a fixed arity, which effectively precludes any kind of change
You then have several solutions:
overload operator() instead: vector(msb, lsb)
use two successive invocations: vector[msb][lsb]
overload the comma operator: vector[msb,lsb]
The last solution matches the... |
3,977,893 | 3,977,914 | Copy constructor not being called | I have a class which allocates memory on the heap and then the destructor frees it. My copy constructor is never being called for some reason and I do not understand why. Here is my implementation:
AguiBitmap::AguiBitmap( const AguiBitmap &bmp )
{
this->nativeBitmapPtr = al_clone_bitmap(bmp.nativeBitmapPt... | That bit of code wont invoke the copy constructor - it invokes the assignment operator (or the copy-assignment operator):
// a helper `swap` function
void AguiBitmap::swap(AguiBitmap& a, AguiBitmap& b)
{
using std::swap; // enable the following calls to come from `std::swap`
// if there's no ... |
3,978,275 | 3,978,526 | Guidelines for writing a test suite | What are the best practices/guidelines for writing test suite for C++ projects?
| This is a very broad question. For unit testing and Test Driven Development (TDD), there is some useful (if somewhat platidinous in parts) guidance on this from Microsoft - you can overlook the Visual Studio-specific advice, if it does not apply.
If you are looking for guidance on system or performance testing, I woul... |
3,978,351 | 3,985,120 | How to avoid backslash escape when writing regular expression in C/C++ | For regular expression \w+\d, in many script language such as perl/python it can be written literally. But in C/C++, I must write it as:
const char *re_str = "\\w+\\d";
which is ugly to eye.
Is there any method to avoid it? MACRO are also acceptable.
| When I reading [C: A reference manual] Chapter 3: Prepressors. An idea emerges:
#define STR(a) #a
#define R(var, re) static char var##_[] = STR(re);\
const char * var = ( var##_[ sizeof(var##_) - 2] = '\0', (var##_ + 1) );
R(re, "\w\d");
printf("Hello, world[%s]\n", re);
It's portable in both C and C++, only ... |
3,978,889 | 3,987,355 | Why is QHBoxLayout causing widgets to overlap? | I need to place several instances of a custom QPushButton subclass adjacent to one another. For some reason, the buttons overlap one another when painted. A simplified example of the problem is below.
Here is the (incorrect) output:
Here is the code:
#include <QtGui>
class MyButton : public QPushButton {
public:
ex... | The solution is to add the following to the subclass:
setAttribute(Qt::WA_LayoutUsesWidgetRect);
Apparently it is only necessary on the Mac platform; Windows and Linux display the layout as expected.
|
3,978,898 | 3,979,117 | How to compile and run C++ with MinGW using Eclipse and CDT? | I would like to do some C++ development on Windows using Eclipse and the CDT plugin. I use Eclipse Helios SR1 and have installed the CDT plugin. I have also installed MinGW and now I wrote a simple "Hello World" in Eclipse.
hello.cpp
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World" << end... | Does Setting up Eclipse CDT on Windows, Linux/Unix, Mac OS X work for you?
|
3,978,900 | 3,979,023 | mutually referential classes yield "incomplete type" error | I have a situation in which A has a reference to a class C defined inside B, and C has an instance of class B.
When I try to compile the code below, I get "field a has incomplete type". I assume this is because the compiler does not know how much memory it should allocate for an instance of A.
class A;
class B {
publi... | As an absolute guess, I notice there's one permutation you haven't tried:
class B {
public:
class C; // Forward declaration
};
class A {
A(const B::C& _c)
: c(_c)
{}
const B::C& c;
};
class B::C {
A a;
C() : a(*this) {} // Thanks Nim for pointing this out!
};
This is quite possibly illegal, but w... |
3,978,952 | 3,979,606 | Looking for a simplest (and fastest) example of TCP socket programming for windows, c or c++ | I'm looking for a simplest (and fastest) example of TCP socket programming for windows, c or c++, whichever can get it accomplished faster, sending trival data, for example 1 byte, or several bytes, but in one packet. It's for research purposes. I googled and found several examples, however every single of out them loo... | Before writing the third comment, I collect them in an answer
There's RUDP which is reliable and fast since it omits the connection setup: en.wikipedia.org/wiki/Reliable_User_Datagram_Protocol ; see also What do you use when you need reliable UDP?
Out of Steven's UNIX Network Programming I, p. 369 I suggest T/TCP whic... |
3,979,129 | 3,979,612 | Measuring total CPU time of a program that uses precompiled libraries (C++, Linux) | I am currently stumbled into this problem and I'd love to hear some suggestions from you.
I have a C++ program that uses a precompiled library to make some queries to PostgreSQL database. Now the problem is I want to find out the total (combined) cpu time it takes to do all routines described in the source code of the ... | Of course you'll get the wall-clock time anyway, but presumably you're trying to get the CPU time.
This is nontrivial when you have subprocesses (or unrelated processes) involved. However, you may want to try to have a more holistic approach to benchmarking.
Measuring the latency of an application is easy enough (just ... |
3,979,207 | 3,979,334 | MurmurHash - how does it loop through the key? | I am looking at MurmurHash (sites.google.com/site/murmurhash/)
I'm using it in a black box kind of a way and not trying to understand the maths at this stage.
However, I did have a little look at the code and got worried about how it seems to work...
Here's the code:
uint64_t MurmurHash64A ( const void * key, int len, ... | The algorithm processes the data passed 8 bytes at a time (uint64_t is 8 bytes).
The first loop will combine all set of 8 bytes to make a single key of 8 bytes.
Then the switch will use the remaining bytes (all 3 bytes in your example passing "ABC") and processes it to take them into account in the final result.
|
3,979,700 | 3,979,819 | How can I prefetch a memory region most easily? | Background: I've implemented a stochastic algorithm that requires random ordering for best convergence. Doing so obviously destroys memory locality, however. I've found that by prefetching the next iteration's data, the performance drop is minimized.
I can prefetch n cache lines using _mm_prefetch in a simple, mostly... | There's a question asking just about the same thing here. You can read it from the CPUID if you feel like delving into some assembly. You'll have to write platform specific code for this of course.
You're probably already familiar with Agner Fog's manuals for optimization which gives the cache information for many po... |
3,979,766 | 3,981,001 | How do traits classes work and what do they do? | I'm reading Scott Meyers' Effective C++. He is talking about traits classes, I understood that I need them to determine the type of the object during compilation time, but I can't understand his explanation about what these classes actually do? (from technical point of view)
| Perhaps you’re expecting some kind of magic that makes type traits work. In that case, be disappointed – there is no magic. Type traits are manually defined for each type. For example, consider iterator_traits, which provides typedefs (e.g. value_type) for iterators.
Using them, you can write
iterator_traits<vector<int... |
3,979,942 | 3,980,528 | What is the complexity / real cost of exp in cmath compared to a FLOP? | [I globally edited the question to be more "useful" and clear]
I was wondering about the complexity of the implementation of the function exp in cmath.
By complexity, I mean algorithmic complexity if possible. Otherwise cost compared to a floating point operation (addition for example)
The following lines :
double x = ... | It seems that the complexity is actually constant since MSVC9 compiler does some bit-magic involving specific tables, bitmasks and biases. As there are few branches after all instruction pipeline should help a lot. Below is what it does actually.
unpcklpd xmm0,xmm0
movapd xmm1,xmmword ptr [cv]
movapd xmm... |
3,979,956 | 3,980,264 | Class wrapper design question | I want to wrap part of the TinyXML library in some custom classes in my project because I only need some of its functionality and I do not wish to expose everything.
I have a problem where my XMLDocument::AddNode(...) function is basically doing the same thing that my XMLNode class is meant for. I wondered if anyone... | You already encapsulate the TinyXml document - now you just need to delegate to it where you want, to expose only a subset of the function it provides.
Replace this
void XMLDocument::AddNode(XMLNode& node) // This function does over what XMLNode class is actually for... I just want to add the node to the XMLDocument
... |
3,980,011 | 3,980,033 | Calling base method from derived class | I have, for example, such class:
class Base
{
public: void SomeFunc() { std::cout << "la-la-la\n"; }
};
I derive new one from it:
class Child : public Base
{
void SomeFunc()
{
// Call somehow code from base class
std::cout << "Hello from child\n";
}
};
And I want to see:
la-la-la
Hello from ch... | Sure:
void SomeFunc()
{
Base::SomeFunc();
std::cout << "Hello from child\n";
}
Btw since Base::SomeFunc() is not declared virtual, Derived::SomeFunc() hides it in the base class instead of overriding it, which is surely going to cause some nasty surprises in the long run. So you may want to change your declaration... |
3,980,035 | 3,980,113 | Performance of Win32 memory mapped files vs. CRT fopen/fread | I need to read (scan) a file sequentially and process its content.
File size can be anything from very small (some KB) to very large (some GB).
I tried two techniques using VC10/VS2010 on Windows 7 64-bit:
Win32 memory mapped files (i.e. CreateFile, CreateFileMapping, MapViewOfFile, etc.)
fopen and fread from CRT.
I ... | I believe you'll not see much difference if you access the file sequentially. Because file I/O is very heavily cached, + read-ahead is probably also used.
The thing would be different if you had many "jumps" during the file data processing. Then, each time setting a new file pointer and reading a new file portion will ... |
3,980,076 | 3,980,125 | A std::map like container that maps types to values | I'm looking for a hybrid meta-container/container class. I want a class that maps a compile-time type to a runtime value. A code snippit is worth 1024 words so:
struct Foo { /* ... */ };
struct Bar { /* ... */ };
int main()
{
meta_container<Foo,float,int> mc;
mc.get<float>() = 1.0f;
mc.get<Foo>().method(bla... | boost::fusion : http://www.boost.org/doc/libs/1_44_0/libs/fusion/doc/html/index.html
|
3,980,303 | 3,980,515 | Command line switches out of order | I'm working on a C++ program that accepts a filename as a command line input, reads a bunch of data from that file, computes two things about the data, then exits. One of those computations must be done, but the other is much more optional, so I thought it would be neat to add a -c flag to turn it off. Naively, I would... | Use boost program options . Example:
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("compression", po::value<int>(), "set compression level")
;
po::variables_map vm;
po::store(po::parse_command_line(ac, av, desc), vm);
po::notify(vm);
if (vm.count("he... |
3,980,552 | 3,980,585 | Expanding a dynamically allocated array | I have allocated an array as follows.
#include <iostream>
int main() {
const int first_dim = 3;
const int second_dim = 2;
// Allocate array and populate with dummy data
int** myArray = new int*[first_dim];
for (int i = 0; i < first_dim; i++) {
myArray[i] = new int[second_dim];
for ... | Yes, but in a very painful way. What you have to do is allocate new memory which now has your new desired dimensions, in this case 4 and 2, then copy all the contents of your matrix to your new matrix, and then free the memory of the previous matrix... that's painful. Now let's see how the same is done with vectors:
#i... |
3,980,599 | 3,980,706 | Block attatchment in 3D grid | I'm doing ray picking to find the scene node that my cursor points at. All of those scene nodes are equally sized cubes. I have the hit scenenode's position, the position of the ray intersection and the triangle that the node/mesh that were hit. What i want to do is to attatch a new block to the face of the collided sc... | If you know the triangle that your ray intersects you can calculate the normal vector for that triangle and place a new block at positionOfHitBlock + normal. For example the triangles forming the left face of a block will have a normal of (-1.0,0.0,0.0), so you will want to place a block one farther over to the left.
|
3,980,627 | 3,980,644 | Is a friend function defined in-class automatically inline? | If a member function is defined inside the class, it is an inline function. E.g.
struct X
{
void mem_f() {} //mem_f is inline
};
My question is whether a nonmember friend function defined inside the class is also automatically inline.
E.g.
struct Y
{
friend void friend_f() {} //is friend_f inline?
};
A relev... | Yes, it is. §11.4/5:
A function can be defined in a friend
declaration of a class if and only if
the class is a non-local class (9.8),
the function name is unqualified, and
the function has namespace scope.
Such a function is implicitly inline. A friend function defined in
a class is in the (lexical) scope... |
3,980,684 | 3,980,805 | Cyclic and acyclic data structures | What is the difference, can you give me examples?
| If you can start at node X, navigate through the structure without visiting the same node twice, and arrive back at X, then the structure is cyclic. The cycle is the series of nodes visited along such a path.
We usually make an exception for cycles of size 2 (i.e., visit a neighbor and come right back) in undirected st... |
3,980,815 | 3,980,869 | Derived class function | class Base
{
protected:
int data;
public:
virtual int getData() { return data; }
virtual void setData(int value) { data = value; }
};
class Child : protected Base
{
public:
void setData(int value)
{
Base::setData(value);
cout << "Data is set.\n";
}
};
class Worker
{
... | Did you actually make it a public base class?
// vvvvvv important
class Child : public Base
Otherwise it's private, and you get errors similar to what you have, namely:
‘Base’ is not an accessible base of ‘Child’
|
3,980,835 | 3,980,853 | Why is my MD5 value printing with extra "f" characters? | I have strange problem when using at() method of std::string. I'd like to calculate md5 hash for given string using this library: http://sourceforge.net/projects/libmd5-rfc/files/
Hash is calculated correctly, but there is a problem with printing it human way. The output is:
af04084897ebbf299b04082d105ab724
ffffffaf040... | Your byte values are being sign-extended.
That happens when you promote the (signed) char to a wider type and the top bit is set, because it tries to preserve the sign (which is why you're seeing the extra f characters only for values greater than 0x7f). Using an unsigned char should fix the problem:
const unsigned cha... |
3,980,879 | 3,980,926 | Type decision based on existence of nested typedef | I need to define a template struct such that:
element<T>::type
is of type:
T::element_type
if T contains a (public) typedef named element_type, otherwise (if it does not contain such typedef)
element<T>::type
is of type
T::value_type
if T is mutable and of type
const T::value_type
if T is constant.
I am really s... | Maybe something like:
template <typename T>
struct has_element_type
{
typedef char yes[1];
typedef char no[2];
template <typename C>
static yes& test(typename C::element_type*);
template <typename>
static no& test(...);
static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};
temp... |
3,980,945 | 3,981,033 | OpenGL: Triangles with points at infinity | I am trying to render a two-dimensional half-plane in OpenGL with the following code:
void renderHalfplane(double *x, double *n)
{
glPushMatrix();
double theta = -360.0 * atan2(n[0], n[1])/(2.0*PI);
glTranslated(x[0], x[1], 0);
glRotated(theta, 0, 0, 1.0);
glBegin(GL_TRIANGLES);
glVertex4d(0.0, 0.0, 0.0, ... | I tested this on my machine(nVidia Quadro) and it renders correctly. I've found code samples (for shadow volumes) that scales the W coordinate to infinity that work fine also.
I'm going to guess it's a driver issue or something external to this code?
|
3,981,480 | 3,981,863 | ifstream fails to open in recursive calls | we are running into an odd issue when trying to parse an input file. the idea is that this file can include other files, which must be parsed as well. We are doing this recursively in a function defined as
int parse_inp(const char* filename)
The main file parses no problem, but recursive calls cannot open their file s... | Are you sure the filename does not contain any garbage or bad character that would lead to this issue?
If the error is file not found, that means the filename is wrong in some way.
Could it come from a bad declaration of buffer? We don't see it in your code.
Another possibility is that you use strtok again in your init... |
3,981,624 | 3,981,660 | Code requires too much memory | I'm porting some code to another structure:
class EnvironObject
{
protected:
vector<float> mX, mY, mXSpeed, mYSpeed;
int mMaxObjects;
public:
virtual void init(int maxObjects);
virtual void setLimit(int limit);
virtual int getLimit();
virtual void update(float arg) = 0;
};
vo... | Look again at that function of yours:
void EnvironObject::init(int maxObjects)
{
mX = mY = mXSpeed = mYSpeed = std::vector<float>(mMaxObjects);
// ^
// ...
mMaxObjects = maxObjects;
}
You're using a not yet initialized variable.
A big problem with your c... |
3,981,724 | 3,981,816 | Call virtual method immediately after construction | I need to call a virtual method for all classes derived from a given base base class right after the construction of the derived object. But doing so in the base class constructor will result in a pure virtual method call
Here is a simplified example:
struct Loader {
int get(int index) { return 0; }
};
struct Base... | Use the PIMPL pattern:
template<typename T>
class Pimpl
{
public:
Pimpl()
{
// At this point the object you have created is fully constructed.
// So now you can call the virtual method on it.
object.load();
}
T* operator->()
{
/... |
3,981,766 | 3,981,793 | C++ Outputting to .CSV Files | So basically i've never worked with CSV files before, but im making a program thats going to be calculating and outputting ALOT of data to files (8 separate files)
Basically it's going to do a formula. then output it as something like: (| means seperate column)
int | int | int | float | string | int | int | int | float... | Although there can be some slight technicalities, in most cases indeed that is all there is to it.
|
3,982,470 | 3,982,490 | What does "typedef void (*Something)()" mean | I am trying to understand what this means, the code I am looking at has
in .h
typedef void (*MCB)();
static MCB m_process;
in .C
MCB Modes::m_process = NULL;
And sometimes when I do
m_process();
I get segmentations fault, it's probably because the memory was freed, how can I debug when it gets freed?
| It defines a pointer-to-function type. The functions return void, and the argument list is unspecified because the question is (currently, but possibly erroneously) tagged C; if it were tagged C++, then the function would take no arguments at all. To make it a function that takes no arguments (in C), you'd use:
typed... |
3,982,496 | 3,982,514 | Const keyword appended to the end of a function definition... what does it do? | Suppose I define a function in C++ as follows:
void foo(int &x) const {
x = x+10;
}
And suppose I call it as follows:
int x = 5;
foo(x);
Now typically (without the const keyword), this would successfully change the value of x from the caller's perspective since the variable is passed by reference. Does the const ke... | This won't work. You can only const-qualify a member function, not an ordinary nonmember function.
For a member function, it means that the implicit this parameter is const-qualified, so you can't call any non-const-qualified member functions or modify any non-mutable data members of the class instance on which the me... |
3,982,633 | 3,982,651 | C++ - dynamically use either reference or local variable | I would like to do something like this (I'm aware that this won't compile):
struct Container{
vector<int> storage;
};
float foo(Container* aContainer){
if(aContainer!=NULL)
vector<int>& workingStorage=aContainer->storage;
else
vector<int> workingStorage;
workingStorage.reserve(100000... | Create a local std::vector<int> named local_storage for the case where a container is not provided by the caller, then create a reference to whatever container you are actually going to use.
std::vector<int> local_storage;
std::vector<int>& working_storage = aContainer
? aConta... |
3,982,717 | 3,984,591 | C# bindings for MEEP (Photonic Simulation Package) | Does anyone know of a way to call MIT's Meep simulation package from C# (probably Mono, god help me).
We're stuck with the #$@%#$^ CTL front-end, which is a productivity killer. Some other apps that we're integrating into our sim pipeline are in C# (.NET). I've seen a Python interface to Meep (light years ahead of CTL... | The straightforward and portable solution is to write a C++ wrapper for libmeep that exposes a C ABI (via extern "C" { ... }), then write a C# wrapper around this API using P/Invoke. This would be roughly equivalent to the Python Meep wrapper, AFAICT.
Of course, mapping C++ classes to C# classes via a flat C API is non... |
3,982,787 | 3,982,826 | Kinds of integer overflow on subtraction | I'm making an attempt to learn C++ over again, using Sams Teach Yourself C++ in 21 Days (6th ed.). I'm trying to work through it very thoroughly, making sure I understand each chapter (although I'm acquainted with C-syntax languages already).
Near the start of chapter 5 (Listing 5.2), a point is made about unsigned int... | 2^32 - 3000000000 = 1294967296 (!)
|
3,982,812 | 3,982,832 | C++ SQL Queries/SQL Wrapped for C++? | Just more a general question I can't seem to find a definite answer on.
But what is a good SQL wrapper for C++ that allows me to call queries?
I'm used to Oracle, but i've used MYSQL before aswell.
And how would you call something such as an insert statement (for example) in one?
| Personally I love SOCI, simple and easy to use, just follow the link for easy example code and a much better explanation of what SOCI is all about then I could put in this answer. I use this for all of my C++ SQL development work.
|
3,983,153 | 3,983,182 | C++ remove node binary search tree | I am trying to figure out how to remove a node from a binary search tree, I understand that it is different for each node whether it is a leaf, has one child or two children. So as of now my function is nothing more than:
bool BinSTree::remove_root(treeNode*& node) {
if(node -> left == NULL && node -> right == NULL... | This sounds like homework. You might find this article on binary tree rotation to be helpful. In addition to give you some hints on how to handle some interesting cases, that article will also show you how you might diagram the problem out for yourself.
Deleting from a tree is an interesting case, and I remember puzz... |
3,983,256 | 3,983,361 | Updating global variables from a single worker thread: Do I need mutexes? | It seems that this question gets asked frequently, but I am not coming to any definitive conclusion. I need a little help on determining whether or not I should (or must!) implement locking code when accessing/modifying global variables when I have:
global variables defined at file scope
a single "worker" thread readi... | I suppose it depends on what you are doing in your DoWork() function. Let's assume it writes a point value to p1. At the very least you have the following possibility of a race condition that will return invalid results to the main thread:
Suppose the worker thread wants to update the value of p1. For example, lets c... |
3,983,295 | 3,983,306 | templated class with templated constructor (of other type) | Is it possible to have a templated class and also templating the constructor with some other type?
something like this:
template<typename T1>
class Foo{
template<typename T2>
Foo(T1 aBar, T2 dummyArgument){
bar = aBar;
bytesOfT2 = sizeof(T2);
};
int bytesOfT2;
T1 bar;
};
is this po... | Yes, a class template can have a constructor template. You call it as you would call any other constructor:
Foo<int> my_foo(42, 0.0);
This invokes the constructor template with T1 = int (because T1 is a class template parameter and the class template argument is int) and T2 = double (because T2 is a function template... |
3,983,541 | 3,983,578 | Trying to sort an array | I'm trying to sort an array least to greatest and i am really lost....
Here is what i have so far:
int temp, temp2;
for (int x = 0; x < array_size; x++)
{
temp=a[x];
for (int i = 0; i < array_size; i++)
{
if (a[i] < temp)
{
... | You can use the STL sort algorithm.
In case you really want to hand code it, you may want to make some changes:
In the inner for loop, change
int i = 0
to
int i = x + 1
Also, reassign temp to a[i] inside the if.
Full code below:
// Arun Saha, 2010-Oct-20
// http://stackoverflow.com/questions/3983541/trying-to-sort-a... |
3,983,564 | 3,983,645 | Stopping or Blocking Inheritance in C++ | I would to block child classes from overriding a base method and have the child classes override a new method in a parental class. In other words, a child class of the base class blocks the base class methods and delegates to a new method that further child classes must override. I still want the base class method to... | For your immediate problem, you can rename your class_name() functions to class_name_impl() or similar, then in the base class have a class_name() function that calls the implementation one. That way, only the base class version will match when calling class_name() on a derived object.
More generally, you can frustrat... |
3,983,588 | 3,983,722 | Boost 1.44.0 + VS2010 Private member error | I have a class declaration in Utils.h:
class Utils {
private:
static boost::mutex outputMutex;
};
In the cpp file:
boost::mutex Utils::outputMutex = boost::mutex();
I get:
Error 1 error C2248: 'boost::mutex::mutex' : cannot access private member declared in class 'boost::mutex'
If we look inside boost/... | The .cpp file should be:
boost::mutex Utils::outputMutex;
There's no need for an assignment. It will be constructed appropriately.
|
3,983,800 | 3,983,820 | something like a using declaration for enums? | Basically this is what I'd like to do:
struct A {
enum E {
X, Y, Z
};
};
template <class T>
struct B {
using T::E;
};
// basically "import" the A::E enum into B.
std::cout << B<A>::X << std::endl;
The reason why is that I want to basically inject the implementation details into my template class.... | This works for me:
struct A {
enum E {
X, Y, Z
};
};
template <class T>
struct B {
typedef typename T::E E;
};
// basically "import" the A::E enum into B.
int main(void)
{
std::cout << B<A>::E::X << std::endl;
return 0;
}
Output is
0
I do get a warning about non-standard extension in th... |
3,983,814 | 3,983,876 | pointer to std::vector of arbitrary type (or any other templated class) | let's say i want to have a member variable for a pointer to std::vector but i do not want to specify what type of variable it stores. I want to access only those functions that are independant of it's actual generic type. is this possible with c++? something like this:
class Foo{
public:
void setVec(std::vector* so... | You are almost at the answer. Instead of making std::vector inherit from Ivector, create a new class:
template <typename T>
class IVectorImpl : public Ivector
{
public:
explicit IVectorImpl(std::vector<T> * Data) : m_Data(Data){}
std::vector<T> * m_Data;
...
virtual int size() const {return m_Data->size()... |
3,984,009 | 3,984,015 | Problems with binary search function | Having trouble with the binary_search function listed at the top. not sure where to go with it. I'm not very familiar with binary searching.
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
void get_input(ifstream& fin, int a[], int size, int & array_size);
void binary_search (int a[], ... | Try changing
startindex=midindex;
to:
startindex=midindex + 1;
and
int midindex=(array_size/2);
to
int midindex= startindex + (lastindex - startindex) / 2
and most importantly you are doing nothing when you find the element !!
if(element == a[midindex]) {
cout<<"Element "<<element<<" found at index "<<midindex<<e... |
3,984,215 | 3,984,226 | C++: Initialization of inherited field | I've a question about initialization of inherited members in constructor of derived class. Example code:
class A
{
public:
int m_int;
};
class B: public A
{
public:
B():m_int(0){}
};
This code gives me the following output:
In constructor 'B::B()':
Line 10: error: class 'B' does not have any ... | You need to make a constructor for A (it can be protected so only B can call it) which initializes m_int just as you have, then you invoke :A(0) where you have :m_int(0)
You could also just set m_int = 0 in the body of B's constructor. It is accessible (as you describe) it's just not available in the special construct... |
3,984,296 | 3,989,453 | Model View Controller Design pattern Code Example | I was studying the Model-View-Controller design pattern and i understand the concept behind the pattern theorotically, but I wanted to get a peek at how one would actually put it to practice.
Wikipedia mentions Wt - Web toolkit, CppCMS and some other standard implementations which use the pattern however I have not bee... | Here's a quick example I made (didn't try compiling it, let me know if there's errors):
class Button; // Prewritten GUI element
class GraphGUI {
public:
GraphGUI() {
_button = new Button("Click Me");
_model = new GraphData();
_controller = new GraphController(_model, _button);
}
~Gr... |
3,984,361 | 3,984,372 | got "cannot appear in a constant-expression" when using template | template < int >
class CAT
{};
int main()
{
int i=10;
CAT<(const int)i> cat;
return 0; //here I got error: ‘i’ cannot appear in a constant-expression
}
even
int i=10;
const int j=i;
CAT<j> cat; //this still can not work
but I have convert i to const int ,wh... | A non-type template argument needs to be a compile-time constant. Casting an int to a const int does not make it a compile-time constant. You either need to use 10 directly:
CAT<10> cat;
or make i a const int:
const int i = 10;
CAT<i> cat;
|
3,984,588 | 3,984,720 | C++ STL vector reserve | I have tested on stl vector with code below:
struct structA{
char charArray[256];
}
structA a;
..assign 256 characters to a.charArray
vector<structA> v1;
v1.reserve(1000);
for(int i=0; i<1000; i++){
v1.push_back(a);
}
I realized that for every 16 push_back, there is a spike in the v1.push_back. I suspect that... | Run this simple test and see if there are any allocations or deallocations you don't want or don't expect.
#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include <algorithm>
template <class T> class my_allocator;
// specialize for void:
template <> class my_allocator<void> {
public:
... |
3,984,915 | 3,984,938 | Most Common Mistake done/seen in C++ |
Possible Duplicate:
What C++ pitfalls should I avoid ?
What is the most common mistake in C/C++programming that you keep committing or see most of the people do? Being aware of it atleast subconsciously will increase my or anyone's chances of committing it.
| Wrong memory management in all kinds of ways - new without delete, delete on the wrong pointer, unclear ownership of a pointer with resulting memory allocation / deallocation problems etc.
|
3,984,957 | 3,985,293 | GlutSolidSphere not solid | Hi my program is supposed to display a solid red colored sphere in the center of the screen, all i am getting is the boundary of the sphere :
int main(int argc, char **argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA);
glutInitWindowSize(800,600);
glutInitWindowPosition(0,0);
glutCrea... | Try adding glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); before your glutSolidSphere(2.5, 50, 40);
|
3,984,989 | 3,984,993 | What is the differnce between "const X a" and "X const a" if X is the class | i have a class name X, what is the difference between "const X a" and "X const a"
| Nothing.
A const qualifier applies to whatever is immediately to its left. If there is nothing to its left then it applies to whatever is immediately to its right.
|
3,985,069 | 3,985,102 | C++ database communication library | I'm looking for a well designed, efficient and robust C++ cross-database and cross-platform database communication library.
I need support for
Oracle
MySQL
PostgreSQL
Firebird (optional)
MSSQL (optional)
When I say cross-platform I really mean cross-platform, I need something similar to boost.
Currently I'm researchi... | Using: Progress DataDirect Connect® and Connect XE
Intresting options:
http://www.sqlapi.com/
http://www.thefreecountry.com/sourcecode/database.shtml
http://www.trumphurst.com/cpplibs/cpplibs.php
|
3,985,121 | 3,985,165 | How Utility functions can be shared across various classes? | I had a class Display with 2 utility functions getDate and getTime like below.
class Display
{
public:
void getDate(char *pDate); //Utility functions for converting to custom format
void getTime(char *pTime);
};
Later, In other class called Retriever also, i needed the same Utility functions getDate and getTime. I... | I think that using namespace will be most appropriate. You can choose name for that namespace so that everyone be aware of it purpose:
namespace DisplayRetrieverImplementation {
void getDate(char *pDate); //Utility functions for converting to custom format
void getTime(char *pTime);
}
|
3,985,176 | 3,985,262 | Qt QComboBox with different background color for each item? | Is there a way to set a different background color for each item in a QComboBox ?
| I guess the only way to do it would be to write your own model, inheriting QAbstractListModel, reimplementing rowCount()and data() where you can set the background color for each item (using the BackgroundRole role).
Then, use QComboBox::setModel() to make the QComboBox display it.
Here is a simple example, where I cre... |
3,985,623 | 4,467,704 | Outlining in VS2008, C++, not working | I'm using VS2008 (version 9.0.30729.1 SP) and have found that outlining regularly stops working. I get outlining options for the start and end of functions, and for comment blocks, but not for other code blocks, such as ifs, while loops, for loops, etc... Using Reset all settings, as recommended in a similar previous... | My suggestion would be to write a script which every couple of hours adds a randomized post to the VS2008 support forums, requesting that this feature be made more robust, until someone at MS promises to improve it. ;-)
More seriously, you might make a copy of the VS configuration settings files, work until the bug reo... |
3,985,720 | 4,053,778 | Recursive read of TCollection | I'm very bad with recursion, never used it before. I know the theory of it .. not that that helps :)) For my problem i have a structure of TCollection that contains TCollection and TCollectionItem etc .. I have to write a recursion function that will read all my TCollectionItems.
Here is graphical view:
TCollection->TC... | You haven't indicated the prototypes of the TCollection methods so as to enumerate and to read your TCollectionItems, and other needed details.
However, this is definitely solved by: The Composite Design Pattern.
The aim of this pattern is to traverse a recursive form, and to forward a call on a composite onto its comp... |
3,985,836 | 3,986,910 | how to use boost::unordered_map | for my application, i need to use a hash map, so i have written a test program in which i store some instances of a baseclass in a boost::unordered_map. but i want to reach the instances by calling special functions which return a derived class of the base and i use those functions' parameters for hash key of unordered... | Here are a couple of design problems:
struct HashKey
{
ULL * hasharray;
...
Your key type stores a pointer to some array. But this pointer is initialized with the address of a local object:
BaseClass * & FindClass(ULL* byt, int Num, size_t & HCode)
{
HashKey hk(byt,Num); // <-- !!!
HashPair hp(hk,0);
... |
3,985,873 | 3,985,924 | How a main function is being called in a c/cpp project | Good day good-looking computer people,
I might be asking a bit too much, but here it goes.
I'm trying to do a bit of reserve engineering on this sound library. Looking at the main.cpp file (which I have posted below) it has two methods, setup and play. I'm a bit confused as to how this is working:
When you run the Xco... |
If the program isn't starting from a
main method in the main.cpp file,
where else could it be starting from ?
From a main method in a different source file or pre-compiled library, probably, or definitely.
|
3,986,006 | 3,986,068 | 32 Bit Com Server on 64 Bit System | i developed a Com Server and on windows XP 32 bit. To Test the Com Server i created a Client with C# to call the Functions via Interop.
Everything works fine, but now i need to get the ComServer run on a Windows 7 64 bit System.
I took the ComServer DLL and the C# EXE to the 64 bit Computer, registered the ComServer DL... | You can't load a 32-bit library into a 64-bit process and vice versa - the library and the process must be of same bitness.
The best solution is to get a 64-bit version of the COM server library. If that is not possible (which is quite usual) you have two options:
make the consuming program 32 bit (likely you have to ... |
3,986,056 | 3,990,170 | Get the path "difference" between two directories | The situation:
I got one or more absolute paths, e.g.:
/home/benjamin/test/
/home/benjamin/test/a/1
/home/benjamin/test/b/1
How can I get the difference between two paths? Let's say I want to know how I can get from path 1 to path 2. Expected result would be
/home/benjamin/test/a/1 - /home/benjamin/test/ = /a/1
Is th... | I would try to use std::mismatch (documentation)
template <class InputIterator1, class InputIterator2>
pair<InputIterator1, InputIterator2>
mismatch (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2 );
Return first position where two ranges differ
Compares the elements in the ran... |
3,986,192 | 3,988,347 | MFC Treeview : How to check if Treeview already contain particular child node? | In MFC Treeview control, how i can check condition if particular child node is already present in treeview?
My requirement is like if particular child node is present in treeview dont add it again in that treeview...
Any code snippet is welcome ........
Thanks.
| You'll want to call the methods ItemHasChildren/GetChildItem and GetNextSiblingItem.
There is a code example for the GetNextSiblingItem help on MSDN.
|
3,986,249 | 3,986,420 | slot machine payout calculation | I want to create a 5 reels slot machine calculation system and I'm not sure what approach to take.
I understand that there is a lot of math within it, especially if I want the machine to be enjoyable to a player.
Are there any tips/links for that? Was looking for info at the web but they discuss on it from the player's... | As Phong noted, you need to first determine what the overall, long-term payout of the machine should be. e.g. $0.95 for every $1.
You then look at all your winning combinations, the odds of that combination occurring, and the payout of that combination. Add them all together and it should be equal to your desired long ... |
3,986,289 | 3,986,425 | Sending C strings and vectors to MurmurHash gives inconsistent results | I'm trying to use MurmurHash (returning 64 bit hashes on a 64bit comoputer) and have sent it the simple 3 letter string 'yes' as follows
char* charptr = "yes";
cout << MurmurHash64A(charptr, 3, 10);
(where 3 is the length and 10 is the seed)
This gives a 64bit hashed response as expected, I can set up more pointers to... | &mystring points at the string object. You want to use mystring.c_str() to get a pointer to a raw character array.
For the vector, you want &(*charvec)[0]. But you probably don't want to use new; you could just do vector<char> charvec; void *myvecptr3 = &charvec[0];.
|
3,986,446 | 3,987,144 | QT: Pause function flow till QWebView SIGNAL is completed | I'm a mostly webdeveloper, so my question can be somekind of a beginners.
I'm writing a function which works with QWebView content, some kind of a macro script which makes action on loaded web page.
code is something like that:
somefunction() {
QWebView *webView;
webView->load(QUrl("http://www.google.com"));
<...> her... | You can use a nested QEventLoop to synchronize asynchronous processing like page loading. When loadFinished is emitted, just exit() the loop to resume execution from where you entered the loop.
On the other hand, splitting processing to multiple functions (slots) isn't that bad either. The code and logic is still in th... |
3,986,536 | 4,686,602 | automatically compare two series -Dissimilarity test | I have two series, series1 and series2. My aim is to find how much Series2 is different from Series1,on a bin to bin basis, (each bin represents a particular feature,) automatically/quantitatively.
This image can be seen in its original size by clicking here.
Series1 is the expected result.
Series2 is the test/incomin... | Here is a C implementation of an algorithm to compute the divergence of actual data from predicted data. The algorithm comes from a book entitled Practical BASIC Programs from Osborne/McGraw-Hill copyright 1980.
Here is the .h file:
/*
* divergence.h
*
* Created on: Jan 13, 2011
* Author: Erik Oosterwal
*/
... |
3,986,721 | 3,986,733 | Sending a C++ struct over UDP in Java | I'm a C++ programmer and have a need to set up some UDP communications between a java android app and the C++ server running on a PC.
I have structure that I need to receive on the PC that consists of the following:
int
int
float
Unfortunately I'm totally at a loss as to how I can do this with Java.
I need to create a... | You can use Google protocol buffers as a language-independent way to serialize structures for transmission and receipt. Both Java and C++ are available out of the box, and Jon Skeet has written a production-ready C# implementation.
I see a couple of examples of Protobuf in use on Android, including this.
|
3,986,765 | 3,986,778 | How to define a nested member template outside a class template? | Consider the following class template:
template <class T>
class MyClass
{
void MyFunc();
};
template <class T>
void MyClass<T>::MyFunc()
{
//...implementation goes here
}
I need to add another function template MyFunc2 which accepts a template argument T2
i.e.,
template <class T>
class MyClass
{
void MyFunc()... | template <class T>
template <class T2>
void MyClass<T>::MyFunc2(T2* pData)
{
//...implementation goes here
}
$14.5.2/1 - "A template can be
declared within a class or class
template; such a template is called a
member template. A member template can
be defined within or outside its class
definition or class tem... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.