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,798,480 | 4,798,550 | Box2D collision detection failure | I have recently began using Box2D version 2.1 in combination with Allegro5. Currently, I built a test with a ground and 4 boxes. 3 boxes are stacked, and the other one smashes causing them to flip. During this demonstration, I noticed got two glitches.
One is that creating a box in Box2D "SetAsBox( width, height )", on... | It's actually SetAsBox(halfwidth, halfheight). I know it sounds weird but take a look inside SetAsBox. Passing in the parameters 15 and 15 will give a box with corners (-15,-15) and (15,15) i.e. a box of size 30x30.
I think it's intended as an optimisation, but it's a pretty silly one.
I don't know what's causing your ... |
4,798,578 | 4,798,617 | C++ templates problem: convert to null | I have a Stack container class and I want to create instances of various types of Stacks. so I do this:
template <typename T>
class MyStack
{
.
.
T Pop()
{
if(!IsEmpty())
{
return data[top--];
}
else
{
return NULL; // I got error here
}
.
.
}
When I try to ... | By returning a T by value, the contract of your function is that you will return a value. The two alternatives are to change the contract of your function (e.g. return a T* instead) or to fail to return by throwing an exception.
Personally, I think that it is acceptable and appropriate to throw an exception in this cas... |
4,798,777 | 4,798,816 | Is there a C++ equivalent to Java's BigDecimal? | I'm looking for a C++ class that can do decimal floating point arithmetic. Looking through http://speleotrove.com/decimal/ there are links to all sorts of classes that people have written and not maintained. Digging through the decNumber++ stuff led me to some emails showing that GCC will eventually support this functi... | There exists a huge library called GMP (GNU multiple precision library) which supports this and also has C++ bindings, though to be honest the C++ interface is a bit wonky and outdated.
An example from the documentation, the following creates a float called f with at least 500 bits of precision:
mpf_class f(1.5, 500);
... |
4,798,825 | 4,798,849 | Is there a similar way to read integer pairs from stdin to vector<pair<int,int> > in C++ | I am wondering if there is a way as slick as the following
copy(istream_iterator<int>(cin), istream_iterator<int>(),back_inserter(v));
to copy pairs of int into a vector<pair<int,int> > when the input is given in pairs in the order of their appearance?
Thanks.
| You can do this – but you need to write your own operator >> for the pair class first. This operator is the whole secret of the above call. Its actual implementation depends on the format of your int pairs.
|
4,798,921 | 4,798,955 | Does memory that is allocated in a function get freed when function returns? | I have a function that allocates memory using the new keyword.
That array gets returned from the function, but I need to somehow free it. Is it ever freed after the function returns, or is it up to the receiving code to free the array after it is done with it?
Should I just make this array a member variable, and free i... | It depends. You need to define who has got the ownership of such object.
You can allocate the array in your function, return it, and let the caller free it, or put a pointer to it in a class which will destroy the pointer in the destructor.
If the ownership for such object should be shared among many entities you shoul... |
4,798,936 | 4,798,972 | ‘numeric_limits’ was not declared in this scope, no matching function for call to ‘max()’ | I compiled this code at home on my mac w/ xcode and there was no provblem. I compile it at school with g++ on linux and I get these errors:
numeric_limits’ is not a member of std
expected primary-expression before ‘>’ token
no matching function for call to ‘max()’
#include <iostream>
#include <cstdlib>
using namespa... | You need to include the header file <limits>, which is where std::numeric_limits is defined. Your Mac compiler was helping you out by automatically including that header file; however, you should not rely on that behavior and explicitly include any header files you need.
|
4,799,058 | 4,799,290 | calling qsort with a pointer to a c++ function | I have found a book that states that if you want to use a function from the C standard library which takes a function pointer as an argument (for example qsort), the function of which you want to pass the function pointer needs to be a C function and therefore declared as extern "C".
e.g.
extern "C" {
int foo(void c... | A lot depends on whether you're interested in a practical answer for the compiler you're using right now, or whether you care about a theoretical answer that covers all possible conforming implementations of C++. In theory it's necessary. In reality, you can usually get by without it.
The real question is whether your... |
4,799,470 | 4,799,510 | New Operator With Vectors | These questions are relatively straight forward. When using vectors, should I use the new operator when pushing back a new element? And which release method should I call? Here's what I mean:
// Release method: 1.
void ReleaseMethodOne( vector< int * > &ThisVector )
{
// Clear out the vector.
ThisVector.clear( ... | STL containers store copies of the objects you give to them, pointers in your example. They never release any memory you explicitly allocated. You have to deallocate that memory yourself, so the second "release" method should be used.
Of course, you don't need to new every int. Just use vector<int> instead - you won't ... |
4,800,155 | 4,998,718 | Validating against multiple xml schemas with Xerces DOM parser | I was wondering if there was a way to validate against multiple xml schemes using Xerces DOM parser in c++?
Here is the use-case: I want to be able to parse multiple xml files against its corresponding xsd schema. However, when I initially look at each xml file, I do not know what file it is until I parse it, hence I c... | The code does not work if each xml is in the same namespace. Each xml file must be in a different namespace in order for the code above to work.
parser->setExternalSchemaLocation("http://www.somelocation schema.xsd http://www.somelocation1 schema1.xsd");
|
4,800,385 | 4,800,587 | Parse failure using Boost datetime library with time zone string | I'm trying to parse a date/time string in a custom format using Boost's date time library. The format I'm trying to use is rather unusual because it includes the Posix time zone description string. The docs for the library clearly state that there is a flag (%ZP) usable for both input and output that handles the Posi... | I think your format string should look like this: %Y-%m-%dT%H:%M:%s *;%ZP the %s * will match seconds and fractional seconds. With this change, the above code runs, bizarely though, the output I get is:
1989-Nov-09 15:30:42.005000 ST
Not sure why it says ST rather than PST, however the timezone information does get par... |
4,800,494 | 4,800,521 | How to have Java liked style static initialization in C++ | I was wondering, is it possible to have static initialization as Java style in C++? If not, what is the alternative way?
// .h
class A {
protected:
static CBitmap bitmap;
};
// .cpp
CBitmap A::bitmap;
// Error!
static {
global_initialization();
bitmap.LoadBitmap(IDB_BITMAP);
}
| You can't do this directly in C++ as you can in Java, but you can fake it in a few ways. One option would be to have a static bool class variable that's initially false. In the constructor, you can then do this:
MyClass::MyClass() {
if (!staticInitialized) {
/* ... */
staticInitialized = true;
... |
4,800,520 | 4,800,598 | How can I ensure proper speed of an animation in Qt using OpenGL? | I have 200 frames to be displayed per second. The frames are very very simple, black and white, just a couple of lines. A timer is driving the animation. The goal is to play back the frames at approx. 200 fps.
Under Linux I set the timer to 5 ms and I let it display every frame (that is 200fps). Works just fine but it ... | The short answer is, you can't (in general).
For best aesthetics, most windowing systems have "vsync" on by default, meaning that screen redraws happen at the refresh rate of the monitor. In the old CRT days, you might be able to get 75-90 Hz with a high-end monitor, but with today's LCDs you're likely stuck at 60 fps... |
4,800,605 | 4,800,757 | Iterating through objects in JsonCpp | I have a C++ application that uses jsoncpp to decode a JSON string. I have created the following function but it only shows me the top level objects...
How do I get it to dump the entire object list?
--Function--
SaveJSON( json_data );
bool CDriverConfigurator::PrintJSONTree( Json::Value & root, unsigned short depth ... | You have some errors related to seemingly not having a great handle on recursion or the key->value nature of JSON and how that relates to the library you're using. I haven't tested this code at all, but it should work better.
void CDriverConfigurator::PrintJSONValue( const Json::Value &val )
{
if( val.isString() )... |
4,800,667 | 4,800,774 | How to serialize a CString using boost | I'm trying to use boost::serialization to replace one part of an existing project that implements its own methods for serialization but are not that good.
However, I'm facing some problems because the application uses MFC. I tried to serialize the CString as follows
template<class Archive>
void save(Archive & ar, CStri... | You can only use save and load if you are working with a class you can add BOOST_SERIALIZATION_SPLIT_MEMBER() to the definition of. Since you can't do that for string, you need to implement Boost serialization in terms of a serialize method:
template<class Archive>
void serialize(Archive & ar, CString & s, const unsi... |
4,800,701 | 4,800,712 | Adding to middle of std::vector | Is there a way to add values to the middle of a vector in C++? Say I have:
vector <string> a;
// a gets filled up with "abcd", "wertyu", "dvcea", "eafdefef", "aeefr", etc
and I want to break up one of the strings and put all of the pieces back into the vector. How would I do that? the strings I break can be anywhere... | You can insert into a vector at position i by writing
v.insert(v.begin() + i, valueToInsert);
However, this isn't very efficient; it runs in time proportional to the number of elements after the element being inserted. If you're planning on splitting up the strings and adding them back in, you are much better off usi... |
4,800,924 | 4,800,997 | Get Process Username c++ | i am making a taskmanager like app. for windows,i can get all the system processes,now i want to get process's username.I got the code from net.
void enableDebugPrivileges()
{
HANDLE hcurrent=GetCurrentProcess();
HANDLE hToken;
BOOL bret=OpenProcessToken(hcurrent,40,&hToken);
LUID luid;
bret=LookupP... | IIRC there's a separate pseudo account called LocalService, but its not in the normal security system (hence you get a null string). There's also a NetworkService account.
|
4,801,122 | 4,801,176 | How to stop time from running backwards on Linux? | Here's a little test I've written to verify that time does indeed only run forwards in Linux.
#include <time.h>
#include <sys/time.h>
bool timeGoesForwardTest2()
{
timeval tv1, tv2;
double startTime = getTimeSeconds(); // my function
while ( getTimeSeconds() - startTime < 5 )
{
gettimeofday( &... | There is an open issue at the VirtualBox Bug Tracker. They link to a blog post stating why you shouldn't use gettimeofday() to measure the passage of time:
The most portable way to measure time
correctly seems to be
clock_gettime(CLOCK_MONOTONIC, ...)
|
4,801,146 | 4,801,156 | C++ hex string to unsigned int |
Possible Duplicate:
C++ convert hex string to signed integer
I'm trying to convert a hex string to an unsigned int in C++. My code looks like this:
string hex("FFFF0000");
UINT decimalValue;
sscanf(hex.c_str(), "%x", &decimalValue);
printf("\nstring=%s, decimalValue=%d",hex.c_str(),decimalValue);
The result is -65... | output with int with %u instead of %d
|
4,801,411 | 4,801,442 | Forward declaration of std::wstring | // This is a header file.
class MyClass; // It can be forward declared because the function uses reference.
// However, how can I do forward declaraion about std::wstring?
// class std::wstring; doesn't work.
VOID Boo(const MyClass& c);
VOID Foo(const std::wstring& s);
| You can't. #include <string>, you have (almost) no choice.
The reason is that wstring is defined in namespace std and is typedef'd to std::basic_string<wchar_t>. More elaborately, std::wstring is std::basic_string<wchar_t, std::char_traits<wchar_t> >. This means that in order to forward-declare std::wstring you'd have ... |
4,801,479 | 4,801,581 | loading gdb source for a shared library | i'm using gdb 7.2 on ubuntu 10.10
while stepping with step i get to a point that looks (literally) like this:
0x00130a2c in boost::contexts::context::impl_t::impl_t(void (*)(void*), void*, unsigned int, boost::contexts::context::impl_t*, std::auto_ptr<boost::contexts::context::allocator_base>) () from /home/lurscher/th... | You can compile the third-party library with debugging symbols, and those debugging symbols will chain [i.e. if your app is compiled with debugging symbols, you can step through and see the source lines even within the library]
boost jam takes a debug argument which will instruct it to build a debug version.
in gcc, de... |
4,801,524 | 4,801,533 | Iterator for a container of a custom object | If I've built a class that I want to contain inside, for example a set, how would I iterate through said set? Could I say
std::set<customObject>::iterator it
I thought I could do that, but I'm getting the following series of errors...
drawing.h:110: error: no match for ‘operator=’ in ‘it = ((object*)this)->object::ob... | ((object*)this)->object::objects. std::vector<_Tp, _Alloc>::begin
objects is apparently a std::vector<object>, not a std::set<object>. You therefore need to use a std::vector<object>::const_iterator.
*it.draw_in_place();
This is incorrect: you need to dereference the iterator to access the element first, then use t... |
4,801,632 | 4,801,660 | How to implicitly convert Qt objects to QString? | What's the best way of making all of the commented code below work in a standard C++/Qt way?
class A {
public:
A() { }
virtual ~A() { }
virtual QString toString() { return "A"; }
};
class B: A {
public:
B() { }
~B() { }
QString toString() { return "B"; }
};
int main(int argc, char *argv[]) {
... | You just add a so-called conversion function:
struct foo
{
operator int() { return 5; }
};
foo f;
int i = f; // uses operator to convert to int
So in your case, just replace virtual QString toString() with virtual operator QString().
That said, implicit operators are generally frowned-upon. Not only are casts fr... |
4,801,833 | 4,801,857 | Avoiding virtual functions | So suppose I want to make a series of classes that each have a member-function with the same thing. Let's call the function
void doYourJob();
I want to eventually put all these classes into the same container so that I can loop through them and have each perform 'doYourJob()'
The obvious solution is to make an abstr... | Virtual functions don't cost much. They are an indirect call, basically like a function pointer.
What is the performance cost of having a virtual method in a C++ class?
If you're in a situation where every cycle per call counts, that is you're doing very little work in the function call and you're calling it from your... |
4,801,849 | 4,801,871 | Accessing Vectors In C++ | I wrote a simple program that accesses a file called "input.txt" and pushes its contents into a vector of the string type.
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
int main()
{
fstream input;
input.open("input.txt");
string s;
input >> s;
while (!input.eof())
... | For starters, here's a much cleaner version of the code you've just written:
ifstream input("input.txt");
string s;
while (input >> s) {
cout << s << endl;
vector<string> elems;
elems.push_back(s);
}
This uses ifstream instead of fstream, which seems appropriate here since you aren't using the write facili... |
4,801,876 | 4,802,158 | Safe Lua invoke C++ registered function | Hey,everyone! I've a C++ app embedded Lua as script. A non-programmer edits the Lua script, then the C++ app invoke the Lua script and the Lua script also invokes C++ registered function.
I use Luaplus to do the above job. My question is: when the script-editor makes mistakes such as misspelling the the parameter, th... | Look at lua_cpcall and lua_pcall. They both allow protected function calls of lua in c. If they return a non-negative number then the call failed and the lua stack contains only the error string. In cpcalls case the stack is otherwise unmodified. For pcall you'll need to look at lua_pushcclosure to invoke a cfunction s... |
4,801,926 | 4,801,938 | Using a command line program from within a C# application | I have written a C++ program (which executes from the command line), that works fine. Now I need to use it for my C# application. That is to say, I would like the output from my C++ program to be used in my C# application whenever it is called.
Is it possible? If so, how?
Any links or help would be appreciated.
| You can use System.Diagnostics.Process to fire up your C++ program and redirect its output to a stream for use in your C# application. The information in this question details the specifics:
string command = "arg1 arg2 arg3"; // command line args
string exec = "filename.exe"; // executable name
string retMessage =... |
4,802,079 | 4,812,903 | How to change text alignment in QTabWidget in C++? | This is the same question as in:
How to change text alignment in QTabWidget?
I tried to port that python code into C++ but it doesn't seem to work.
Here is header file:
#include <QTabBar>
class HorizontalTabWidget : public QTabBar
{
Q_OBJECT
public:
explicit HorizontalTabWidget(QWidget *parent = 0);
protected... | the problem should be in the paint method; check if an example below would work for you, it should draw tabs the same way QTCreator does. I've reused the original tab style QStyleOptionTabV3 to do majority of paint work and then just rendered icon and tab's text on top of the image it produced:
class TestTabBar : publi... |
4,802,310 | 4,802,357 | Letting go of auto_ptr | Occasionally, for fleeting moments, I think auto_ptr is cool. But most of the time I recognize that there are much simpler techniques that make it irrelevant. For example, if I want to have an object freed automatically, even if an exception is thrown, I could new up the object and assign to an auto_ptr. Very cool! ... | It's the simplest thing to use when you need a scoped or unique pointer and you are working in a strict C++03 environment with no access to a tr1 implementation or boost.
|
4,802,315 | 4,802,402 | Why pre-increment operator gives rvalue in C? | In C++, pre-increment operator gives lvalue because incremented object itself is returned, not a copy.
But in C, it gives rvalue. Why?
| C doesn't have references. In C++ ++i returns a reference to i (lvalue) whereas in C it returns a copy(incremented).
C99 6.5.3.1/2
The value of the operand of the prefix ++ operator is incremented. The result is the new value of the operand after incrementation. The expression ++Eis equivalent to (E+=1).
‘‘value of ... |
4,802,337 | 4,802,413 | Compiler error: unmatched call to pow(...) | My company has a piece of software, sporting a rather large codebase. Recently I was assigned the task of checking wether the code would compile on an x86_64 target using gcc 4.1.2. I've gotten pretty far in the compilation with very minor modifications to the code but just this morning I got a somewhat confusing compi... | If you are making many calls to pow(int, unsigned int) why don't you just code it by yourself? If execution speed is not an issue, it's not much work.
Otherwise, I'd use a pow() overload whose input parameters are guaranteed to contain your expected values, such as pow(float, float) or pow(double, double). Anyway, I fe... |
4,802,494 | 4,802,556 | do I need to close a std::fstream? |
Possible Duplicate:
Do I need to manually close a ifstream?
Do I need to call fstream.close() or is fstream a proper RAII object that closes the stream on destruction?
I have a local std::ofstream object inside a method. Can I assume that the file is always closed after exiting this method without calling close? I c... | I think the previous answers are misleading.
fstream is a proper RAII object, it does close automatically at the end of the scope, and there is absolutely no need whatsoever to call close manually when closing at the end of the scope is sufficient.
In particular, it’s not a “best practice” and it’s not necessary to flu... |
4,802,502 | 4,802,553 | __purecall problem in VS2010 using virtual function - once method gets a purecall | I have a very odd Problem:
I use one of my base classes: IEventlistener() which gets implemented by many other classes. Most of the time the system works. But now a very strange problem occured.
Once class (CGUIService) implements the interface, one method (VGetListenerName) works as expected the other one (VHandleMess... | It is hard to judge from one screenshot, but from the information you gave my first guess would be a dangling pointer - perhaps you attempt to call the virtual method on an object which was already destroyed? Another possibility is the object is not completely constructed yet, but this is not very likely, as this would... |
4,802,516 | 4,802,567 | Converting number of 100 ns since 1601 to boost posix time in C++ | I am receiving from a data provider timestamps that follow this specification:
number of 100 nanoseconds since 1601
I am using boost::posix_time::ptime and I would like to convert the timestamps to posix time. Is there a simple way to do that ?
| When did the switch from the Julian to Gregorian calendar occur for this system? Some countries switched before 1st January 1601; others didn't switch until much later. This will critically affect your calculation - by 11 days or so.
Since there are 107 units of 100 ns each in one second, you divide the starting numb... |
4,802,590 | 4,802,623 | Reading Configuration xml files in C++ | How can the following configuration file be read in C++. Is there any support in STL. I can't afford to use other 3rd party libraries.
<?xml version="1.0" encoding="utf-8"?>
<appSettings>
<add key="FileType" value="doc"/>
<add key="FileLength" value="102234"/>
</appSettings>
I am not using managed C++.
| STL has no support for parsing xml. If you're determined not to use a third party library then your only other option is to write a parser by hand, this seems like a pretty bad idea. Why exactly can't you afford to use third party libraries?
|
4,802,628 | 4,803,433 | Good Open Source Software to Analyse | I'm looking for an informative and important open source software product to do an investigation and analysis for my University project. What are some good open source projects to study on? I prefer something written in Java, C, C++ etc.
This study is a comparison between programming languages (language evaluation) lik... | You could hit one of the open source hosting services like Github, Google Code, SourceForge, Launchpad, etc. Cruise through the repositories in there until you find something interesting. There are literally thousands of projects in there--git, jQuery, rails (Ruby on Rails), django, V8, Greasemonkey, etc. You can bl... |
4,802,673 | 4,803,726 | How to optimize a for loop? | I have a problem, let's say:
Find all two pairs of numbers (x,y) and (z,t) such that x³ + y³ = z³ + t³, where (x, y) != (z, t) and x³ + y³ < 10,000.
Taking the cube root of 10,000 yeilds 21.544 -> round down to 21, so I got:
#include <iostream>
using namespace std;
int main() {
for( int x = 1; x <= 20; ++x ) {
... | Typical tradeoff: memory for speed.
First the bound on x is quite large: if we suppose that (x,y) is ordered with x <= y, then
x^3 + y^3 < N and x^3 < y^3 (for positive numbers)
=> x^3 + x^3 < N (by transitivity)
<=> x^3 < N/2
<=> x <= floor((N/2)^(1/3))
Thus x <= 17 here.
Now, let us memoize the result of x^3 + ... |
4,802,674 | 4,802,849 | How to pass two-dimensional array as an argument? | My Matrx class is defined as
class Matrx
{
double A[50][50];
int m,n;
public:
Matrx(void);
Matrx(int a, int b)
{
m=a;
n=b;
}
Matrx operator +(Matrx b);
Matrx Transpose(Matrx b);
Matrx operator *(Matrx b);
CString printMatrx();
void readMatrx(double a[][]);
Matrx TransposeMat(Matrx b);
};
void Matrx::r... | You need to properly learn about arrays and pointers. This includes the lesson "huh! They are not as useful as I thought they were". After you've gotten familiar with how arrays and pointers work exactly you should rethink your design.
For example, in my opinion, the following design has lots of advantages:
#ifndef MAT... |
4,803,531 | 4,803,592 | Creating functor from lambda expression | I would like to know if it is possible to create an actual functor object from a lambda expression. I don't think so, but if not, why?
To illustrate, given the code below, which sorts points using various policies for x and y coordinates:
#include <vector>
#include <functional>
#include <algorithm>
#include <iostream>
... | This problem arises because SortXY only takes types, whereas lambdas are objects. You need to re-write it so that it takes objects, not just types. This is basic use of functional objects- see how std::for_each doesn't take a type, it takes an object.
|
4,803,536 | 4,803,674 | How can I Always open server? | I have code (my c++ socket server) but I don't know How can I always open. My server will close. when It already send to client It will close itself. But I want it to wait others client and never closed. How can I do it ? Oh I use multi-threaded too.
please,Help me.
and here is my code
int main(void)
{
HANDLE hThread... | You have to use a loop for that :)
Basically, the server main code must be in a loop, that will go forever ... while you do not stop it.
you should have :
// That's close to pseudo code :)
while(notStoppedByMaster)
{
// [...]
ClientSocket = accept(ListenSocket, NULL, NULL);
handleRequest(ClientSocket);
}
... |
4,803,607 | 4,803,715 | How do I Quickly Compare Variable-Length Bit Strings in C++? | I'm performing comparisons of objects based on the binary presence or absence of a set of features. These features can be represented by a bit string, such as this:
10011
This bitstring has the first, fourth and fifth feature.
I'm trying to calculate the similarity of a pair of bit strings as the number of features t... | You can use the std::bitset STL class.
They can be built from bit strings, ANDed, and count the number of 1:
#include <string>
#include <bitset>
int main()
{
std::bitset<5> option1(std::string("10011")), option2(std::string("10010"));
std::bitset<5> and_bit = option1 & option2; //bitset will have 1s only on common... |
4,803,641 | 4,819,137 | Game NPC multi-action lua script design | I need to put scriptable NPC in my currect game project.
The project itself is developed in C++ language.
I will using Luabind to bind lua and c++.
I need to call NPC function when certain NPC clicked or timer to do something is activated.
Currently I stuck between 2 NPC script design.
Using a kind of npcname_action t... | I've done something like this before and I used something similar to your #2 option. When the map loads I load a configuration Lua file containing all the NPC data; among that is the name of the script file used for the NPC.
When I need to load the NPC in the game I compile the Lua file. NPC's can use a 'model' NPC t... |
4,803,689 | 4,860,120 | Sharing a boost::asio::io_service object between dynamically loaded libraries | First what I did (minimum sample will be provided if it's not just me doing something plain stupid):
I have a GUI application that shall support several network interfaces to change content that's displayed in the GUI. The network interfaces are realized as plugins that are dynamically loaded on GUI startup. The GUI ap... | I would check several options:
* Maybe the object is copied at some point rather than passed by reference; you can make it boost::noncopyable to prevent this from happening.
* Check the return value of poll if it is bigger than 0 some handler was run; if it is 0 the problem is boost think there are no handler.
* Add a ... |
4,803,898 | 4,803,956 | Fill in the int array from zero to defined number | i need to fill in the int[] array in C++ from zero to number defined by variable, but ISO C++ forbids variable length array...
How to easily fill in the array? Do i need to allocate/free the memory?
int possibilities[SIZE];
unsigned int i = 0;
for (i = 0; i < SIZE; i++) {
possibilities[i] = i;
}
btw. if you would ... | As you've found, you cannot create a variable-length array on the stack. So your choices are either to allocate it on the heap (introduces memory-management issues), or to use a std::vector instead of a C-style array:
std::vector<int> possibilities(SIZE);
for (int i = 0; i < SIZE; i++)
{
possibilities[i] = i;
}
I... |
4,803,900 | 4,804,234 | Object-oriented semaphore usage in C++ | I know how to use Unix semaphores in C. Before using them I must call a constructor-ish function named sem_init and after using them I have to call a destructor-like function named sem_destroy.
I know I can keep doing this in C++ because of its backwards compatibility with C, but does C++ have a real object-oriented wa... | If you really insist on using POSIX semaphores and not Boost, you can of course wrap sem_t in a class:
class Semaphore {
sem_t sem;
public:
Semaphore(int shared, unsigned value)
{ sem_init(&sem, shared, value); }
~Semaphore() { sem_destroy(&sem); }
int wait() { return sem_wait(&sem); }
int ... |
4,803,926 | 4,805,526 | Boost Plugin choices | I'm looking to implement a plugin architecture into our current application (Unix, C++) and have been reviewing the options (pending approval) within the Boost libraries.
Edit: I'm looking to dynamically add classes at runtime.
Boost.Plugin
Boost.Reflection
Boost.Extension
I was wondering what everyones experience/opin... | Eh. We just used dlopen and dlsym along with a pair of extern "C" static functions that must be defined in the dll
extern "C" static plugin* create( arg_pack* );
extern "C" static errno_t destroy( plugin* );
Have a plugin-manager look for ".dll" or ".so" files and load them into a
map<string, pair< plugin*(*)(arg_pack... |
4,804,021 | 4,804,073 | What is the difference between these three statements? | What is the difference between these three statements?
static const int foo = 42;
const int foo = 42;
#define foo 42
| 2) const int foo = 42;
This is an int variable whose value you can't change.
1) static const int foo = 42;
This is the same as 2), but it's only visible in the source code file that it's in. So you can't use it in another .cpp file for example if you compile them separately and then link together. By using static wit... |
4,804,154 | 4,804,175 | Copy of const char * using std::string constructor | is this code ok?
void SomeClass :: foo(const char * _name) {
//name is of type const char *
name = std::string(_name).c_str();
}
it looks like it is working, but iam not sure if it is ok
should i do an old school strcpy ?
| It's ok since it compiles and doesn't cause undefined behavior.
It's not ok since name points to an invalid memory after the statement completes execution.
name = std::string(_name).c_str();
At the end of this statement the temporary std::string is destroyed and it frees the memory of c_str().
should i do an old scho... |
4,804,186 | 4,804,221 | UPDATE: C++ undefined reference | When I try to run the following C++ program: UPDATE (Updated code since the past link had some errors): http://pastie.org/private/pdpfpzg5fk7iegnohebtq
I get the following:
UPDATE
The errors that arise now are as follows:
Any ideas on that?
Thanks.
| You're not linking in GradeBook.o so you're getting an undefefined reference.
Try
g++ GradeBookMain.cc GradeBook.cc -o GradeBookMain
You also have a typo "maximun" instead of "maximum" in GradeBook.h
|
4,804,258 | 4,804,327 | C++: Checking for NULL on delete |
Possible Duplicate:
Test for void pointer in C++ before deleting
Is code snippet 1 equivalent to snippet 2?
//Snippet 1:
delete record;
record = new Record;
//Snippet 2
if (record != NULL)
{
delete record;
record = NULL;
}
record = new Record;
| The only difference I can see is that if the Record constructor throws an exception, the first sample might leave the record variable set to the old deleted value, whereas in the second, it will be set to NULL.
EDIT:
Indeed the first sample, if repeated later, would lead to a double delete.
delete record;
record = new ... |
4,804,274 | 4,804,338 | How to run the application at windows startup without touch the Registry? | In my Windows 7, some applications run automatically at startup but in in the Run key of the registry there is nothing about these applications.
So I would to know How to run the application at windows startup without touch the Registry.
| Here's a non-exhaustive list of ways on might run something at startup:
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Run (for 64bit Windows)
HKCU\Software\Microsoft\Windows\CurrentVersion\Run
Install a service
Schedule a task (seems quite trendy... Googl... |
4,804,298 | 4,805,413 | How to convert wstring into string? | The question is how to convert wstring to string?
I have next example :
#include <string>
#include <iostream>
int main()
{
std::wstring ws = L"Hello";
std::string s( ws.begin(), ws.end() );
//std::cout <<"std::string = "<<s<<std::endl;
std::wcout<<"std::wstring = "<<ws<<std::endl;
std::cout <... | Here is a worked-out solution based on the other suggestions:
#include <string>
#include <iostream>
#include <clocale>
#include <locale>
#include <vector>
int main() {
std::setlocale(LC_ALL, "");
const std::wstring ws = L"ħëłlö";
const std::locale locale("");
typedef std::codecvt<wchar_t, char, std::mbstate_t>... |
4,804,387 | 4,804,407 | C++ Base constructor calling with parameter that will be constructed in the derived constructor | QUESTION 1)
class Base {
Base(std::string name);
virtual std::string generateName();
}
class Derived : Base {
Derived();
virtual std::string generateName();
}
here comes the question :
what method will be called on generateName() ?
Derived :: Derived : Base(generateName()) {
//what method will b... | First, the solution: use a static member function or a nonmember function.
As for the behavior, Derived::generateName() will be called. The long sentence in the C++ Standard that defines this behavior says (C++03 12.7/3):
When a virtual function is called directly or indirectly from a constructor (includ... |
4,804,427 | 4,804,471 | std::next_permutation() from a part of vector | i'm trying to generate permutations from a part of a vector. See below.
vector<int> myArray;
myArray.resize(5);
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
myArray[3] = 4;
myArray[4] = 5;
int i = 0;
do {
for (i = 0; i < myArray.size(); i++) {
printf("%i ", myArray[i]);
}
printf("\n");
} while (... | while (next_permutation(myArray.begin()+1, myArray.begin()+3)); should work
|
4,804,431 | 4,804,571 | Casting from string to void* and back | is possible to re-map STL class object from void* ?
#include <string>
void func(void *d)
{
std::string &s = reinterpret_cast<std::string&>(d);
}
int main()
{
std::string s = "Hi";
func(reinterpret_cast<void*>(&s));
}
| Use static_cast to convert void pointers back to other pointers, just be sure to convert back to the exact same type used originally. No cast is necessary to convert to a void pointer.
This works for any pointer type, including pointers to types from the stdlib. (Technically any pointer to object type, but this is wh... |
4,804,647 | 4,804,839 | Access violation error by using pointer to creat object | so i just started windows programing with C++. First I draw some lines and it was OK,
then i tried to create a class for drawing some shapes, and it's working fine when I'm using a normal method to create object (in the code these parts are commented out),
but when I'm using a pointer to create new object, I get an Acc... | The problem is that you don't construct a shapes object until receiving (and handling a WM_LBUTTONDOWN) event. So if any other event (eg. WM_MOUSEMOVE) is handled before, then sh will still be 0.
Besides, note that you have a memory leak here: you call sh = new shapes(); for every WM_LBUTTONDOWN event, without ever del... |
4,804,653 | 4,805,000 | C++ object persistence library similar to eternity | I'm looking for a C++ object persistence library to replace the Eternity library that I've been prototyping with for about a day. The Eternity library came up short.
I've created an object hierarchy similar to this:
I have an std::list of ArchiveJob*'s that I'd like to persist and restore in XML format. Each Archive... | Boost Serialization is what you need:
serializing containers
it's cross-platform and windows-friendly despite the fact that it doesn't have VS2008 solution file
serializing derived class
[EDIT] actually I was wrong, it includes VS7.1 solution file
|
4,804,655 | 4,804,707 | Finding type of path using the Windows API | I'm trying to find the type of file a path is. I have this for Linux::
pathType CFilesystem::findPathType(const string& path) const
{
struct stat info;
int status = stat(path.c_str(), &info);
if(status == -1)
{
switch(errno)
{
case ENOENT:... | In windows, I think the function you are looking for is GetFileAttributesEx
You can also use the regular _stat function on windows as well though. Are you including sys/types.h and sys/stat.h?
|
4,805,141 | 4,806,583 | Driver Backup using setupapi | I'm stuck. To cut long story short, the task is to enumerate all driver files for backup. For some drivers like display adapter driver, I use
SetupScanFileQueue(queueHandle,
SPQ_SCAN_USE_CALLBACKEX,NULL,
DumpDeviceDriversCallback,&count,&scanResult)
from setupapi and that's working fine as in... | There are lots of devices that are installed using what's called a "No Driver" INF. These INFs provide enough information such that Device Manager will have some info to show for the device (thus avoiding them appear in the "unknown devices" category) but don't actually install any drivers.
These devices do not need dr... |
4,805,236 | 4,805,304 | Modules Design in C++ | I'm new in this website and I want to ask you some questions about C++ because I'm learning it these days and I'm a noob (I just know C and Java).
I'm using the Stroustrup book but I still don't understand the uses and differences between classes and namespaces.
Also I did some C programs for a subject (operating syste... | You won't get far with just namespaces on their own :) All they do (as their name suggest) is provide a named-space for types to prevent pollution of the global namespace, and prevent conflict between identical type names. Therefore it is common for an API to have an outer namespace containing everything it has, ther... |
4,805,278 | 4,805,691 | Permutations of multiple ranges of numbers | I need to generate permutations from multiple ranges of numbers in array.
using namespace std;
int generatePermutations(vector<int> &myVector, vector<vector<int> > &swappable) {
int i = 0, s = 0;
for (s = 0; s < swappable.size(); s++) {
do {
for (i = 0; i < myVector.size(); i++) {
... | I take it swappable is a set of ranges which may be swapped? So [[1, 3], [4, 6]] means anything in [1, 3) (indexes 1 and 2) can be swapped around in that range, and similarly for [4, 6)? Is it also true that the ranges will never overlap?
How does this look:
typedef vector<vector<int> >::const_iterator SwappableIter;... |
4,805,462 | 4,805,572 | How to add specific header folders to Eclipse? | I have a c++ project in a unix environment, that has a CMakeLists.txt. I used Cmake to convert it into an Eclipse project and import it in Eclipse CDT. Now, it says it can't find files in #include "file.h" statements.
This project has more than 20 folders and some of these folders contain the headers. I went to Projec... | You can specify include directories in the original CMakeLists.txt using the include_directories command and re-generate the Eclipse project. This has the advantage over specifying the include directories in Eclipse because it will work for other CMake targets as well.
|
4,805,544 | 4,808,633 | Whether there is a UDT backend for boost::asio? | Please, tell to me are whether exist UDT protocol backend for boost::asio?
UDT is a reliable UDP based application level data transport protocol for distributed data intensive applications over wide area high-speed networks. ( http://udt.sourceforge.net/index.html )
| TCP, UDP, and ICMP are supported by Boost.Asio. Other protocols can be implemented by extending the Protocol type requirements. There are several threads on the asio-users mailing list discussing adding support for SCTP, you may be able to use that as an example.
|
4,805,807 | 4,806,200 | SFINAE: detect if class has free function | Is there a way, using SFINAE, to detect whether a free function is overloaded for a given class?
Basically, I’ve got the following solution:
struct has_no_f { };
struct has_f { };
void f(has_f const& x) { }
template <typename T>
enable_if<has_function<T, f>::value, int>::type call(T const&) {
std::cout << "has f... | #include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <functional>
#include <type_traits>
struct X {};
struct Y {};
__int8 f(X x) { return 0; }
__int16 f(...) { return 0; }
template <typename T> typename std::enable_if<sizeof(f(T())) == sizeof(__int8), int>::type call(T const& t) {
... |
4,805,844 | 4,805,943 | C++ EasyBMP Pointer Issue | The following code is causing a Segmentation Fault on the .ReadFromFile line:
int main()
{
// Load in.bmp
BMP * original;
cout << "line " << __LINE__ << ": Got here!" << endl;
original->ReadFromFile("in.bmp"); //Error HERE!
int width = original->TellWidth();
int height = original->TellHeight();
cout << "line " << __L... | Your pointer original is pointing to a random memory location. Trying to use it will cause the undefined behavior. You need to allocate memory for BMP object and store the address in this pointer. If you want your object to persist even after it goes out of the function use original = new BMP();(don't forget to delete ... |
4,805,864 | 4,806,022 | Static definition lists | I need to create definition lists in C++ that would describe SQL tables. For the moment I'm doing it like this, as it does not really need to be a real object, and it is rather convenient to initialize this way:
namespace Table_name
{
static ColumnList Cols("Table_name");
static const Column Id ("Id INTE... | you can use singleton for this to be sure that you don't have any problem related to undefined order of static initializations
also you can check MySql++ library to check how they resolve table structure definition problem
|
4,805,865 | 4,805,917 | which one faster concurrent_queue<> vs mutex-ed queue<> during iteration | suppose you want to iterate all item in the queue which implemented using concurrent_queue<> and std:queue<>.
Since on concurrent_queue<> there is no iterator, so I can only think that I need to do try_pop() and push() until you pop-ed and re-push-ed all items in the concurrent_queue<>.
which one is more efficient in ... | If you're in a multithreaded environment and you push/pop from the queue to check it, won't other threads see imprecise data if you context-switch between a pop and a push operation? And another thread might push another object off, so the first thread would miss it... etc.
It's just too complicated, too fraught with r... |
4,805,935 | 4,805,956 | C++ dynamic binding problem | The questions are:
a) Is the following code legal or not ? (considering it crashes at run-time)
b) If there is any compiler flag for gcc or MVC to show at compile time, a potential problem in the following code ?
#include <iostream>
using namespace std;
class A
{
public:
void write(){ cout<<"A"; }
};
class ... | No, it's not legal. B doesn't derive from A, nor vice versa. Forcing a cast like this results in undefined behaviour. You're telling the compiler "shut up, I know what I'm doing", which leads to all sorts of trouble. This is one reason to avoid old C-style casts, and use C++-style casts instead (static_cast, etc.).... |
4,805,968 | 4,806,665 | passing variable to a thread after it already started | i am newbie in C++ and boost.
As part of my master thesis, i wrote a program which simulate a statistical model. During the computation, i use boost::thread to process my "center of mass vector", for saving some computation time. So far so good.
Now, i would like to take each result from the boost::thread (each time on... | the simplest possible way is to use std::queue, boost::mutex and boost::conditional_variable. wrap any access to queue by mutex, after pushing to queue call conditional_variable.notify_one(). in consumer thread wait on conditional_variable until any result is ready, then process it.
|
4,806,013 | 4,806,072 | C-style struct initialization from initialization list in C++ | Is there syntax that allows you to use the struct initialization syntax:
struct A { int a; int b; }
int main()
{
A a = { 1, 2 }; //syntax
return 0;
}
in an initialization list? E.g.
class B
{
public:
B(int a_, int b_) : obj { a_, b_ } { }
private:
A obj;
};
| If you have a class with public member variables, you can automatically use it the same way as you would do with structs. But in C++ there's not a way to define arbitrary initializer list behavior. But in C++0x there is, as pointed out here. If you happen to be using GCC, this feature is supported in GCC 4.4 and above ... |
4,806,035 | 4,806,267 | Can you retrieve source from a debug-compiled binary? | I was digging around and found an executable for something I wrote in Visual C++ 6.0 about 8 years ago. I never backed up the source code, but I think I always compiled everything in debug mode. I also vaguely remember hearing somewhere that "you can't decompile an executable into source code unless you have your compi... |
I do not believe there is a flag though you might find something by using PEDUMP which will dump out COFF file formats (Windows EXE and DLLs). You can infer if an executable was compiled for debug rather quickly by running Dependecy Walker and seeing if your EXE is linking to any debug DLLs (suffixed with D, e.g. MSV... |
4,806,157 | 4,806,234 | Any way to cout in base64? | I know I could use itoa to create a base64 string, just wondered if there was an easy way to cout a number in base64 the same way cout << hex sets a flag to display integral values in hex...
| There isn't a built-in way (setbase only accepts 8, 10, 16 as parameters). You'll have to write your own stream manipulator.
|
4,806,167 | 4,806,275 | reverse the position of integer digits? | i have to reverse the position of integer like this
input = 12345
output = 54321
i made this but it gives wrong output e.g 5432
#include <iostream>
using namespace std;
int main(){
int num,i=10;
cin>>num;
do{
cout<< (num%i)/ (i/10);
i *=10;
}while(num/i!=0);
return 0;
}
| Your loop terminates too early. Change
}while(num/i!=0);
to
}while((num*10)/i!=0);
to get one more iteration, and your code will work.
|
4,806,238 | 4,807,085 | Can't compile SFINAE in Visual Studio 10 | #include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <functional>
#include <type_traits>
struct X {};
struct Y {};
__int8 f(X x) { return 0; }
__int16 f(...) { return 0; }
template <typename T> typename std::enable_if<sizeof(f(T())) == sizeof(__int8), int>::type call(T const& t) {
... | This compiles and works correctly in VS2010. Modified using suggestion by David.
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <functional>
#include <type_traits>
struct X {
typedef X is_x;
};
struct Y {};
__int8 f(X x) { return 0; }
__int16 f(...) { return 0; }
template... |
4,806,510 | 4,817,981 | const variables in header file and static initialization fiasco | After reading a lot of the questions regarding initialization of static variables I am still not sure how this applies to const variables at namespace level.
I have kind of the following code in a header file config.h generated by the build script:
static const std::string path1 = "/xyz/abc";
static const std::string p... | I tried to get the necessary information right from the C++03 Standard document. Here is what I found:
Regarding the const static declarations:
According to section 3.5.3 objects defined at namespace level and declared const have internal linkage by default. static also declares a namespace level object to have interna... |
4,806,567 | 4,806,811 | MSVC 2008 Immediate Window nonsense and some code confusion | I've been fooling with the MSVC 2008 immediate window for the last few hours and I'm flabbergasted with both myself and Microsoft... It probably doesn't help that I stumbled on this mystery at bedtime and it's now 6 hours later. :)
Please see the following:
? "1234567\\87654321\\"
CXX0026: Error: bad format string
I... | size_t endpos = str.find_last_not_of( L”\\/” ); // no
size_t endpos = str.find_last_not_of( L"\\/" ); // yes
Beware of code that you copied off a website, maybe a blog post. The author may well have used a word processor, one that implements 'smart quotes'. If you look closely at the first and the second line you'... |
4,806,625 | 4,949,623 | Fstream fails to create new file | I'm using a FileManager for a project so that reading and writing is less of a hassle for me. Or would be, if I didn't spend all this time debugging it. So, this comfort-class actually caused me stress and time. Awesome.
The problem seems to be the fstream. Before I continue further, here is the structure of my FileMa... | Best method:
void FileManager::open(std::string const& filename)
{
using std::ios_base;
if( stream_.is_open() )
stream_.close();
stream_.open( filename.c_str() ); // ...try existing file
if( !stream_.is_open() ) // ...else, create new file...
stream_.open(filename.c_str(), ios_base::in ... |
4,806,827 | 4,806,936 | C++: Defined my own assignment operator for my type, now .sort() wont work on vectors of my type? | I have a class (those that have read Accelerated C++ may find this class familiar) defined as follows:
class Student_info{
public:
Student_info() : midterm(0.0), final(0.0) {};
Student_info(std::istream& is){read(is);};
Student_info(const Student_info& s);
~Student_info();
Student_info& operator=... | No, no, no. It's not supposed to work that way at all. Your current assignment operator destroys the object it's called on, then calls itself (oh hey, infinite recursion) on a destroyed object (oh hey, undefined behaviour). You are not supposed to destroy the existing object. At all. And this code *this = s does not in... |
4,807,025 | 4,807,060 | In C++, how do I correctly load a file into an array of wider than char data types? | Specifically, I'm trying to program an FPGA with a binary file. The transaction register is 16-bits wide. So I need to create an array of uint16_t and fill it with an input file. Here is what I tried:
int bufferSize = 512;
uint16_t buffer[bufferSize];
std::ifstream *pStream = new std::ifstream( filepath );
if( pStre... | It seems you've run into an endianness issue. You may need to use htons() or alike to get the endianness you desire. (use it on every element of the array, e.g. with a loop or std::transform). See http://beej.us/guide/bgnet/output/html/multipage/htonsman.html for some more detail.
|
4,807,033 | 4,807,067 | std::cin extract to enum | I don't understand why I can't to that:
enum MyEnum {X=1, Y};
...
X x;
std::cin >> x;
the problem is that C++ is not smart enougth or I'm mistaking something?
| You can, but you need to write a custom operator>> overload:
std::istream& operator>>(std;:istream& is, MyEnum& e) { ... }
The reason you cannot do this with the default std::istream operator>> overloads is that the right side argument must exactly match the parameter of the operator overload because it is taken by no... |
4,807,065 | 4,807,133 | How can I get the amount of bytes transfered and received on the windows platform? | I want to know the amount of data that transfered and received on the windows platform. Is there any APIs that supply this information? I can only find the bandwidth information from WMI, such as data sends per second.
Thanks!
| You can get the amount of data transmitted/received (among other things) for each network adapter in the machine with GetIfEntry. To use it, you'll need to get a list of adapters with GetIfTable (or one of its relatives, such as GetIfTable2).
|
4,807,066 | 4,807,117 | How do I construct a std::string with a variable number of spaces? | If I have the following code:
std::string name = "Michael";
std::string spaces = " ";
How would I programatically create the spaces string (a string with all spaces, the length matching the name variable)?
| You can pass a character and a length to a string, and it will fill a string of that length with the given character:
std::string spaces(7, ' ');
You can use the .size() property of std::string to find the length of your name; combined with the above:
std::string name = "Michael";
std::string spaces(name.size(), ' ');... |
4,807,166 | 4,809,931 | Bandwidth Monitoring using c++ program | I am developing a small application that requires a module that would check whether there is bandwidth or not.Basically the module should trigger an event when the bandwidth goes down. Can this be achieved using c++ program
| Look for your network interface in /sys/class/net/ directory. My system only has two interfaces lo and eth0.
There are a lot of files describing the status of the interface to explore.
I would start with operstate, statistics/rx_bytes or statistics/rx_packets.
|
4,807,259 | 4,808,027 | Adding an existing project to a solution edits project file | I have a C++ solution (solution.sln) where I want to include an existing library (library.vcproj), so I open solution.sln in Visual Studio and include the library.vcproj file for it. Then I set up the project dependencies and some include paths to get it to compile. Everything works fine.
When I'm about to commit these... | I found the reason for this behavior. It's not a VS bug, it's actually a robust behavior!
There is another library includd into solution.sln with the same GUID so VS updates the GUID of the incoming library.vcproj.
Digging into svn logs I could find that someone copied the library.vcproj file from anther library and ed... |
4,807,286 | 4,807,318 | Shared void pointers. Why does this work? | To solve a very peculiar problem in my application I need a shared-pointer to allocated data, but to the outside world, the underlying data type should remain hidden.
I could solve this by making some kind of Root class of which all my other classes inherit, and use a shared_ptr on this Root class, like this:
std::shar... | The shared_ptr constructor that you use is actually a constructor template that looks like:
template <typename U>
shared_ptr(U* p) { }
It knows inside of the constructor what the actual type of the pointer is (X) and uses this information to create a functor that can correctly delete the pointer and ensure the correct... |
4,807,419 | 4,808,190 | How to identify (or connect) User id with incoming socket? | I need to identify the unique id of Socket. That's the right way to use socket descriptor?
Is socket descriptor unique?
For example
QTcpSocket* pClientSocket = nextPendingConnection();
int id = pClientSocket->socketDescriptor();
User user(id);
/*...*/
void slotReadClient(){
socket = (QTcpSocket*)sender();
user = us... | Socket ids (which are actually file descriptors) are instantaneously unique over their lifetime. Meaning the following:
int my_fd socket(...);
/* during this time no calls to socket will ever return my_fd */
close(my_fd);
I'm not sure the specifics of what you mean by user id, I think that this wouldn't work because... |
4,807,484 | 4,807,852 | Qt using boost::shared_ptr in a signal/slot | Is it possible, and if so, how can I create a signal/slot in Qt that is a const reference to a shared_ptr? I want a signal that looks like this:
void signal( shared_ptr<SomeClass> const & )
I know how to do this without a constant reference, that is simply the type shared_ptr<SomeClass> but for efficiency* reasons I'd... | So far I have found that I can simply do this:
Q_DECLARE_METATYPE(shared_ptr<SomeClass>)
qRegisterMetaType<shared_ptr<SomeClass> >();
qRegisterMetaType<shared_ptr<SomeClass> >("std::shared_ptr<SomeClass>const&");
I'm trying to verify now whether this truly works correctly. The documentation here isn't clear on what ac... |
4,807,629 | 4,807,695 | How do I find the current directory? | I am trying to read a file which I read previously successfully.
I am reading it through a library, and I am sending it as-is to the library (i.e. "myfile.txt").
I know that the file is read from the working/current directory.
I suspect that the current/working directory has changed somehow.
How do i check what is the ... | Since you added the visual-c++ tag I'm going to suggest the standard windows function to do it. GetCurrentDirectory
Usage:
TCHAR pwd[MAX_PATH];
GetCurrentDirectory(MAX_PATH,pwd);
MessageBox(NULL,pwd,pwd,0);
|
4,807,643 | 4,807,726 | Container covariance in C++ | I know that C++ doesn't support covariance for containers elements, as in Java or C#. So the following code probably is undefined behavior:
#include <vector>
struct A {};
struct B : A {};
std::vector<B*> test;
std::vector<A*>* foo = reinterpret_cast<std::vector<A*>*>(&test);
Not surprisingly, I received downvotes when... | The rule violated here is documented in C++03 3.10/15 [basic.lval], which specifies what is referred to informally as the "strict aliasing rule"
If a program attempts to access the stored value of an object through an lvalue of other than one of the following types the behavior is undefined:
the dynamic type of the o... |
4,807,709 | 4,807,736 | How can I change the value of the elements in a vector? | I have this code, which reads in input from a file and stores it in a vector. So far, I've gotten it to give me the sum of the values within the vector and give the mean of the values using the sum.
What I'd like to do now is learn how to access the vector again and subtract a value from each element of the vector and... | You can simply access it like an array i.e. v[i] = v[i] - some_num;
|
4,807,866 | 4,808,003 | Can I globally redirect the output of system() calls? | I have a program that executes various shell commands via system() and occasionally prints to cout. I want to redirect all output coming from system() calls to a log file so they don't clutter up the normal output. Can I do this without having to append > log to all my system commands?
| Looks like you can use popen
|
4,808,165 | 4,808,451 | C++ std library linking with different C++ standards | I am compiling a project using Cygwin (GCC v4.5.0) and I'm having an odd linker problem. I am hoping somebody with some expertise can help.
Error: undefined reference to std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::basic_string<char, std::char_traits<char>, std::allocator<c... | Yes, both new revisions of the standard and technical reports make many changes to the content of the standard library. The function you referenced (std::string's move constructor) is newly added in C++0x's standard library.
The version of the standard does not affect name mangling, although the compiler version does,... |
4,808,812 | 4,809,366 | Using xadd for different integer widths | I'm currently porting atomic.hpp out of boost for a project and would like to generalize the atomic add function whereby it's templated on the type to add:
template <typename T, typename V>
inline T add(volatile T* mem, V val)
{
T r;
asm volatile
(
"lock\n\t"
"xadd %1, %0":
"+m"( *m... | Yes, you can use lock xadd under IA32 or IA64 with all types of numbers 8, 16, 32 and 64 bit signed or unsigned.
The memory alignment isn't needed but if it is, then the memory access is faster.
From Intel Manual:
The integrity of the LOCK prefix is
not affected by the alignment of the
memory field. Memory locking... |
4,808,922 | 4,808,937 | C++ pass-by-reference | I'm trying C++ pass-by-reference using this simple code:
#include <iostream>
int square(int &x)
{
return x*x;
}
int main()
{
std::cout<<"Square of 4 is: "<<square(4)<<std::endl;
return 0;
}
But, when I try to run it, I get the following:
UPDATE
I get the following error after modifying the code based on @Pablo Santa ... | You can't pass a constant (4) if you are expecting a reference.
You must pass a variable:
int n = 4;
square(n);
Having said that, you probably want something like this:
void square(int &x)
{
x = x*x;
}
Not a function returning an int.
|
4,808,957 | 4,809,754 | Need to speed up C++ code involving Boost multi-index and lookups to unordered_multimap | I'm looking for strategies to speed up an agent-based model that's based on objects of class Host, pointers to which are stored in a Boost multi-index container. I've used Shark to determine that the vast majority of the time is consumed by a function calcSI():
Function calcSI() has to compute for every instance of cl... | Like you suggested in #1, try maintaining a carriage count array next to the Host::carriage unordered_multimap and keep them both "synchronised". Your Host::isInfectedZ would then use the (hopefully) faster carriage count array:
int Host::isInfectedZ( int z ) const {
return carriageCount[ z ];
}
If the range of inte... |
4,808,965 | 4,808,983 | How do I return a vector<T> from a function in c++ | I am creating a generic data structure and I want to return a vector that contains some of the objects in my structure.
I tried
template<class T>
vector<T> DataStructure<T>::getItems(int count)
{
vector<T> items;
for(int i = 0; i < count; i++)
items.push_back(data[i]);
return items;
}
But t... | vector is not defined.
You need to #include <vector> and to specify its namespace either using std::vector or putting an using namespace std; in your function or at the global scope (this latter suggestion should be avoided).
#include <vector>
template<class T>
std::vector<T> DataStructure<T>::getItems(int count)
{
... |
4,809,541 | 15,053,925 | wxWidgets 2.9.1 - Problem with keyboard navigation when using multiple wxStaticBoxes | wxWidgets 2.9.1 documentation recommends the new way of creating staticboxes - we should create all controls inside the staticbox as its children.
However, there's a problem with keyboard navigation when you have more than one staticbox in your dialog/panel. There is no way to move cursor between controls placed in dif... | Problem was finally solved in the pre-release version of wxWidgets 2.9.5.
More information can be found on the corresponding ticket page
I did answer to my own question, because there were no other answers. Maybe this will be useful for someone else in the future.
|
4,809,554 | 4,809,602 | expected constructor, destructor, or type conversion before * ( line 45) | subj on line 45
//Server.h
class Server : public QTcpServer
{
Q_OBJECT
public:
typedef QHash<int, Student*> Students;
...
Students* getStudents () const;
...
private:
Students _students;
};
//Server.cpp
void Server::setPort( quint16 port )
{
_port = port;
}
q... | Students is really a "nested type", and the compiler can't figure out what it refers to since it hasn't seen the Server:: context yet. You need:
Server::Students* Server::getStudents() const
|
4,809,868 | 4,810,068 | R-value inserts don't work for unordered_map | I'm using the latest available GCC build from repository. I decided to use it because some additional C++0x features. However now I stuck with something what supposes to work - I want to add new element to map via r-value. Simplified code, which demonstrates problem:
#include <tr1/unordered_map>
class X
{
public:
... | Your code looks correct to me except for your use of tr1. tr1-qualified stuff doesn't know about rvalue reference or move semantics.
I took your code, removed tr1 from the header and namespace qualifiers, and successfully compiled your code using g++-4.4 and libc++ (http://libcxx.llvm.org/). Try removing tr1.
|
4,809,950 | 4,810,355 | How can I profile pure dll? | I have project that creates dlls. These dlls are invoked from python later by special plugin system blue-sky. So in this project it's very hard to build executable file, but I need profiling. Are there any profilers that can work with pure dlls?
I've tried Intel Amplifier, Microsoft VS2008 profiler they don't work. I'... | If your dll is loaded by Python then you need to profile the Python process. With the Microsoft profiler as long as all the .pdb files are present it should resolve symbols within the dll. Another option is to create an executable that loads and calls the functions you're interested in and then profile said executabl... |
4,810,026 | 4,810,293 | Sending Protobuf Messages with boost::asio | I'm trying to hack a client together in C++ using Google's Protocol Buffers and boost::asio.
My problem is that I don't know how I can feed the protobuf message to asio.
What I have is this:
// set up *sock - works
PlayerInfo info;
info.set_name(name);
// other stuff
Now I know that the following is wrong, but I'll po... | I don't know much about Google's Protocol buffer, but try the following:
PlayerInfo info;
info.set_name(name);
// ...
boost::asio::streambuf b;
std::ostream os(&b);
info.SerializeToOstream(&os);
boost::asio::write(*sock, b);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.