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,145,236
4,145,441
Namespaces and class members
Consider: #ifndef __t__ENTITY_H #define __t__ENTITY_H #include "../graphics/animation.h" namespace t { namespace entity { namespace type { enum Enum { GFX = 0, SFX, PFX, AI, MAX }; } //template <class T> class Entity { public: Entity(unsigne...
You should try to avoid making headers include other headers unless they are necessary. In this case you can put in a forward declaration in the first header. namespace t { namespace graphics { class Animation; } // continue with definitions } There is a possibility that your headers are being include...
4,145,561
4,146,122
System tray context menu doesn't disappear
I create a notification icon with: notifyIcon.cbSize = sizeof(NOTIFYICONDATA); notifyIcon.hWnd = mainWnd; notifyIcon.uID = 100; notifyIcon.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE; notifyIcon.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_LOGO)); notifyIcon.dwState = NIS_SHAREDICON; notifyIcon.uVersion = NOTIFY...
Do not catch WM_RBUTTONDOWN but WM_RBUTTONUP. And of course do not handle both WM_RBUTTONUP and WM_CONTEXTMENU, since they will both get handled and you'd show the context menu twice for every right-click. Showing the menu twice would have the effect you describe: the menu shows up, but doesn't seem to disappear (becau...
4,145,575
4,146,044
transport stream & mpeg file format
I would like to convert a TS file to mpeg file. Is there any documents describing such process? I know the TS architecture, but I don't know mpeg's file architecture. Any info on this subject will highly appreciated. Thank you.
What you are probably wanting to do is convert from MPEG-TS (Transport Stream) to MPEG-PS (Program Stream). MPEG-PS is the format of a standard .mpg file as well as the format DVD video uses. You probably should get a hold on the standard which is ISO/IEC 13818-1. This standard contains all of the MPEG-TS and MPEG-...
4,145,595
4,145,678
why call operator new explicitly
I saw code like this: void *NewElts = operator new(NewCapacityInBytes); And matching call explicitly operator delete is used consequent later. Why do this instead of: void *NewElts = new char[NewCapacityInBytes]; Why explicit call to operator new and operator delete??
Explicitly calling operator new like that calls the global "raw" operator new. Global operator new returns a raw memory block without calling the object's constructor or any user-defined overloads of new. So basically, global operator new is similar to malloc from C. So: // Allocates space for a T, and calls T's cons...
4,145,605
4,145,722
std::vector needs to have dll-interface to be used by clients of class 'X<T> warning
I'm trying to make my library exportable as a DLL but I'm getting a lot of these warnings for one specific class that uses std::vector: template <typename T> class AGUI_CORE_DECLSPEC AguiEvent { typedef void (*AguiCallbackFptr)(T arg, AguiWidget* sender); std::vector<AguiCallbackFptr> events; public: void call(...
Exporting from a DLL is platform-specific. You will have to fix this for Windows (basically use declspec(dllexport/dllimport) on the instantiated class template) and encapsulate the required code in your Windows-specific preprocessor macro. My experience is that exporting STL classes from DLLs on Windows is fraught wit...
4,145,664
4,145,797
Efficiency when rearranging arrays in OpenGL
Imagine I have a vertex array and an index array. Suppose it is possible to rearrange the elements in the index array so that a single call glDrawElements with GL_TRIANGLE_STRIP draws the desired figure. Another possibility would be to call glDrawElements with GL_TRIANGLES but this would make the index array longer. Do...
There's no really performance differences between a call with GL_TRIANGLE_STRIP and GL_TRIANGLES. Now if you can rearrange your indices for maximizing post-transform vertex cache, you can have huge performance gains. I did so years ago for rendering large terrain patches and observed 10 to 15 times FPS speedups (using ...
4,145,915
4,146,005
A virtual member function is used if it is not pure?
C++03 3.2.2 ...An object or non-overloaded function is used if its name appears in a potentially-evaluated expression. A virtual member function is used if it is not pure... And then later in 3.2.3 we have: Every program shall contain exactly one definition of every non-inline function or object that is used in that pr...
The two clauses are not mutually exclusive. That a virtual function is used if it is not pure, does not mean that the converse holds. If a virtual function is pure it does not mean that it is necessarily not used. It may still be used "if its name appears in a potentially evaluated expression" such as in your example: ...
4,145,934
4,145,988
Using C++ headers (.h) vs headers plus implementation (.h + .cpp), what are the disadvantages?
As a novice C++ programmer I have always put my classes interface in .h files and implementation in .cpp files. However I have recently tried C# for a while and I really like its clean syntax and way to organize files, in particular there is no dinstinction between headers and implementation, you usually implement a cl...
There's a few ways that separating the two help in C++. Firstly, if you'd like to update a library without changing an interface then having the code in the C++ file means that you simply can update the library rather than the library plus the headers. Secondly it hides the implementation. That is, it forces people ...
4,145,957
4,146,031
Can you use a boost::shared_ptr as a key for a map?
I may need to rethink my overall design a bit more, but as it stands, it looks like I may want to do something like: class A; class B; std::map<boost::shared_ptr<const A>, B> APtrToBMap; I've tried this, and it does seem to work in a simple case (the compiler didn't complain, and simple tests seem to work). But I'm h...
The reference has this to say: template<class T, class U> bool operator<(shared_ptr<T> const & a, shared_ptr<U> const & b); // never throws Returns: an unspecified value such that operator< is a strict weak ordering as described in section 25.3 [lib.alg.sorting] of the C++ standard; under the equivalence relation d...
4,146,140
4,146,392
QSlider Value Changed Signal
I'm using a QSlider (v4.6) for input as well as to provide feedback to the user. For the feedback I will be calling the setValue method. I'm trying to find a signal that will fire only if the user modified the value. The valueChanged signal fires when the user changed the value as well as when I call setValue. sliderMo...
Good question, I checked the API and also couldn't find a signal that would be triggered only if value was modified by user. The workaround you proposed may be the only option, just keep in mind that you don't have to disconnect / connect all signals, just use QObject::blockSignals method: slider->blockSignals(true); s...
4,146,499
4,146,525
Why does a virtual function get hidden?
I have the following classes: class A { public: virtual void f() {} }; class B : public A{ public: void f(int x) {} }; If I say B *b = new B(); b->f(); the compiler says error C2660: 'B::f' : function does not take 0 arguments. Shouldn't the function in B overload it, since it is a virtual function? Do vir...
Assuming you intended B to derive from A: f(int) and f() are different signatures, hence different functions. You can override a virtual function with a function that has a compatible signature, which means either an identical signature, or one in which the return type is "more specific" (this is covariance). Otherwise...
4,147,372
4,147,521
XML Parsing results in Duplicates using libxml2
I'm using libxml2 to parse the following XML string: <?xml version=\"1.0\"?> <note> <to> <name>Tove</name> <name>Tovi</name> </to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> Formatted as a C-style string: "<?xml version=\"1.0\"...
The main problem I see in your code is that you're calling xmlNodeGetContent(). This is returning you the whole text inside the tag and its ending counterpart. When parsing with libxml2 you get some nodes whose content is complex, so you cannot rely on xmlNodeGetContent() to retrieve the content. You have to do the rec...
4,147,405
4,147,437
DeleteIPAddress and AddIpAddress Problem
i tried to write program adding ip address using this function DWORD AddIPAddress( __in IPAddr Address, __in IPMask IpMask, __in DWORD IfIndex, __out PULONG NTEContext, __out PULONG NTEInstance ); I have added it but how can I delete it. DeleteIPAddress takes NTEContext as Parameter how can i get it...
You can't do this. From MSDN: To use DeleteIPAddress, AddIPAddress must first be called to get the handle NTEContext. The previous procedure assumes that AddIPAddress has already been called somewhere in the code, and NTEContext has been saved and remains uncorrupted. The lifetime of the added address is...
4,147,639
4,147,678
Converting color bmp to grayscale bmp?
I am trying to convert a colored BMP file to gray-scale BMP. The input bmp is 24 bit and I am producing the same 24 bit bmp at the output, only this time in gray-scale. The code I am using is for(int x = 0; x < max; x++) { int lum; lum = (r[x]*0.30) + (g[x]*0.59) + (b[x]*0.11); r[x] = lum; g[x] = lum;...
These should really be unsigned char; if char happens to be signed on your platform, then this code won't do what you expect.
4,147,784
4,164,054
Adding signals to class that inherit from QGraphicsScene
I want to add a signal to a class that inherits from QGraphicsScene. signals: void update(std::vector< std::vector<int> > board); When I do this, Qt Creator warns me that I forgot the Q_OBJECT macro. But somewhere I read that since QGraphicsScene doesn't inherit from QObject, I shouldn't put it in my class definit...
Reposting as answer, as requested: Is update() your signal? did you try to implement the signal yourself? If yes, don't do that, signals are defined by moc.
4,147,944
4,148,583
Should the ARG_TYPE for a CArray be const & or not
What's the difference between these 2 lines CArray<MyClass, MyClass> MyArray CArray<MyClass, const MyClass & > MyArray
The MyClass is always copied to the array. But the first form copies it twice: the first time when its given as a parameter to the Add or SetAt function, the second time internally. With the second form you avoid the first copy.
4,147,967
4,148,008
Partially processing a file with the preprocessor
We have inherited a very convolved project (500kloc) with a lot of preprocessor conditional logic, most of which is no longer relevant, and I want to clean it up. Can I use the preprocessor¹ to expand only some of the conditional logic, and leave all other preprocessor macros, defines, and includes alone in the output?...
There is a tool called "unifdef" that will do what you want.
4,148,052
4,148,110
C++ function using a kind of bitwise: I'll get duplicated values?
this is my C++ function that uses a kind of bitwise: int genkey(const unsigned char a,const char b,const char c ) { int val=0; unsigned char *p= reinterpret_cast <unsigned char *>(&val); p[0]=a; char *q= reinterpret_cast <char *>(&val); q[1]=b; q[2]=c; return val; } I'm using that for gener...
Your code will give different results on different architectures. Maybe that doesn't matter, of course. This is a portable equivalent: return ((((int) a << 8) + b) << 8) + c; Or this: return ((((int) a * 256) + b) * 256) + c;
4,148,202
4,148,317
value-initialization of a const member reference
I am looking at code of the following form: class foo { public: foo() {} //... }; class bar { public: bar() : ref() {} private: const foo &ref; }; Is initializing a reference using a temporary in this way correct? I know that it is possible to initialize a const reference that's a local variable...
This code is ill-formed. You can't default initialize or value initialize a reference. If you actually had an expression inside of ref(), then yes, 12.2.5 would apply and the temporary would be destroyed when the constructor exits.
4,148,242
9,302,406
Is it possible to convert a C++0x lambda to a clang block?
I've wondered if it is possible to convert a C++0x lambda to a clang block. So far anything I've seen on it has involved the discussion between their differences. My primary reason for looking into this, is to make an eventual wrapper for libdispatch, and while I'm quite aware of dispatch_*_f functions, any information...
A patch enabling this conversion implicitly was just added to clang trunk.
4,148,341
4,148,429
Is this correct usage of C++ 'move' semantics?
Tonight I've been taking a look at some code I've been working on over the last few days, and began reading up on move semantics, specifically std::move. I have a few questions to ask you pros to ensure that I am going down the right path and not making any stupid assumptions! Firstly: 1) Originally, my code had a fun...
A reference is still a reference. In the same way you cannot return a reference to a local in C++03 (or you get UB), you can't in C++0x. You'll end up with a reference to a dead object; it just happens to be an rvalue reference. So this is wrong: std::vector<T>&& doSomething() const { std::vector<T> local; ret...
4,148,428
4,148,439
Template way of finding maximum allowable value
Possible Duplicate: C++ variable types limits I have a defined type that may not stay at what it is. I want to make use of the maximum value for that type as an undefined value but don't want to use something like, INT_MAX because I might later change the type to a long or something else entirely. I've seen a temp...
Use: std::numeric_limits<T>::max() It's in the header <limits>. See here: http://www.cplusplus.com/reference/std/limits/numeric_limits/
4,148,619
4,148,648
How to pass pointer and pointer to a function?
I implement a function that acts like getline( .. ). So my initial approach is: #include <cstdio> #include <cstdlib> #include <cstring> void getstr( char*& str, unsigned len ) { char c; size_t i = 0; while( true ) { c = getchar(); // get a character from keyboard if( '\n' == c || EOF == c )...
Your pointer crash is probably in the realloc *str = ( char* )realloc( str, len ) Should be *str = ( char* )realloc( *str, len ) As Steve points out, your code leaks the original if realloc fails, so maybe change it to something like: char* tmp = (char*) realloc(*str, len) if (tmp) { *str = tmp } else { // real...
4,148,638
4,149,589
How to move an item up and down in a wxListCtrl (wxwidgets)
This should be pretty easy but I'm having a heck of a time doing it. Basically I want to move a row in my wxListCtrl up or down. I posted this to wxwidgets forum and got the following code. m_list->Freeze(); wxListItem item; item.SetId(item_id); // the one which is selected m_list->GetItem(item); // Retrieve the it...
Is the list ordered? if it is auto ordering it may be ignoring the order you are trying to apply. From recollection the internal order was not necessarily sequential, you might have to get the index of the previous item and go one before it.
4,148,837
4,148,992
String from file C++ BorlandC 3.1
I'm trying to put the content of a file into a variable, but I'm having issues with BorlandC 3.1 . I've read the documentation for this on http://cplusplus.com/doc/tutorial/files/ but, I don't have getline in Borland... Can anyone point me to a way to get the string from the first line of the file into a variable ? Tha...
There is more than one getline. Use the <iostream> one since BC++ 3.1 does not come with the one provided by <string> (because it precedes STL by quite a few years if I remember correctly).
4,149,072
4,149,092
c++ access stuff out side the class
ok, lets say I have this: class A: { Public: int dd; } Ok, then I have this class: class B: { Public: void sss(){ ff=dd; } int ff; } Ok, the problem is that class B doesn't know what dd is. How can I make class B know it?
It's public: and not Public:. Because dd is part of A, you need an instance of A to access dd.
4,149,086
4,149,141
Python-style pickling for C++?
Does anyone know of a "language level" facility for pickling in C++? I don't want something like Boost serialization, or Google Protocol Buffers. Instead, something that could automatically serialize all the members of a class (with an option to exclude some members, either because they're not serializable, or else b...
I don't believe there's any way to do this in a language with no run-time introspection capabilities.
4,149,118
4,150,914
Exception handling doesn't work with Qt on Windows
I'm facing strange problem. Namely, Qt somehow turns off exception handling in my program. I can't catch any exception, and when I throw an exception application crashes. I'm using Qt 4.7.0 (32 bit) from Qt SDK v2010.05 on Windows 7 (64 bit), g++ (GCC) 4.5.1 from MinGW, NetBeans 6.9.1. But I also cheked this with g++ ...
I've reconfigured and recompiled Qt with flag -exceptions: D:\Qt\2010.05\qt>mingw32-make confclean && configure -exceptions && mingw32-make and now everything is ok! Thanks all for help, especially to Nick D! Anyway, it's very strange that I had Qt build without this flag. I had downloaded Qt SDK in binary form from o...
4,149,146
4,149,210
Why and when shouldn't I kill a thread?
I am writing a multithreaded socket server and I need to know for sure. Articles about threads say that I should wait for the thread to return, instead of killing it. In some cases though, the user's thread i want to kick/ban, will not be able to return properly (for example, I started to send a big block of data and s...
Killing a thread means stopping all execution exactly where it is a the moment. In particular, it will not execute any destructors. This means sockets and files won't be closed, dynamically-allocated memory will not be freed, mutexes and semaphores won't be released, etc. Killing a thread is almost guaranteed to cause ...
4,149,229
4,149,240
How to check (via the preprocessor) if a C source file is being compiled as C++ code
The question title should say it all, but here's an example of what sort of thing I'm looking for: #ifndef THE_IDENTIFIER_THAT_WOULD_INDICATE_BEING_COMPILED_AS_CPLUSPLUS /* * Example of something that would matter. */ typedef enum _bool bool; enum _bool { false, true }; #endif What is the identifier? It's bugging ...
#ifndef __cplusplus If I remember correctly.
4,149,334
4,149,845
How to make boost::asio::ip::tcp::acceptor block forever?
How would someone do that? It just blocks until the first connection attempt.
the boost::asio::ip::tcp::acceptor::accept method already blocks until a connection is attempted.
4,149,668
4,149,739
Is a DLL slower than a static link?
I made a GUI library for games. My test demo runs at 60 fps. When I run this demo with the static version of my library it takes 2-3% cpu in taskmanager. When I use the DLL version it uses around 13-15%. Is that normal? Is so, how could I optimize it? I already ask it to use /O2 for the most function inlining.
Do not start your performance timer until the DLL has had opportunity to execute its functionality one time. This gives it time to load into memory. Then start the timer and check performance. It should then basically match that of the static lib. Also keep in mind that the load-location of the DLL can greatly affec...
4,149,992
4,150,025
Storing ints as floats
Suppose I have an API that only allows me to store floats, or arrays of floats. However, I would like to be storing integer values here. I (roughly) understand that I am pretty okay with a straight cast up to around 2^23, but what if I want to go higher? Is there any way that I can take advantage of more of the 32 bits...
Questionable: In C, you can do the following, which is potentially unsafe (due to strict-aliasing rules): int i = XXX; float f; *(int *)&f = i; and which relies on the assumption that sizeof(int) == sizeof(float). Less questionable: Safer, but more longwinded, is the following: int i = XXX; float f; memcpy(&f, &i, siz...
4,149,993
4,153,251
What socket-based model should I use for many simultaneous connections?
I need to know what socket-based model is the best for servers with many simultaneous connections, exactly as in an MMORPG server. I've read about c10k, but what should I use, if for example my server would allow only 5000 clients at one time? Blocking sockets, threaded (one thread per client)? Non-blocking sockets, n...
Personally I'd suggest that you use an IOCP based design, but then I would say that as I have an IOCP based framework that I've used for years to develop high performance servers for clients. I recently put together some of my reasons for prefering IOCP to the other models available on windows and they're available her...
4,150,019
4,150,102
Implementing a shake event?
I'm making a gui API for games and one requested feature was a shake event. Essentially an event very similar to Windows 7's Aero Shake. When the mouse is down, if it is rapidly moved back and forth uni directionally, the event is fired. I'm just not sure what type of psedocode would go into this?
I might consider something like this: always create a vector for the direction the mouse travelled on its last move always keep a record of the immediate prior vector, as you gather the next vector (which means you always have two vectors to evaluate). do a dot-product of the two vectors, as each mouse input arrives. ...
4,150,064
4,150,076
what's the difference between including a parameter name in a function declaration and not including one?
I remember reading before about the significance (or lack thereof) between including a parameter name in a function declaration and not including one. But I can't remember what it was that I read or where I read it. for example, void do_something(int *); // No parameter name included, only type. vs... void do_somethi...
There is no difference, as far as the compiler is concerned. Adding meaningful parameter names is a helpful form of documentation, though.
4,150,218
4,150,226
Is there any overhead using this-> for accessing a member?
When accessing a member of some class, I can use e.g.: this->myVar = 10 or I can just write: myVar = 10 I like to use this-> because it explicitly declares that the variable is a member of this class, but does it cause any overhead in comparison to just using the variable name by itself? As an alternative I could ma...
There is no overhead. The compiler will generate the exact same code for both versions.
4,150,586
4,150,631
How to use regexp to perform a glob in C/C++ (Linux)
I need to match simple some simple glob patterns that include only * and ?. It occurred to me that I could transform the input pattern into a regexp - the only problem is I'm not familiar with regexp enough to know the replacements. Essentially, I need an implementation for: std::string getRexExpForGlob(const std::stri...
Depending on your OS, you may have <fnmatch> with int fnmatch(const char* pattern, const char* string, int flags). This allows glob patterns against arbitrary strings, and a few extra flags to allow flexibility beyond that needed for filename matching. Otherwise, glob's * and ? are equivalent to regexp .* and . respec...
4,150,649
4,150,796
Confused about usage of `std::istreambuf_iterator`
I've implemented a deserialization routine for an object using the << stream operator. The routine itself uses an istreambuf_iterator<char> to extract characters from the stream one by one, in order to construct the object. Ultimately, my goal is to be able to iterate over a stream using an istream_iterator<MyObject> ...
When you use istreambuf_iterator, you are manipulating the underlying streambuf object of the istream object. The streambuf object doesn't know anything about it's owner(the istream object), so calling functions on the streambuf object does not make changes to the istream object. That's why the flags in the istream o...
4,150,832
4,150,857
Pythonic way to rewrite the following C++ string processing code
Previous, I am having a C++ string processing code which is able to do this. input -> Hello 12 output-> Hello input -> Hello 12 World output-> Hello World input -> Hello12 World output-> Hello World input -> Hello12World output-> HelloWorld The following is the C++ code. std::string Utils::toStringWithoutNumerical(...
Edit: This reproduces more accurately what the C++ code does than the previous version. s = re.sub(r"\d+", "", s) s = re.sub(r"(\s)\s*", "\1", s) In particular, if the first whitespace in a run of several whitespaces is a tab, it will preserve the tab. Further Edit: To replace by a space anyway, this works: s = re.su...
4,150,966
4,153,135
shared QUndoStack among several QMainWindows?
Greetings all, In my application,user can open several QWindows which share the same data.(save Data ,multiple Views)I needed to use one shared QUndoStack between the windows. Undo/Redo works fine,but when any of a QWindow closed, Undo/Redo menu get disabled.I guess its because the stack get cleared. Any tips? Thanks ...
Depending on your reasons for sharing the undo stacks between the windows you may also consider using the QUndoGroup. Then you create separate stacks for each window, and group then with QUndoGroup. The undo/redo actions are created from the group, not from the stacks.
4,150,988
4,151,158
Need suggestion on choose library to parse XML file in C++
(I plan to use my VS2005) Assume that there is not .NET installed on my computer. For the app will run on some computers which there is no .NET environment. I just want to find a good lib on parsing XML in C++. I googled and found LibXML++, XmlLite, and Xerces-C++ XML Parser(Top result from google page). How do I decid...
Since I couldn't see it in any of the items Georg linked to (they largely seem focused on TinyXML, RapidXML, pugixml and Xerces) I'd add XMLLite is one I used with some success. It's very performance oriented and stream based. It's not necessarily the easiest to use however, but for pure performance considerations it...
4,151,065
4,151,339
3D Graphics Batching
A lot of sites/articles say 'batch! batch! batch!'. Can someone explain what 'batching' represents with respect to shaders? Namely, does changing textures changing arbitrary shader variables mean something can't be 'batched'?
The easiest way to summarize it is to try to make as few API calls as you can to draw what you need to draw. Using vertex arrays or VBOs (not even optional in modern APIs), texture atlases and avoiding the need for state changes all contribute to that. It's really amazing how many triangles a modern GPU can draw in t...
4,151,142
4,151,183
Pythonic way to create empty map of vector of vector of vector
I have the following C++ code std::map<std::string, std::vector<std::vector<std::vector<double> > > > details details["string"][index][index].push_back(123.5); May I know what is the Pythonic to declare an empty map of vector of vector of vector? :p I try to have self.details = {} self.details["string"][index][index]....
Probably the best way would be to use a dict for the outside container with strings for the keys mapping to an inner dictionary with tuples (the vector indices) mapping to doubles: d = {'abc': {(0,0,0): 1.2, (0,0,1): 1.3}} It's probably less efficient (less time-efficient at least, it's actually more space-efficient ...
4,151,203
4,151,278
Why is this c++ working? (variables with the same name)
Alright, I wanna know why this code is working, I just realized that I have two variables with the same name within the same scope. I'm using g++ (gcc 4.4). for(int k = 0 ; k < n ; k++) { while(true) { i = Tools::randomInt(0, n); bool exists = false; for(int k = ...
Alright, I wanna know why this code is working, I just realized that I have two variables with the same name within the same scope. You seem confused about scopes. They're not "within the same" scope... the for loop's k has it's own nested/inner scope. More importantly, to see why the language allows it, consider: ...
4,151,254
4,151,294
Where's g++'s VLA extension?
My question is related to this thread. Here is the code #include <stdio.h> int main(int argc, char *argv[printf("Hello, world!\n")]) {} I accidently saved it as a *.cpp file and tried to compile it with g++. But I got an error and a warning. error: expected ',' or '...' before 'argv' warning: second argument of 'in...
g++ allows (again, as an extension) VLAs. I think it just doesn't allow them in parameter lists. This compiles in g++ 4.4.1. #include <stdio.h> int main(int argc, char *argv[]) { char *array[printf("Hello, world!\n")]; }
4,151,287
4,151,303
c++ referencing class functions error: identifier is undefined
I am trying to call a function for my stack class. If I have all of the functions within the main file the project works, however, when called from the class it says the the Error: identifier "function name" is undefined. I think it is a simple syntax error, but i can't find it. main.cpp #include<iostream> #include <st...
At a cursory glance, this function: void emptystack(struct stack* s) { s->top=EMPTY; } Is missing the scope operator (::), so you probably intended to write it as: void mystack::emptystack(struct stack* s) { s->top=EMPTY; } I'm not sure if that's your problem though, since "I'm trying to call a function" is a...
4,151,340
4,151,416
Malfunctioning type-casting of string to unsigned int
I'm having a annoying problem with a C++ function that I wrote and whose purpose is to validate de user input. The function reads the user input, verifies if it's a number and, if so, if it is in the range [min, max]. The problem occurs when I invoke the template function with a unsigned type, like size_t, and the inpu...
In C++ arithmetic involving an unsigned type with n value bits, is guaranteed to be modulo 2^n. That means any result is wrapped back into the range 0 through 2^n-1, by adding or subtracting a suitable multiple of 2^n. This is so also in C. So you need to check the input for minus sign, or add some other check. By the ...
4,151,497
4,153,258
DirectX 10 HUD in C++
I'm attempting to make a custom HUD system in DirectX 10. My current method of attack is to simply use a tree of meshes to represent different levels of the menu. I believe that by disabling the Depth Test I can make a mesh which is pasted up above the rest of my 3d world in the background. To achieve this I've attempt...
Yeah you are barking up the right tree. Something to bear in mind though is that if your menu system is layered then you HAVE to draw back to front as the Z-buffer can't help you. This will mean quite a bit of overdraw. Another solution allows you to limit the amount of overdraw by using a Z-Buffer (and especially ...
4,151,504
14,990,896
Wrapping FILE* with custom std::ostream
I have a function which works with a std::ostream. I need to support using a C file handle (FILE*). Should I be creating my own subclass of std::ostream which delegates to a FILE*?
As Ben Voigt points out, you want to subclass streambuf. There are pages on the University of Southern California's website which have the documentation, header, and source for a GNU implementation of a streambuf subclass (stdiobuf) that wraps a FILE*. It has some dependencies on the library it is a part of (GroovX), b...
4,151,617
4,163,518
C#/C++ Capture local machine ip packet and drop it
I am working on a firewall project. So far I succeed to block packets by ip basis which is I done by windows filtering platform. But my customer does not want to block the whole ip. He wants to block specific url. So now I need to capture each packet and read it. So far I can do that by C# raw socket. But I dont know h...
Does this help you? http://www.osix.net/modules/article/?id=824 In this article the author reads packets in raw format and then sends them on. I think you can probably use this as a basis for what you want to do.
4,151,671
4,151,756
how to scan the system memory through program?
I just want to read the system memory, not the memory allocated for other processes, just free memory. I tried allocating huge memory using malloc: char *ptr; ptr = (char*)malloc((1024*1024*700)*sizeof(char)); I tried to print it, but it is printing the null character (i.e. nothing). printf("%c",ptr[i]); So I casted ...
Regarding: the system memory , not the memory allocated for other processes, just free memory On a modern operating system, this has no real meaning, as all memory is virtual. As caf has said you could try scanning /proc/mem (as root), but that would give you all physical memory (including physical memory that curren...
4,151,706
4,151,781
Can I build local http server?
I need to build a local fake http server. It will listen all my http request and will decide which packet will be dropped or forward or delayed. Can I do that ? If I can how can I do it ?
Can I do that ? Yes If I can how can I do it ? First, make a socket server: http://www.switchonthecode.com/tutorials/csharp-tutorial-simple-threaded-tcp-server Next, parse HTTP and respond to it (linked in HTTP/1.0 for simplicity): http://www.ietf.org/rfc/rfc1945.txt As for "dropped or delayed", a "web server" does...
4,151,746
4,154,281
Anyone know of a C++ or Python library that will divide an image into pieces of arbitrary shape?
I'm working on a project involving puzzles made out of user-supplied images. I have been very hard-pressed to find a library that will serve my purposes. I would like to write the program in either Python or C++. I have been considering using Qt (or PyQt) to do it, so if you know of a library that will work with Qt it ...
You can't expect to find a library for any specific task. In this case, you need image-processing library, which is able to: draw image region with transparent background. You have piece configuration, use it as a mask to cut out edges. save drawn image to some format. Qt graphics is totally able to do all that.
4,151,840
4,151,867
Why can't I read fstream's binary data with operator>>?
If I do something like the following: ifstream file; file.open("somefile", ios::binary); unsigned int data; file >> data; My stream will always set the failbit and the data will remain uninitialized. However, if I read a char or unsigned char instead, the stream is fine. perror() is telling me "result too large". ...
The iostream extraction operator (>>) attempts to interpret numerical strings separated by whitespace, not binary data. There are many different ways to encode an unsigned integer in binary form (e.g. a 32-bit 2's complement representation in little-endian byte order). That's why you must use the read/write functions t...
4,151,908
4,152,419
Enable a single warning in Visual Studio
Is there a compiler switch to enable a single warning in Visual Studio? The reason I ask is I want to enable warning C4265 which is off by default. My searching has only turned up ways to turn warnings off. Even Microsoft pages called How to: Enable or Disable Compiler Warnings still only mention disabling.
If you want to turn it on (or off) in the project setting, you have to go to: Configuration Properties -> C/C++ -> Command Line and then under Additional Options you can enter: /w3#### to set your warning to level 3, and thus enable it; or you can enter /wd#### to disable a warning. Current (2015,2017,2019,...) Visual...
4,152,018
4,152,130
Initialize global array of function pointers at either compile-time, or run-time before main()
I'm trying to initialize a global array of function pointers at compile-time, in either C or C++. Something like this: module.h typedef int16_t (*myfunc_t)(void); extern myfunc_array[]; module.cpp #include "module.h" int16_t myfunc_1(); int16_t myfunc_2(); ... int16_t myfunc_N(); // the ordering of functions is not ...
I was going to suggest this question is more about C, but on second thoughts, what you want is a global container of function pointers, and to register available functions into it. I believe this is called a Singleton (shudder). You could make myfunc_array a vector, or wrap up a C equivalent, and provide a function to ...
4,152,052
4,559,368
Is there an easy way to make gcc omit crtbegin.o/crtend.o?
Aside from using -nostdlib and linking crt1.o -lc -lgcc yourself, is there any easy way to prevent gcc from linking crtbegin[S].o and crtend[S].o? These files are not that large, but I'm playing around with making small binaries, and would like to remove the useless C++ support code that's not needed for C programs. (P...
gcc -wrapper sh,-c,'z= ; for i ; do [ "$z" ] || set -- ; z=1 ; case "$i" in *crtbegin*.o|*crtend*.o) ;; *) set -- "$@" "$i" ;; esac ; done ; exec "$0" "$@"'
4,152,186
4,152,228
Questions about call convention
I remember long ago, when I was using the Turbo C, I didn't need to care about the call convention of a function, every function I used or defined took the form of C call convention. But after I move to Windows platform, I found that there're so many call convention speicifiers such as: WINAPI, STDCALL, __cdecl... Is t...
No, its simply, or mostly, historical legacy with the Windows API. Most systems outside of Windows do not routinely use different calling conventions (exception: syscalls and kernel mode).
4,152,410
4,152,642
DLL exports 4 COM function but not COM object ?! I just don't understand!
I've been looking at DLLs in windows, and I saw many DLLs that have the 4 COM exported functions: DllCanUnloadNow DllGetClassObject DllRegisterServer DllUnregisterServer just for an example: c:\windows\system32\actxprxy.dll // <-- WINDOWS 7 !!! (I guess Vista as well) B - U - T when I am looking for COM objects (using ...
COM defines the vtables and calling parameters of the COM interface methods. However, the pointers to the method implementations are never exported using the DLL Export mechanism: these pointers to method implementations are stored on the vtable of the COM object that was created by the library. That is, without asking...
4,152,578
4,152,695
Should names representing template types be a single character?
we're defining some C++ coding style guidelines based on these guidelines. Number 8 says "Names representing template types should be a single uppercase letter." Explanation: "Common practice in the C++ development community. This makes template names stand out relative to all other names used." Is it really that commo...
I don't really agree with that naming convention. For me, template parameters representing a fully generic type make sense as a simple letter --this is a type T, I don't really care which. But if there is any requirements on the type, it makes sense to produce a name that identifies what the template argument is: templ...
4,152,599
4,152,628
The meaning of static in C++
I thought I was fairly good with C++, it turns out that I'm not. A previous question I asked: C++ const lvalue references had the following code in one of the answers: #include <iostream> using namespace std; int& GenX(bool reset) { static int* x = new int; *x = 100; if (reset) { delete x; ...
That's just what the memory manager decided to do. If you think about it, it makes a lot of sense: You just freed an int, then you ask for an int again... why shouldn't the memory manager give you back the int you just freed? More technically, what is probably happening when you delete is that the memory manager is app...
4,152,799
4,152,944
Does overriding a non-const virtual method hide a const overload?
Consider: #include <iostream> using namespace std; struct A { virtual void f() { cout << "A::f" << endl; } virtual void f() const { cout << "A::f const" << endl; } }; struct B : public A {}; struct C : public A { virtual void f() { cout << "C::f" << endl; } }; int main() { const B b; b.f(); // prin...
I will (once more) link this great article : First, [the compiler] looks in the immediate scope, in this case the scope of class C, and makes a list of all functions it can find that are named f (regardless of whether they're accessible or even take the right number of parameters). Only if it doesn't doe...
4,152,973
4,153,133
Detecting negative number
I have a code in which user has to pass > 0 number otherwise this code will throw. Using type of this arg as std::size_t doesn't work for the reason that negative numbers give large positive numbers. Is it good practice if I use signed type or are there other ways to enforce it? void f(std::size_t number) { //if -1 i...
A lot depends on what type of argument you imagine your clients trying to pass. If they're passing int, and that's clearly big enough to hold the range of values you're going to use, then there's no practical advantage to using std::size_t - it won't enforce anything, and the way the issue manifests as an apparently h...
4,152,976
4,153,098
Flexibility of template alias in C++0x
As I understand, template aliases in C++0x will allow us to do the following: template <typename T> using Dictionary = std::map< std::string, T >; Dictionary<int> ints; ints[ "one" ] = 1; ints[ "two" ] = 2; I have two questions: First, will we be able to do this (bind to any type, or just templates): template <typena...
The syntax is: template <typename Iter> using ValueType = typename std::iterator_traits<Iter>::value_type; as with your second one. Source: http://www2.research.att.com/~bs/C++0xFAQ.html#template-alias Their example is: template<int N> using int_exact = typename int_exact_traits<N>::type; // define alias for conv...
4,153,055
4,153,868
How to load JPG/PNG Textures in an SDL/OpenGL App under OSX
i am writing an SDL / OpenGL application that runs under OSX. I have to use existing code which uses the DevIL library for loading JPG and PNG textures. Unfortunately, this works very bad under OS X, so i decided not to use DevIL at all, and rewrite the respective parts of the application using another library. I want ...
Have a look at the SDL_image library. It offers functions like IMG_LoadPNG that load your picture "as an" SDL_Surface. Since you already work with SDL this should fit quite well in your program. Sample taken from the SDL_image documentation: // Load sample.png into image SDL_Surface* image = IMG_Load("sample.png"); if ...
4,153,091
4,153,292
sqlite: check reader/writer lock
I have 2 processes which both access an sqlite3 database. While reading is not a problem in sqlite, only one process can write to the database. According to the faq: http://www.sqlite.org/faq.html#q5 sqlite uses reader/writer locks. How do i check if the database is locked for writing by another process, both from pyt...
When SQLite tries to access a locked database, it's default behaviour is to return SQLITE_BUSY. The documentation describes ways to add custom handling to this event: http://www.sqlite.org/faq.html#q5. I understand from the documentation that any function you call that tries to write to this locked database will simpl...
4,153,110
4,153,123
How do I use for_each to output to cout?
Is there a more straight-forward way to do this? for_each(v_Numbers.begin(), v_Numbers.end(), bind1st(operator<<, cout)); Without an explicit for loop, if possible. EDIT: How to do this for std::cin with a std::vector if possible? (How to read n elements only)?
You could achieve this using std::copy into a std::ostream_iterator: std::vector<int> v_Numbers; // suppose this is the type // put numbers in std::copy(v_Numbers.begin(), v_Numbers.end(), std::ostream_iterator<int>(std::cout)); It would be even nicer if you add some suffix: std::copy(v_Numbers.begin(), v_Nu...
4,153,124
4,153,145
Need for a pointer to pointer
Possible Duplicate: How do pointer to pointers work in C? Hi All, I have very basic question : What is the use of double pointers in C or C++ ? Can somebody explain me that with some examples, please. Thanks, Sen
If you want to change what the original pointer points to in a function call you need a **. This is because when you pass a pointer you are passing a copy of a pointer, i.e., if you modify what the pointer points to inside of a function (i.e., changing the value of the pointer itself) it is reflected in the copy but n...
4,153,140
4,159,382
Synchronizing embedded Python in multi-threaded program
Here is the example of using Python interpreter in multi-threaded program: #include <python.h> #include <boost/thread.hpp> void f(const char* code) { static volatile auto counter = 0; for(; counter < 20; ++counter) { auto state = PyGILState_Ensure(); PyRun_SimpleString(code); PyGILS...
with statement has issue in Python 3.1, but it was fixed in Python 3.2 and Python 2.7. So the right solution is to use the threading module for synchronization. To avoid such issues, one shouldn't use multi-threaded code which uses temporary variables in globals dictionary, or use different globals dictionaries for eac...
4,153,165
4,153,182
Does push_back() always increase a vector's size?
I have a piece of code which creates a std::vector<T> with a known size: std::vector<T> vectorOfTs(n); Does calling push_back increase the size to n+1? vectorOfTs.push_back(T());
Yes; note that vector<T>.capacity() is different from vector<T>.size(). The latter denotes the number of elements currently in the vector while the former represents the number of items that fit in the space currently allocated for the vector's internal buffer.
4,153,236
4,153,280
Does BlackBerry enterprise server support COM?
Do BlackBerry enterprise server APIs expose any COM interface to write applications in C++?
No. The Blackberry Administration API is invoked via SOAP. You can use a C++ SOAP proxy generator to interface with the BAAPI from C++.
4,153,398
4,153,495
how to drag graphics rectangle through mouse left key in c or c++
How to move graphics rectangle using mouse in c or c++. This is some what similar to movable message box in windows. how i do like this in c/c++ graphics application? THANKS in Advance...
Pick your platform... Windows, Mac, Linux or the others. Pick an API... GDI, DirectX, OpenGL On windows, mouse coords are found using GetCurPos() in the winAPI. In openGl, drawing a rectangle involves glBegin(). GlEnd() and the calls that go in the middle. In GDI, Rectangle() should do the trick.
4,153,527
4,154,213
Explicit copy constructor behavior and practical uses
A recent question got me wondering about explicit copy constructors. Here is a sample code that I tried compiling under Visual Studio 2005 : struct A { A() {} explicit A(const A &) {} }; // #1 > Compilation error (expected behavior) A retByValue() { return A(); } // #2 > Compiles just fine, but why ? void...
I believe the relevant sections of C++03 are §12.3.1 2: An explicit constructor constructs objects just like non-explicit constructors, but does so only where the direct-initialization syntax (8.5) or where casts (5.2.9, 5.4) are explicitly used. A default constructor may be an explicit constructor; such a constructor...
4,153,824
4,156,459
How to store and retrieve graphics before message box(Graphics rectangle) in c or c++
Like in windows application when some event occurs, message box is appeared, click OK then previous window appears. Is it possible with c, c++ graphics application that display message box when some event occurs? It should show message box(rectangle graphic) and when pressed OK, it will disappear and displays previous ...
(In addition to previous answer) Another common way is to redraw all regions which lied under message box using the way they drawn previously.
4,153,846
4,153,898
How to create a functor that will read next value from input stream?
Something like this : std::bind1st(std::mem_fun(&istream::get ??), cin). This does not seem to work for me. EDIT: Use : vector<int> vNumbers; generate_n(back_inserter(vNumbers), iNumCount, functor);
I don't think the standard binding functions let you define nullary functions. bind1st binds to the first argument of a binary function and returns a unary function that passes its parameter as the second parameter of the bound function. You can go outside the standard library, however, and use Boost.Bind: boost::bind(...
4,153,852
4,153,899
Assembly ADC (Add with carry) to C++
There is an x86 assembly instruction ADC. I've found this means "Add with carry". What does this mean/do? How would one implement the behavior of this instruction in C++? INFO: Compiled on Windows. I'm using a 32-bit Windows Installation. My processor is Core 2 Duo from Intel.
ADC is the same as ADD but adds an extra 1 if processor's carry flag is set.
4,153,913
4,164,751
error: expected primary-expression before X token
Can you explain what the title error usually means? I get it sometimes and I always eventually manage to fix it by accident, but I still don't have a clue what it means. Here's an example from my current error: Lca<RankVec, VertexVec> lca(graphList[0], dset, ss&); error: expected primary-expression before ')' token
The & symbol is used as a bitwise AND operator. I.e. 0x3 & 0x5 == 0x1. In this form, it's an infix operator between two expressions. From what you've told us, we now know that ss is an expression. Therefore, the compiler thinks ss & is the start of a bitwise AND expression, and it expects the right-hand side (which it ...
4,153,929
4,154,013
Segmentation Fault when accessing (non-pointer) member variable in Qt class instance
I am having some issues with a segmentation fault being caused by access to a member variable in a Qt application. My experience of segmentation faults have shown them generally to be a result of accessing a memory location that is out of bounds. However, I'm struggling to figure out why this would be the case in m...
While this is a wild guess, there's a possibility that you're calling that method on a null object. Note that: unsigned int existingZoom = m_Zoom; is equivalent to unsigned int existingZoom = this->m_Zoom; If you called this method from a null pointer: someUninitializedPtr->ZoomIn(); then this is probably the result...
4,154,072
4,154,471
how to move scrollbars simultaneously in qt
I have two view whose perspectives are xy and xz. These views have their own scrollbars and x side of these views are equal. When i move scroll bar of x sides , i want x scrollbars to move simultaneously. Class of views is QGraphicsView and scrollbars of these views are their own scrollbar. How can i make it? Any hel...
If I understand you correctly, you could simply do the following (if you use QScrollBar as your scrollbar) connect(firstScrollbar, SIGNAL(valueChanged(int)), secondScrollbar, SLOT(setValue(int))); connect(secondScrollbar, SIGNAL(valueChanged(int)), firstScrollbar, SLOT(setValue(int))); Hope this answers your question ...
4,154,339
4,157,334
How to generate circular matrix?
I want to generate a circular matrix in C or C++. How can I generate the matrix below, for n = 3? 1 2 3 8 9 4 7 6 5
In a "circular" matrix, the "middle" of it is circular too, except that it doesn't start with 1. So run round the perimeter and recurse. void cmat_step( int** M, int a, int i, int j, int dim) { int k; /* fill perimeter */ for( k=0; k<dim; ++k) M[i][j+k] = a++; for( k=1; k<dim; ++k) ...
4,154,604
4,395,134
Setting up ImageMagick on Qt with Mac. LIBS and INCLUDEPATH
I would like to build a cross platform application that will make use of imagemagick library in order to perform various actions to selected images. I have installed the library from my terminal and as I can see, Lib files are located at: /opt/local/lib and include files at: /opt/local/include/ImageMagick I tried to op...
Exactly Kamil Klimek @This error simply says, that you application can't find libMagick++.4.dylib at location /usr/local/lib/ check if library is there The file was missing. I copied and everything worked! Thank you so much
4,155,088
4,155,227
How to prevent deletion of pointers managed by a QSharedPointer
I have some intermittent segmentation faults in a Qt application. I think the problem is related to our (bad) use of QSharedPointer. The Qt Documentation states : QSharedPointer::QSharedPointer ( T * ptr ) : Creates a QSharedPointer that points to ptr. The pointer ptr becomes managed by this QSharedPointer and mus...
The normal pattern is to put the new statement inside the smart pointer's constructor, like this: QSharedPointer<Obj> p (new Obj(2)); That way you never have a reference to the naked pointer itself. If you refactor your code so that all new operator are in lines like these, all your problems will be solved.
4,155,282
4,155,408
Moving the mouse pointer in C++ fails on Linux
I'm using the following code to hide and show the mouse cursor: XDefineCursor( m_display, m_window, show ? None : m_hiddenCursor ); XFlush( m_display ); That works fine. However, when I run this: XWarpPointer( m_display, None, m_window, 0, 0, 0, 0, x, y ); XFlush( m_display ); The mouse doesn't move at all. Simply...
It's been a while, but doesn't XWarpPointer make a relative move of the cursor using the passed offsets? It looks like the passed offsets are (0,0) meaning that the cursor wouldn't move. I think the routine you want to use is XMovePointer. Share and enjoy.
4,155,450
4,155,513
ADL with typedefs from another namespace
I have something like this: #include <iostream> namespace N { typedef std::pair<int, double> MyPair; std::ostream& operator << (std::ostream& o, MyPair const & mypair) { /// } } int main() { N::MyPair pr; std::cout << pr; } This naturally doesn't work, because ADL won't find operator<< becau...
You could create your own type in namespace N, possibly inheriting from std::pair. You could add "using namespace N;" inside main. The former is more likely to be useful. Because the type is defined in another namespace and cannot be defined in two. Example: namespace N { struct MyPair : std::pair<int, double> { ...
4,155,481
4,162,954
OpenCV RGB Value Detection?
So im basically either looking for code, or even a sample to detect RGB values (maybe even with hue) to be used with OpenCV Ideally you would be able to show an object in front of your webcam, then click on it with it outputting the RGB values. Im trying to do this because im trying to find a decent color threshold to ...
Here's an article that explains the tracking process: http://aishack.in/tutorials/tracking-colored-objects-in-opencv/
4,155,582
4,155,627
qt write to end file
I need to write some text at the end of txt file. But i can only rewrite all file. How can i add text to the end of file? Thank you.
Are you sure you are opening the file in the append mode? QIODevice::Append
4,155,730
4,155,978
Creating string with libxml2 (c++)
My problem is that I want to create xml tree and get a simple string object (or even char*). And I can't save xml to file. So in the input I have xmlDocPtr with complete xml tree and want to get string containing xml but without using files. Thx for attention.
Use xmlDocDumpMemory or any of its cousins. Usage: void xml_to_string(xmlDocPtr doc, std::string &out) { xmlChar *s; int size; xmlDocDumpMemory(doc, &s, &size); if (s == NULL) throw std::bad_alloc(); try { out = (char *)s; } catch (...) { xmlFree(s); throw; } ...
4,155,831
4,155,884
How to understand the output?
int main(int argc, char** argv) { try { char *p2 = NULL; cout << "p2:" << strlen(p2) <<endl; cout << "mark"; } catch (...) { cout << "caught exception" <<endl; } return 0; } The output is p2:,so neither cout << "mark"; nor cout <<...
In C++, dereferencing a NULL pointer causes undefined behavior, which means anything could happen: the computer could blow up, the function could return an arbitrary value, the program could be killed by an operating system exception (which, unlike a C++ expression, cannot be caught with try-catch). In short, don't do ...
4,155,833
4,156,726
Dangers of converting delegates to function pointers
Suppose you have a managed class that converts a delegate member to a native function pointer and hands it to native code. Assume that the class/delegate stays in scope and does not change for the lifetime of the native code (so that will not be obviously destroyed by the GC). What other problems should one be aware ...
It seems that it's possible to pin the memory location of the delegate/function, but this obstructs a major advantage of the .NET GC: compacting. Once a GC sweep is done, every object is relocated in memory to be contiguous. This makes both access and allocation faster that it would be if the heap were fragmented. If ...
4,155,845
4,156,001
Vector of Structures
I have some code given to me by another person in which we have a structure struct Pair { string s1; string s2; bool equivalent; }; Then he sets up a vector of these structs hard coded std::vector<Pair> PairID; staticdata() { PairID={{"string","string2",true}, {"string","string3",true}, ...
Your code is not legal C++. It is legal C++0x but there have been many changes to the language. So if you want to compile this code as C++ code, you'll need to change it. PigBen's solution is one way, the problem with it being the temporary data could be constructed & destroyed many times, or live for a long time. He...
4,155,847
4,159,360
Choosing between set<int> vs. vector<bool> vs. vector<boolean_t> to use as a bitmap (bitset / bit array)
Given a range of indexes (identifiers), where I want to map each index to a boolean value, that is: // interface pseudocode interface bitmap { bool identifier_is_set(unsigned int id_idx) const; void set_identifier(unsigned int id_idx, bool val) const; }; so that I can set and query for each ID (index) if it is set...
Without knowing the platform you are running this code on and your access patterns, it's hard to say whether vector<bool> will be faster than vector<char> (or vector<int>) or even set<int> or unordered_set<int>. For example, if you have an extremely sparse array, a linear search of a vector<int> that just contains the...
4,155,911
4,155,976
openGL sphere that is both wireframe and solid
I manually drew a sphere, at last :) I want my sphere to be red, but the outlines to be green: In order to achieve this I did the following. I drew a solid sphere in red, and then I drew the same sphere, but wireframe and green. When I turned DEPTH_TEST on, I got some weird behavior, like this: And in order to avoid t...
You're not doing something awfully bad, but if you need to offset geometry to avoid Z-fighting you might want to have a look at glPolygonOffset.
4,156,029
4,165,812
Parametized class creation with assert of parameter presence. Use factory?
I spend about 2 hours reading a lot of factory related topics and I still am not sure if this would be the right approach. Here is the thing: I have an Enemy class that has contains member variables like name_ and health_. I want to create instances of it with different values of these member variables and my first app...
There are essentially three options: Everybody is free to specify the initial name and health of an Enemy, which accepts both as parameters in its (public) constructor. The Enemy class constructor maps an 'Enemy ID' to the appropriate values of the properties. The problems in this approach come when you need to verify...
4,156,272
4,159,391
Boost C++ http post get services: How to make more than one run on same port?
So I am trying to create some service model for my app. I need it to be in C++, based on free libs like boost ffmpeg and so on. So I found boost services. I wonder will be capable of making 2 or more apps (each of my services is stand alone app/process) share same port and just have difrent url endings. Like http://adr...
If I was you I'd be looking at boost::asio (see the http server in the examples) or for something a bit higher level, the Pion framework (which uses asio) or maybe cpp-netlib. It should normally suffice to have a single server process providing mixed functionality on one port in response to parsed URLs.
4,156,288
4,156,361
How to keep track of thousands of painted shapes in Windows C++ CLR
I want to have potentially thousands of painted shapes on a panel and be able to identify them when I mouseover or click on them. What is the best way to do this? My guess is I have to have some shape regions in a table. And have some clever way of looking up matches when I hover across page. Seems computationally inte...
When you paint into your panel, also paint the shapes into a bitmap that isn't displayed and use the shape ID as the color. When you need to look up a shape, just check the pixel at the appropriate coordinates in your bitmap. Make sure you turn off any line smoothing or antialiasing when drawing the bitmap!
4,156,367
4,156,498
What am I doing wrong with my bind function here?
I wrote my bind function which returns a nullary functor because I don't have boost. Though this code compiles fine, it does not behave as I expected. When I input 2 as the number of numbers and try to enter them, the program terminates the first time I hit return. And, when I debug, it segfaults inside mem_fun_t::oper...
istream::get is not the right method to use, as it reads characters, not ints. You'd need to use operator>> (and selecting the right overload is very verbose), or just write a different functor: template<class T> struct Extract { istream &stream; Extract(istream &stream) : stream (stream) {} T operator()() { ...
4,156,473
4,298,991
Qt on Mac: add an existing UI file without rebuilding the whole project
I have a Qt project in XCode on Mac. I want to add an existing .UI file to it. When I do that by listing in the .pri file, the XCode project itself is rebuilt by qmake, and all my post-qmake settings are lost. Is there a way to insert a UI file without listing in the .pri? It's doable in a very straightforward way on V...
There are two custom steps in the target - both call make over files in the project bundle (xcodeproj). The first one invokes qmake. The second invokes the Qt proprocessors - uic, moc. So the answer is - comment out or delete the first step, modify the makefile of the second one by hand. Add generated files (once they'...
4,156,474
4,156,593
How can I programmatically get thread counts for a Windows process?
I want to count native threads of the current Windows process via C/C++. I see there's a related question with a .NET answer, but I can't use that solution. I suspect that there may be a solution via PdhOpenQuery/PdhCollectQueryData but I haven't explored that direction yet, and I'm hoping there's an easier approach....
EDIT the second: Your text says "current process". If that is really the case, you could implement a small DLL whose DllMain maintains an active thread counter using InterlockedDecrement (on DLL_THREAD_DETACH) and InterlockedIncrement (on DLL_THREAD_ATTACH). You would have to make sure your process loads up this DLL e...
4,156,538
4,159,130
How can std::bitset be faster than std::vector<bool>?
According to this answer the poster expects a std::bitset of size 100k bits to be faster than a std::vector<bool> when querying individual bits. How can this be possible? How could they even differ significantly in their implementation, if std::bitset apparently allows for arbitrary sizes just like std::vector?
Measurements on Visual Studio 2010 show that std::bitset is not generally faster than std::vector<bool>. What the exact reason for this is I cannot say -- only that bitset is implemented significantly different from the std::vector full specialization. std::bitset stores it's full content in the object via a template<s...