question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
3,009,824
3,010,033
Void in main and keeping Dos program from dying
Possible Duplicate: Difference between void main and int main? Alright, so I'm using bloodshed complier, first thing I should note is I'm using a 2001 edition C++ for the absolute beginner, was there any changes to C++ since 2001 that would effect the validity of this book? I ask because I know php has php5 and now...
What there have been since 2001 are changes to C++ compilers, which on the whole are much pickier about how standards-conformant your C++ must be before they accept it. For example, gcc has gone from 2.95 or so all the way to 4.4.2. Earlier compilers may have let you slide with this form of main, as they would several ...
3,009,911
3,010,026
operator overloading and inheritance
I was given the following code: class FibHeapNode { //... // These all have trivial implementation virtual void operator =(FibHeapNode& RHS); virtual int operator ==(FibHeapNode& RHS); virtual int operator <(FibHeapNode& RHS); }; class Event : public FibHeapNode { // These have nontri...
You must be a bit confused about dynamic dispatch. It is often said that "dynamic dispatch occurs only when you make a call through a pointer or through a reference". Formally speaking, this statement is totally bogus and misleading. Dynamic dispatch in C++ happens always when you call a virtual function, with one and...
3,010,048
3,010,074
Posix equivalent of LocalAlloc(LMEM_ZEROINIT, size)
I have code which works on windows, that calls LocalAlloc as follows: LocalAlloc(LMEM_ZEROINIT, size) I need the equivalent malloc or calloc call to get this to work on Unix systems, through Mono. Simple answer?
From what I understand it just allocs zeroed memory, so a calloc(1, size) should suffice to allocate size zeroed bytes.
3,010,160
3,010,264
C++: Assign L"" string to WCHAR[]?
I have a WCHAR[]: WCHAR foo[200]; I want to copy values into it: if (condition) { foo = L"bar"; } else { foo = L"odp"; } What is the best way to do this?
Depending on exactly what you need to do, you could change the type of foo: const WCHAR *foo; if (condition) { foo = L"bar"; } else { foo = L"odp"; } This is fine if don't need to append any more data to foo.
3,010,201
3,010,242
Should I use C(99) booleans ? ( also c++ booleans in c++ ?)
I haven't done much c programming but when I do when I need a false I put 0 when I want true I put 1, (ex. while(1)), in other cases I use things like "while(ptr)" or "if(x)". Should I try using C99 booleans, should I recommend them to others if I'm helping people new to programming learn c basics(thinking of cs 1?? ...
In C++ there is no reason to not use it. In C, i only use int for this task, without any #define or something like that. Variable-names like isDefinition are clear enough to indicate what's going on, in my opinion. Of course, there is nothing wrong with defining your own bool or using the ones of <stdbool.h>.
3,010,305
3,010,871
Programmatically selecting file in explorer
In my application I can programmatically open explorer and select a file using the following code: void BrowseToFile(LPCTSTR filename) { CString strArgs; strArgs = _T("/select,\""); strArgs += filename; strArgs += _T("\""); ShellExecute(0, _T("open"), _T("explorer.exe"), strArgs, 0, SW_NORMAL); }...
Found the answer to my question. I need to use the shell function SHOpenFolderAndSelectItems. Here is the code for the function if anybody is ever interested: void BrowseToFile(LPCTSTR filename) { ITEMIDLIST *pidl = ILCreateFromPath(filename); if(pidl) { SHOpenFolderAndSelectItems(pidl,0,0,0); I...
3,010,339
3,010,366
C++: Cannot convert from foo& to foo*
I have a method: odp(foo& bar); I'm trying to call it: foo baz; odp(&baz); I get a compiler error: error C2664: "odp" cannot convert parameter 1 from 'foo *' to 'foo &' What am I doing wrong? Aren't I passing in a reference to baz? UPDATE: Perhaps I have a misconception about the relationship between pointers and re...
When you apply the unary & operator to an object, you get a pointer to that object, not a reference. You need a reference in this case. In order to initialize a reference parameter, you don't need to apply any operators at all: an lvalue object can immediately be used by itself to initialize a reference of the appropri...
3,010,347
3,050,828
C++ Builder and Excel Automation, where to get started?
I want to dynamically create and populate an excel spreadsheet with C++ builder 2009, but I'm not entirely sure how to go about it. Searching the web, I've narrowed it down to using OLE Automation. Moreover, I'm looking for a document or programming tutorial that can get me started. Is there a simple programming tutori...
To open an excel spreadsheet: Variant excelApp = Unassigned; //EOleSysError is thrown if GetActiveObject does not succeed. i.e //if Excel is not currently open. try { excelApp = Variant::GetActiveObject("Excel.Application"); } catch(EOleSysError& e) { excelApp = Variant::CreateObject("Excel.Application"); //op...
3,010,483
3,010,601
Trouble with wstringstream
I have a wstringstream: wstringstream sstream; AlterSstream(sstream); wstringstream bar_stream; bar_stream << sstream; bar_stream << "foo"; MessageBoxW( NULL, bar_stream.str().c_str(), L"subject", MB_OK ); This outputs a long string that looks nothing like what I put in it in AlterSstream(): 00000000002CEC5...
There is no overload to copy from stream to stream. You need to change the line: bar_stream << sstream; to: bar_stream << sstream.str();
3,010,550
3,010,908
Hardcoding the resources in application
I have some code which shows a simple dialog box and handles user action (written using plain WinAPI). // Display dialog and handle user action LRESULT choice = DialogBoxParam(NULL, MAKEINTRESOURCE(AP_IDD_DIALOG), NULL, (DLGPROC)DialogCallback, NULL); Is there any way to hardcode the resource file dialog.rc, which is...
I'm surprised I couldn't find an existing app to do this sort of thing, enough hits on google with people trying to do this. Ok, so the DLGTEMPLATE is a variable length blob of data, normally you let the dialog function pull it from the resource bundle for you, but instead you want to store it in your program. You need...
3,010,791
3,010,982
Mutability design patterns in Objective C and C++
Having recently done some development for iPhone, I've come to notice an interesting design pattern used a lot in the iPhone SDK, regarding object mutability. It seems the typical approach there is to define an immutable class NSFoo, and then derive from it a mutable descendant NSMutableFoo. Generally, the NSFoo class ...
Objective-C is too dynamic. In C++ const-qualification is enforced at compile-time, and any violations of const-qualification at runtime (such as modifying a const-qualified object through a non-const-qualified pointer) is undefined behaviour. It is partly the same as the reason why there are no private methods in Obje...
3,010,913
3,010,924
Is there an existing template for a new C++ Open Source project
I want to start a new C++ (Qt) Open Source project and I'm wondering if there is an existing template somewhere for files usually found in an Open Source project but that are not purely source code (README, LICENSE, CHANGELOG, etc.) I could probably find a popular Open Source project for inspiration but if there is so...
One place to look might be the implementation of the GNU Hello program. It includes all the standard template files expected by the GNU coding guidelines. You may, of course, choose to follow another set of guidelines than GNU's.
3,011,005
3,011,009
What is operator<< <> in C++?
I have seen this in a few places, and to confirm I wasn't crazy, I looked for other examples. Apparently this can come in other flavors as well, eg operator+ <>. However, nothing I have seen anywhere mentions what it is, so I thought I'd ask. It's not the easiest thing to google operator<< <>( :-)
<> after a function name (including an operator, like operator<<) in a declaration indicates that it is a function template specialization. For example, with an ordinary function template: template <typename T> void f(T x) { } template<> void f<>(int x) { } // specialization for T = int (note that the angle brackets...
3,011,036
3,011,051
need to get computer speaking to a cell phone
i have this super manual: http://www.arib.or.jp/IMT-2000/V710Dec08/5_Appendix/R99/27/27005-320.pdf i dont understand whether it is for every phone or just a certain subset i would like to know what i need to get started to have my computer speak to the phone i am ready to write in c#, c++, or what ever they need has an...
basically you need a cable, and most often you talk to it through a serial port which is basically what something like http://www.microsoft.com/downloads/details.aspx?familyid=06a4f997-7f69-4891-8929-37b9041924a2&displaylang=en does
3,011,253
3,011,897
Why is my slot not being called?
I have this class: class CustomEdit : public QTextEdit { Q_GADGET public: CustomEdit(QWidget* parent); public slots: void onTextChanged (); }; CustomEdit::CustomEdit(QWidget* parent) : QTextEdit(parent) { connect( this, SIGNAL(textChanged()), this, SLOT(onTextChanged())); } void CustomEdit...
All classes that contain signals or slots must mention Q_OBJECT at the top of their declaration. They must also derive (directly or indirectly) from QObject. Try using Q_OBJECT
3,011,271
3,012,858
How to get width and height of directshow webcam video stream
I found a bit of code that gets me access to the raw pixel data from my webcam. However I need to know the image width, height, pixel format and preferably the data stride(pitch, memory padding or whatever you want to call it) if its ever gonna be something other than the width * bytes per pixel #include <windows.h> #...
That's really ugly. Please don't do that. Insert a pass-through filter like the sample grabber instead (as I replied to your other post on the same topic). Connecting the sample grabber to the null renderer gets you the bits in a clean, safe way without rendering the image. To get the stride, you need to get the media ...
3,011,274
3,011,307
Antialiasing algorithm?
I have textures that i'm creating and would like to antialias them. I have access to each pixel's color, given this how could I antialias the entire texture? Thanks
The basic method for anti-aliasing is: for a pixel P, sample the pixels around it. P's new color is the average of its original color with those of the samples. You might sample more or less pixels, change the size of the area around the pixel to sample, or randomly choose which pixels to sample. As others have said, ...
3,011,291
3,011,398
Replacement compiler for Qt Creator?
I like Qt Creator as an IDE, but the built-in compiler is slower than dirt. Can I replace it, and if so, with what? Developing on Windows but targeting multiple Mac as well.
By default on Windows the compiler is mingw, a port of GCC. Qt also contains support for the Visual Studio compilers, which you can switch to. The only full-fledged C++ compiler on Macintosh is GCC. C++, especially with template heavy code, is slow to compile. There is no avoiding this. In my experience, Visual Studio ...
3,011,345
3,011,551
C++ online Role Playing Game (RPG)
So I've been learning C++ and SDL to make some basic 2d games. I want to create a game sort of like World of Warcraft but a 2D version. I want it to be on-line and use a database or something to start data like amount of Gold, HP, etc. I was wondering though, if I do this in SDL, would it still work on-line or would th...
No offense, but an RPG is definately the last thing a new programmer should attempt to create. They are the most time, resource, and skill intensive style of game one could possibly try to create. I speak from experience here and can say that RPGs are huge time sinks, even for experienced game studios. At best, you ...
3,011,409
3,013,086
Sparse constrained linear least-squares solver
This great SO answer points to a good sparse solver for Ax=b, but I've got constraints on x such that each element in x is >=0 an <=N. Also, A is huge (around 2e6x2e6) but very sparse with <=4 elements per row. Any ideas/recommendations? I'm looking for something like MATLAB's lsqlin but with huge sparse matrices. I'm...
You are trying to solve least squares with box constraints. Standard sparse least squares algorithms include LSQR and more recently, LSMR. These only require you to apply matrix-vector products. To add in the constraints, realize that if you are in the interior of the box (none of the constraints are "active"), then yo...
3,011,412
3,011,467
Command prompt print dialog command
Is there any way a C++ commandline program on Windows can produce a graphical GUI print dialog for printing to a printer, just like usual GUI programs? I've combed through this webpage and it seems there are only commands that print files in the background to a pre-determined printer.
Command-line applications in Windows still have full access to everything that GUI-mode applications do (the only difference is they start out with a console, whereas GUI-mode applications do not). So you can still call all of the regular printing functions from GDI.
3,011,421
3,011,435
Qt 101: Why can't I use this class?
I have experience with C++ but I've never really used Qt before. I'm trying to connect to a SQLite database, so I found a tutorial here and am going with that. In the QtCreator IDE, I went to Add New --> C++ Class and in the header file pasted in the header the header from that link and in the .cpp file I pasted the so...
Change the DatabaseManager line to: DatabaseManager db; You're declaring a local function called db that takes no parameters and returns a DatabaseManager object when you provide the ();
3,011,486
3,013,364
Help with GetGlyphOutline function(WinAPI)
I want to use this function to get contours and within these contours, I want to get cubic bezier. I think I have to call it with GGO_BEZIER. What puzzles me is how the return buffer works. "A glyph outline is returned as a series of one or more contours defined by a TTPOLYGONHEADER structure followed by one or ...
I have never used this API myself, but after reading the MSDN documentation I would think it works like this: First you have to call GetGlyphOutline with the lpvBuffer parameter set to NULL. Then the function will return the required size of the buffer. You'll then have to allocate a buffer with that size, then call th...
3,011,515
3,011,524
Vector iterators in for loops, return statements, warning, c++
I have three questions regarding a homework assignment for C++. The goal was to create a simple palindrome method. Here is my template for that: #ifndef PALINDROME_H #define PALINDROME_H #include <vector> #include <iostream> #include <cmath> template <class T> static bool palindrome(const std::vector<T> &input) { ...
can you have more than one iterator declared in the first part of the for loop? Yes, but they both have to be of the same type, so you can't declare both a const_iterator and a const_reverse_iterator. is the way I have my return statements in the palindrome() method ok? Yes, though why not just compare *it != *rit...
3,011,564
3,012,301
How can i list and watch all global variables on watch windows of visual studio (for c++)?
When stopped at a breakpoint on main(), i can manually add name of a global variables to watch windows, but what i want is how to show a list of all global variables, because i'm using an external library, which contains many static things. Is it possible? Thanks in advance!
Is the problem that you don't know the global variable names? Or is the problem that you want to look at many global variables and don't want to type them over and over again in the watch window? For the moment I assume the second. I also assume that your external library is a .LIB library and not a .DLL. You could wr...
3,011,980
3,012,149
Initialize Pointer Through Function
I was browsing my teacher's code when I stumbled across this: Order* order1 = NULL; then order1 = order(customer1, product2); which calls Order* order(Customer* customer, Product* product) { return new Order(customer, product); } This looks like silly code. I'm not sure why, but the teacher initialized all pointe...
Init to NULL [edit] since there's a valid discussion, I've changed the order of the options a bit to emphasize the recommended option. Variables should be declared as local and as late as possible, and initialized immediately. Thus, the most common pattern is: Order * order1 = order(...); just before order1 is requir...
3,012,169
3,012,628
Lots of pointer casts in QGraphicsView framework and performance
Since most of the convenience functions of QGraphicsScene and QGraphicsItem (such as items(), collidingItems(), childItems() etc.) return a QList you're forced to do lots of qgraphicsitem_cast or static_cast and QGraphicsItem::Type() checks to get hold of the actual items when you have lots of different type of items i...
The performance overhead is mostly prepaid; it's the result of the overhead of having the .type() member. It might be efficient to retrieve the item->type() once. You know it doesn't change, but chances are the compiler doesn't. [edit] Also, if you really have a lot of types, it could be worthwhile to introduce some in...
3,012,181
3,012,210
When should we use * , & , . , ->?
Why are we using * character when we are creating button but we aren't adding it to app instance? #include <QApplication> #include <QPushButton> int main(int argc,char *argv[]) { QApplication app(argc,argv); QPushButton *button = new QPushButton("Button Text"); QObject::connect(button,SIGNAL(clicked()),&ap...
new returns a pointer, hence the * is used here to define button as a pointer-to-QPushButton, The & is used to reference (get the address of) app, which is then passed to connect. button->show(); is equivalent to: (*button).show(); This is all basic C (except new) and C++ covered in any introductory book.
3,012,243
3,014,190
boost::asio buffer impossible to convert parameter from char to const mutable_buffer&
visual studio tells me "error C2664: 'boost::asio::mutable_buffer::mutable_buffer(const boost::asio::mutable_buffer&)': impossible to convert parameter 1 from 'char' to 'const boost::asio::mutable_buffer&' at line 163 of consuming_buffers.hpp" I am unsure of why this happen nor how to solve it(otherwise I wouldn't ask ...
Based on this line of code... unsigned short packet_type = *((unsigned short*) _buffer_data.c_str()); ...I'm guessing you are using a std::string as the type for _buffer_data and attempting to read data into it using boost::asio::async_read. You can't do that (see my answer here for an explanation: How to asynchronou...
3,012,351
3,012,411
How to know if a QLineEdit got focus?
I want to be able to know if in the QLineEdit it was a click. So I guess I should reimplement the following function(??): void QLineEdit::focusInEvent ( QFocusEvent * e ) [virtual protected] How should I do that? Also, please tell me how to use focusInEvent() function in order to know if QLineEdit myEdit; object got...
Something like that: class YourWidget : public QLineEdit { Q_OBJECT protected: void focusInEvent(QFocusEvent* e); }; In the .cpp file: void YourWidget::focusInEvent(QFocusEvent* e) { if (e->reason() == Qt::MouseFocusReason) { // The mouse trigerred the event } // You might also cal...
3,012,406
3,012,412
C++ interview question involving class pointers
Lets say there is a base class pointer which is pointing to a base class object: baseclass *bptr; bptr= new baseclass; now if i do bptr= new derived; what is the problem here?
The obvious answer is that you're leaking the original base class object.
3,012,559
3,012,890
How to create combobox with bitmaps in Win32?
I wanted to create a custom combo box like this (as in MS Word), Are there any Win32 API calls (I can't use MFC) to get this job done, (like ChooseColor() or ChooseFont()? If there aren't any, can anyone please tell me how to do this? Thanks you. Regards, EDIT: Creating the Owner-Drawn Dialog Box!! Is this the only w...
You have some options to solve your problem: All common controls supports WM_SETFONT, so if you find a Font which has all line elements which you need, you can change font of the combobox control and fill items with corresponding textes. There are ComboBoxEx control which combines images with textes (see http://msdn.m...
3,012,606
3,012,648
hash_map and stdext:: hash_map?
Under the visual C++, we have " hash_map" and "hash_set". In g++, we have " stdext::hash_map" and " stdext::hash_set". Is there any difference in terms of their respective performance or other factors?
None of those are standards. They were just there to fill a need. Concerning the performances, I have no idea, but I guess they're really similar. What existed in TR1, and will be included in C++1X is unordered_map and unordered_set They say they changed the name to avoid any confusion with previous non-standard implem...
3,012,839
3,012,867
Compilation errors calling find_if using a functor
We are having a bit of trouble using find_if to search a vector of pairs for an entry in which the first element of the pair matches a particular value. To make this work, we have defined a trivial functor whose operator() takes a pair as input and compares the first entry against a string. Unfortunately, when we actu...
This is the most vexing parse. You can do: MyFunctor f(s); or MyFunctor f((std::string(s))); The original declares a function f. f takes a single argument, a pointer to a function taking an argument s and returning std::string.
3,013,154
3,013,159
How to call operator<< on "this" in a descendant of std::stringstream?
class mystream : public std::stringstream { public: void write_something() { this << "something"; } }; This results in the following two compile errors on VC++10: error C2297: '<<' : illegal, right operand has type 'const char [10]' error C2296: '<<' : illegal, left operand has type 'mystream *cons...
mystream *const means that this is a constant pointer to a non-constant object. The problem is that you're trying to stream-insert into a pointer -- you must insert into a stream. Try the following. *this << "something";
3,013,286
3,013,435
GetAdaptersInfo (c++)function not working on vista and windows 7
i am using GetAdaptersInfo on windows xp to retrieve mac address.its working well on xp but neither on vista nor on windows 7. Is GetAdaptersInfo supported by windows 7 and vista. if no what api should i use to get mac address
DWORD GetAdaptersInfo( PIP_ADAPTER_INFO pAdapterInfo, PULONG pOutBufLen ); How did you allocate memory for pAdapterInfo? Seems that there is some issue with stack allocation of this [in] parameter. See this
3,013,354
3,013,394
How do I refactor code into a subroutine but allow for early exit?
There's a really obvious refactoring opportunity in this (working) code. bool Translations::compatibleNICodes(const Rule& rule, const std::vector<std::string>& nicodes) { bool included = false; // Loop through the ni codes. for(std::vector<std::string>::const_iterator ...
Obviously the code would be much cleaner and simpler, if you could iterate through the ni and op members of Rule in a loop. If you can't refactor Rule, maybe you could create a wrapper around it to achieve this goal. If you have a single method with such code, I wouldn't bother though. IMO this would only pay off if yo...
3,013,406
3,013,446
Can I disable min, max in STL?
I use one library which is very important and untouchable. The problem is that library declare min, max function, so when I include STL header in project, they conflict. I want to disable min, max function in STL (like #define NOMNMAX) if I could. If I can't, what would be solution? Important : Sorry, It's not Macro. T...
The min and max functions are defined in the std namespace, so this code should not compile: #include <algorithm> int main() { int n = min( 1, 2 ); } If it does, your Standard Library is non-compliant. Also, your important and untouchable library should be declaring it's functions in a namespace. If it isn't. com...
3,013,743
3,013,764
Do I need multiple template specializations if I want to specialize for several kinds of strings?
For example: template<typename T> void write(T value) { mystream << value; } template<> void write<const char*>(const char* value) { write_escaped(mystream, value); } template<> void write<char*>(char* value) { write_escaped(mystream, value); } template<> void write<const std::string&>(const std::string&...
You did it the proper way. char * and const char * are two distinct typenames, they require each their own specialization.
3,013,757
3,013,796
Are there possible approaches to map signal handling (c library) into a c++ exception?
I have a c++ application linked against some c libraries. Are there possible approaches to encapsulate the signal handling in a C++ class, so it could be handled as a c++ exception?
You can't and if you could a lot of things would break. What you should do is set a flag in the signal handler, periodically check in your code and throw an exception when you detect the flag is set. Such an approach is similar to how threads get interrupted in Boost.Threads, which I strongly suggest you study.
3,013,909
3,014,715
What arguments do I pass to the client when running the boost::asio sockets examples
I am learning how to use the boost asio libraries and I am using the UDP examples on visual studio 2008. I have compiled and run the server application(name udp_server.exe). I have tried to run the client application but is does connect to the server. How do I specify the host and service name to the application for it...
Assuming that you are referring to the "Daytime.4 - A synchronous UDP daytime client" example, the server's host name is passed as argv[1] (the first command-line parameter) to the udp::resolver::query ctor. As you can see from the docs, the port is passed as the 3rd parameter to the ctor. This parameter can be a strin...
3,013,926
3,014,304
How to write a custom predicate for multi_index_containder with composite_key?
I googled and searched in the boost's man, but didn't find any examples. May be it's a stupid question...anyway. So we have the famous phonebook from the man: typedef multi_index_container< phonebook_entry, indexed_by< ordered_non_unique< composite_key< phonebook_entry, member<phonebook_en...
It should look like composite_key_compare. For your case (non-template version): typedef composite_key< phonebook_entry, member<phonebook_entry,std::string,&phonebook_entry::family_name>, member<phonebook_entry,std::string,&phonebook_entry::given_name> > my_comp_type_t; struct my_custom_comp { bool o...
3,013,989
3,014,057
Problems compiling an external library on linux
So I am trying to compile the libssh2 library on linux, but when I try to compile the example it comes up with a lot of errors, and even though I include the headerfile it asks for, it still asks for it. Here are the error messages and the resulting messages: ~/ gcc -include /home/Roosevelt/libssh2-1.2.5/src/libssh2_c...
I just cloned the current git build and went into the 1.2.5 relase but I'm unable to reproduce your problem. ./buildconf ./configure make works fine. What are you trying to do exactly?
3,014,011
3,014,164
C++: Weird Segmentation fault
I am trying to print something using C++. However, I am running into a strange bug that has left me clueless, I use the following code: PRINTDLG pd; ZeroMemory(&pd, sizeof(pd)); pd.lStructSize = sizeof(pd); pd.Flags = PD_RETURNDEFAULT; PrintDlg(&pd); // Set landscape DEVMODE* pDevMode = (DEVMODE*)GlobalLock(pd.hDevMod...
I don't know if this is a potential problem here - but you should always initialize all members of structures (like you did with the PRINTDLG). In the DOCINFO struct the lpszDataType member is uninitialized. Instead of using ZeroMemory or memset, I prefer something like DOCINFO di = {0};
3,014,298
3,014,457
MFC , C++ in embedded(semiconductor) projects
What are the internal features/aspects of C++/ VC++ and MFC that are used for embedded(semiconductor) projects by large IT companies. I ask this becuase I need to be prepared for one such poistion. please reply.
MFC isn't used in typical embedded projects. It's an old Microsoft library, typically used for PC software as opposed to embedded software. C++ (the language) and VC++ (a Microsoft compiler for the C++ language) are used in embedded projects. However, the Microsoft compiler cannot target common embedded platforms such ...
3,014,832
3,014,878
consts and other animals
Possible Duplicate: what is the difference between const int*, const int * const, int const * i have a cpp code wich i'm having trouble reading. a class B is defined now, i understand the first two lines, but the rest isn't clear enough. is the line "B const * pa2 = pa1" defines a const variable of type class B? if...
This code declares a pointer to a constant B - in other words, it cannot be used to change the value of what it is pointing to: B const * pa2 = pa1; Alternatively, the following code declares a constant pointer to a constant B - so, pa3 cannot be used to change the value of what it is pointing to, and it cannot be mod...
3,014,879
3,015,500
QT - How to apply a QToolTip on a QLineEdit
On a dialog I have a QLineEdit and a button. I want to enable a tool tip for the QLineEdit(in it or under it) when I press the button. Please give me a code snippet.
Here is a simple example: class MyWidget : public QWidget { Q_OBJECT public: MyWidget(QWidget* parent = 0) : QWidget(parent) { QVBoxLayout* layout = new QVBoxLayout(this); edit = new QLineEdit(this); layout->addWidget(edit); showButton = new ...
3,014,947
3,015,033
how-to add "warnings as error" rule to Qt .pro file?
When I usually work on a C++ project, one of the first things I do is setting up the "treat warning as errors" on my compiler. When using Qt, qmake generates the Makefile for you and doesn't include this option on the compilation commands. I'm pretty sure there is a way to add such an option (and others) into the gener...
You can use QMAKE_CXXFLAGS in pro file to specify compiler flags: QMAKE_CXXFLAGS += -Werror
3,015,263
3,020,675
Segfaults with singletons
// Non singleton class MyLogManager { void write(message) {Ogre::LogManager::getSingletonPtr()->logMessage(message);} } class Utils : public singleton<Utils> { MyLogManager *handle; MyLogManager& getHandle { return *handle; } }; namespace someNamespace { MyLogManager &Log() { return Utils::g...
It feels like you have typical "static initialization order fiasco" - your Utils instance created before one (or both) of other singletons. Try change Utils::configHandle() to something like this: ConfigManager &configHandle() const { static std::auto_ptr<ConfigManager> configHandlePtr(0); if (!configHandlePtr...
3,015,306
3,015,403
What exactly does -march=native do?
Gentoo Wiki told me the following: Warning: GCC 4.2 and above support -march=native. -march=native applies additional settings beyond -march, specific to your CPU. Unless you have a specific reason not to (e.g. distcc cross-compiling), you should probably be using -march=native, rather than anything listed...
Nevermind. $ cc -march=core2 -E -v - </dev/null 2>&1 | grep cc1 /[...]/cc1 -E -quiet -v -iprefix /[...]/4.3.2/ - -march=core2 $ cc -march=native -E -v - </dev/null 2>&1 | grep cc1 /[...]/cc1 -E -quiet -v -iprefix /[...]/4.3.2/ - -march=core2 -mcx16 -msahf --param l1-cache-size=32 --param l1-cache-line-size=64 -mtune...
3,015,311
3,015,616
Why this Explicit P/Invoke does not work?
The following .net to native C code does not work, any ideas extern "C" { TRADITIONALDLL_API int TestStrRef( __inout char* c) { int rc = strlen(c); std::cout << "the input to TestStrRef is: >>" << c << "<<" ; c = "This is from the C code "; return rc; } } [DllImport("MyDll.dll", SetLastError = ...
Your code wrong at C side also. __inout annotation just tell compiler you can change buffer to which "c" argument pointed. But pointer itself located in stack and does not return to caller if you modified "c" argument. Your declaration may look like: extern "C" { TRADITIONALDLL_API int TestStrRef( __inout char** c)...
3,015,444
3,015,774
Instant crashing after replacing calls to clock() with MPI_Wtime()
I have an MPI program that I'm developing on a local computer, but need to run on a remote machine. I used clock() to measure time, but after discovering that it doesn't work well enough on the remote machine (due to a completely different architecture), I replaced a few calls to clock() with MPI_Wtime(), which yielded...
Are you calling MPI_Wtime() from the constructor of a static object? These run before main().
3,015,507
3,015,678
C++ template member specialization - is this a compiler limitation?
Is it possible to do this kind of specialization? If so, how? The specialization in question is marked //THIS SPECIALIZATION WILL NOT COMPILE I have used VS2008, VS2010, gcc 4.4.3 and neither can compile this. I know i can avoid this by overloading func but i want to know if there is a way to do this with template spec...
To answer the question you ask in the title: no, this is not a compiler limitation. This is a language limitation. In C++, in order to explicitly specialize a nested template (be that a class template or a member function template) you have to also explicitly specialize the enclosing template. You are trying to explici...
3,015,582
3,015,871
Direct boost serialization to char array
Boost serialization doc's assert that the way to serialize/deserialize items is using a binary/text archive with a stream on the underlying structure. This works fine if I wan't to use the serialized data as an std::string, but my intention is to convert it directly to a char* buffer. How can I achieve this without cre...
IIUC, you would like to write to a preallocated array of fixed size. You could use a boost::iostreams::array_sink (wrapped with stream to give it an std::ostream interface) for that.
3,015,624
41,755,724
how to declare type conversion in header file and implement in cpp file?
it doesn't work for me. i have a header file and a cpp file. need to define a conversion operator from my class to INT, but it gives me "syntax error" when declaring it in the H file and implementing in the cpp file. maybe i got the syntax wrong? in the H file i have in "public": operator int(); and in the cpp file i ...
I also wanted to separate the class declaration from the implementation. The critical missing ingredient was the const: // Foobar.hpp class Foobar { public: Foobar() : _v(42) {} operator int() const; private: int _v; }; And then in the implementation file: #include "Foobar.hpp" Foo...
3,015,632
3,016,071
how to use cpp source for 2 projects
I'm not sure if I am going about this the right way. I am making some c++ classes to use in 2 apps. I am going to have to compile them to be used in a Cocoa app and later be compiled for use with fastcgi. Should I create a dynamic library?
Don't forget that you have static library as an option too. On some platforms dynamic libs come with a bunch of annoying baggage. They're also slightly slower (though this is usually beside the point). They also can't be replaced without recompiling the program (you might be more concerned about this in a web enviro...
3,015,964
3,015,990
Using template parameters as template parameters
Why is the following code invalid? template <typename S, typename T> struct B{ void f(T t, S s) {t.f<S>(s); } }; gcc 4.3.4 complains that it "expected primary-expression before '>' token", i.e. that "S" wasn't a valid primary-expression.
You need to specify that f is a template: void f(T t, S s) { t.template f<S>(s); } C++ doesn’t know this (at this point) since f’s type depends on the type of the template parameter T. Furthermore, the following syntax would be ambiguous: does < mean the start of a template list or a less-than operator? To help C+...
3,016,350
3,019,274
Qt: Animating the 'roll down' of a QWidget
I have a QWidget that contains various other widgets. I want to animate it appearing on the screen by gradually revealing it from the top down, increasing it's height from 0 to whatever it's natural height would be. The way I have it currently is: mAnimation = new QPropertyAnimation(this, "maximumHeight"); mAnimation-...
For the crash, I'd recommend grabbing a stack trace and, assuming the problem isn't in your code, report it as a bug. For the second, rather than render the widget exactly where you want it with different sizes, render it as you'd like it to be seen. For example: Use a QStackWidget with two items: the actual widget an...
3,016,399
3,021,382
Qt - How to post a banner on the dialog?
I have a directroy where I have several pictures and gif animations. I want to post that pictures and animations on a QDialog in an infinite loop (by cyclically changing pictures in 2 minutes interval) and on that pictures and animations I want to set a link so that when you click the browser open the set link. How I c...
You can use 2 QLabels for this. The first one will be used for static images like jpg and the second one for animations. In the first one you can use setPixmap to set the image and in the second one you need to create a QMovie object giving it the gif file in the constructor. Once the object is created you can assign t...
3,016,524
3,016,589
Use of function pointers for callling functions in a DLL
Is it possible to call a function in a DLL loaded dynamically without making use of function pointers.
Yes, sort of, depending on what you're trying to accomplish. At least for some purposes, the linker's delayload switch can give roughly the effect of explicit dynamic linking, without requiring that you define pointers to all the functions you're going to use, use GetProcAddress to assign values to those pointers, etc....
3,016,683
3,017,368
The difference between traditional DLL and COM DLL
I am currently studying COM. I found that COM DLL is kind of built upon the traditional DLL infrastructure. When we build COM DLLs, we still rely on the traditional DLL export methods to lead us to the internal COM co-classes. If COM is for component reusing at the binary level, I think the traditional DLL can achieve...
No, there's a Big difference. COM has a well defined protocols for creating objects, exposing methods, managing memory, publishing type information, managing threading. There is practically no language left that doesn't support using a COM server, no matter what language it was written in. You will not get that from ...
3,016,714
3,016,764
How does one hide a win32 app window?
I want to run the app in silent mode by passing in a parameter, otherwise I will show the window.
ShowWindow(... SW_HIDE ...) doesn't work? The best practice here is to not create the window in the first place. Nothing forces you to actually create a window in InitInstance. Though if you're working with MFC it's likely a lot of your application/domain/business logic is sitting there, tightly coupled to those MFC me...
3,016,749
3,016,760
Do static local variables in a class persist between objects?
class MyClass { static int staticInt; void instanceMethod( int param ) { static int parameter = param; } } Clearly staticInt is shared between all instance of MyClass. But can different instances of MyClass have different values of parameter the static local variable within instaceMethod? Update What abo...
There is exactly one instance of parameter. If you want an instance of parameter for each instance of the class, use a nonstatic member variable.
3,016,772
3,016,845
Dynamic memory allocation with default values
class A { private: int m_nValue; public: A() { m_nValue = 0; } A(int nValue) { m_nValue = nValue); ~A() {} } Now in main if i call A a(2);// 2 will be assigned for m_nValue of object A. Now how do we do this if i want to define an array of objects. Also how do we do this if i dynamically create objects using operato...
You cannot do this. If you want to dynamically allocate an array, it has to be a default-constructable object. This means, it needs to have a constructor with no parameters, which is the one that will be used.
3,016,839
3,016,922
How can I call a function from a dll?
How could I call a function from a DLL? I tried to declare a void pointer and to store in it the result of GetProcAddress... but didn't work. I also wanted to declare an unsigned long int (I saw it somewhere on the internet), but then I didn't know how to continue on. :D So, would anybody mind giving me a hand?
Try for something like this. typedef int (*PFuncMethods)( int args ); hDLL = LoadLibrary(L"your.dll"); if( !m_hDLL ) return; methods = (PFuncMethods)GetProcAddress(hDLL,"methods"); if ( !(methods) ) { FreeLibrary(hDLL); hDLL = NULL; methods = NULL; return; } if( methods(1) == 0) ... the method name is w...
3,016,899
3,016,982
Qt QMainWindow at Close
this may seem like a very simple question, but I want to dump some data whenever the QMainWindow closes, so I used the following piece of code: QObject::connect(MainWindow.centralwidget, SIGNAL(destroyed()), this, SLOT(close())); But this doesn't seem to make it call close(). Am I doing this wrong?. Isn't the centralw...
I'd try QGuiApplication::lastWindowClosed() instead.
3,016,956
3,016,986
How do I install the OpenSSL libraries on Ubuntu?
I'm trying to build some code on Ubuntu 10.04 LTS that uses OpenSSL 1.0.0. When I run make, it invokes g++ with the "-lssl" option. The source includes: #include <openssl/bio.h> #include <openssl/buffer.h> #include <openssl/des.h> #include <openssl/evp.h> #include <openssl/pem.h> #include <openssl/rsa.h> I ran: $ su...
You want to install the development package, which is libssl-dev: sudo apt-get install libssl-dev
3,017,039
3,017,075
How to pass a function in a function?
That's an odd title. I would greatly appreciate it if somebody could clarify what exactly I'm asking because I'm not so sure myself. I'm watching the Stanford videos on Programming Paradigms(that teacher is awesome) and I'm up to video five when he started doing this: void *lSearch( void* key, void* base, int elemSize,...
int (*cmpFn)(void*, void*) is a function pointer -- a pointer to a function that can be called later. When you call iSearch you pass it a function that takes two void* and returns an int, and it binds that to the parameter cmpFn. Then iSearch can do something like int x = cmpFn(voidPtr1, voidPtr2); to call that functio...
3,017,051
3,017,518
Obtain container type from (its) iterator type in C++ (STL)
It is easy given a container to get the associated iterators, example: std::vector<double>::iterator i; //An iterator to a std::vector<double> I was wondering if it is possible, given an iterator type, to deduce the type of the "corresponding container" (here I am assuming that for each container there is one and only...
I don't think this would be possible. On some STL libraries you actually have a vector iterator as a pointer type, i.e. std::vector<T>::iterator is a T* so I can't think of any way you could get back to the container type from that.
3,017,095
3,017,130
Interaction between for loops with clock function?
Can someone explain me the exact interaction in context of delay between the two for loops with clock function. How does for1 interact with for2 on the cout statement(30 on 640000000)? start=clock(); cout<<endl<<start<<endl; for(delay=0; delay<30; delay++) for(i=0; i<640000000; i++); end=clock(); cout<<end<<endl; ...
Probably a decent optimizer will see that the loop is a no-op and optimize it out completely, so there will be almost no difference between start and end. If it's not optimized out, the two loops are simply working around the fact that 30*640000000 is bigger than could be stored in a 32-bit integer. It runs the inner 6...
3,017,162
3,017,438
How to get total cpu usage in Linux using C++
I am trying to get total cpu usage in %. First I should start by saying that "top" will simply not do, as there is a delay between cpu dumps, it requires 2 dumps and several seconds, which hangs my program (I do not want to give it its own thread) next thing what I tried is "ps" which is instant but always gives very h...
cat /proc/stat http://www.linuxhowtos.org/System/procstat.htm I agree with this answer above. The cpu line in this file gives the total number of "jiffies" your system has spent doing different types of processing. What you need to do is take 2 readings of this file, seperated by whatever interval of time you require...
3,017,234
3,017,262
How to handle asynchronous socket receiving in C++?
I'm currently using a thread to handle Connect and Send calls asynchronously. This is all working fine, but now I want to make receiving asynchronous too. How should I receive data without pausing the whole queue while waiting for data? The only solution I can think of right now is a second thread.
Look into non-blocking sockets and polling APIs like select(2)/poll(2)/epoll(4)/kqueue(2). Specifically in C++, look into boost::asio.
3,017,264
3,017,290
Is it good practice to make getters and setters inline?
public: inline int GetValue() const { return m_nValue; } inline void SetValue(int nNewValue) { this -> m_nValue = nNewValue; } On Learn C++, they said it would run faster. So, I thought it would be great to use on getters and setters. But maybe, there are some drawbacks to it?
I don't inline anything until a profiler has specifically told me that not inlining is resulting in a performance problem. The C++ compiler is very smart and will almost certainly automatically inline such simple function like this for you. And typically it's smarter than you are and will do a much better job at det...
3,017,389
3,017,431
Question about my sorting algorithm in C++
i have following code in c++ #include <iostream> using namespace std; void qsort5(int a[],int n){ int i; int j; if (n<=1) return; for (i=1;i<n;i++) j=0; if (a[i]<a[0]) swap(++j,i,a); swap(0,j,a); qsort5(a,j); qsort(a+j+1,n-j-1); } int main() { return 0; } ...
swap is a function in std which must be included by <iostream>. When you attempt to make calls to your swap, it can't find it (I'll explain in a moment) and instead looks at the std::sort, which takes two arguments (hence the first error). The reason it can't find your swap is because it is declared after it is called....
3,017,411
3,017,508
Why does this class declaration not work on Visual Studio
So I'm trying to get some code that is written for gcc to compile on Visual Studio 2008. I have a problem that I have narrowed down to this: class value_t { public: typedef std::deque<value_t> sequence_t; typedef sequence_t::iterator iterator; }; This code fails: 1>cpptest.cpp 1>c:\program files\mic...
Its undefined behavior. See this link on c.l.c++.moderated Snip from Daniel K's answer :- the C++ standard (both C++03 and C++0x) says that what you are trying causes undefined behaviour, see [lib.res.on.functions]/2: "In particular, the effects are undefined in the following cases: [..] — if an incomp...
3,017,425
3,018,880
opencv conversion from a Mat element to IplImage *
How can I convert a Mat element to IplImage * element? Please Help!
Mat mat_img; //.... IplImage ipl_img = mat_img; This puts a header of IplImage on top of mat_img so there is no copying. You can pass &ipl_img to function which need IplImage*.
3,017,462
6,330,990
how can i use youtube chromeless player in desktop application?
i like to use youtube chromeless player in my QT c++ application im using qwebkit , but in the youtube doc's its says: " To test any of these calls, you must have your file running on a webserver...." how can i overcome this restriction and use chromeless player or some alternative?
What exactly do you want from Youtube Chrome-less player. If it is the outlook and GUI then you can create exactly like this in QT. If it is the playability of the files you can use several open source media file APIs, or even QT Media extensions. Youtube chromeless player is just an swf application that can host a fil...
3,017,538
3,017,764
OpenCV image conversion from RGB to HSV
When I run this following code on a sample image(RGB), and then process it to display the converted HSV image, Both appear to be different... Can anyone explain why this happens? OR Can you suggest a solution for this not to happen... because it's the same image after all Mat img_hsv,img_rgb,red_blob,blue_blob; img_rgb...
I don't know the new (2.x) OpenCV well enough yet, but usually images loaded in OpenCV are in CV_BGR channel order and not RGB, therefore you most likely want CV_BGR2HSV OpenCV does not actually "know" HSV, it will just encode Hue in first channel, Saturation in second and Value in third. If you display an image in Op...
3,017,642
3,017,664
OpenGL: How to update only a portion of a texture?
I dont want to update the whole texture every time i change a small part of it, what is the command for this? And when i have mipmapping on, set with GL_GENERATE_MIPMAP, how optimized is that internally? will it calculate whole image again, or just the part i updated?
glTexSubImage2D. Mipmap generation process is implementation dependant, it probably will update the whole mipmap chain.
3,017,745
3,017,793
Given Date, Get Day of Week - SYSTEMTIME
Is it possible to determine the day of the week, using SYSTEMTIME, if a date (month-day-year) is provided or is this structure one-way only? What is the most lightweight way to accomplish what I am asking if SYSTEMTIME cannot do it (using Win32)?
According to the msdn, the wDayOfWeek member is ignored when converting SYSTEMTIME to FILETIME. When converting back, it's filled in. SYSTEMTIME t = { 2010, 6, -1 /*ignored*/, 11 }; FILETIME ft; HRESULT hrto = SystemTimeToFileTime( &t, &ft ); HRESULT hrback = FileTimeToSystemTime( &ft, &t ); WORD dayofweek = t.wDay...
3,017,814
3,017,854
check compiler version in visual studio 2008
Im writing application in c++ and after try to run built (in debug mode) application on another machine I had error (The application has failed to start because its side-by-side configuration is incorect). I realised that there are missed DLLs from windows\WinSxS\ But I dont really know which folder contains what I re...
Compile with your runtime library set to multi threaded instead of multi threaded DLL. 1) Right click on your project, click on properties 2) Under Configuration Properties -> C/C++ -> Code Generation 3) Change the Runtime Library value to be Multi Threaded Debug (if in debug) or Multi Threaded Release (if in release) ...
3,017,915
3,017,943
Displaying a `std::map`
Declared a map early on: map<char*,char*> rtable; // used to store routing information Now I'm attempting to display the contents of the map: void Routes::viewroutes(){ typedef map<char*, char*>::const_iterator iter; for (iter=rtable.begin(); iter != rtable.end(); ++iter) { cout << iter->second << "...
iter is a type in your code. Should be a variable. typedef map<char*,char*> my_map_t; // alias for a specialized map // declare a variable of needed type my_map_t rtable; // declare iter of type my_map_t::const_iterator for (my_map_t::const_iterator iter=rtable.begin(); iter != rtable.end(); ++iter) { cout <<...
3,018,201
3,018,231
How to Access a Private Variable?
This question isn't meant to sound as blatantly insulting as it probably is right now. This is a homework assignment, and the spec sheet is scarce and poorly designed to say the least. We have a function: double refuel( int liter, GasStation *gs ) { // TODO: Access private variable MaxFuel of gs and decrement. } S...
Now that sounds like a real lousy homework assignment. Anyway, I can think of three ways to access private data: through public member functions by a friend of the class cheating: #define private public #include "the_class.h" #undef private The first two are legal, but require you to change the class. The last i...
3,018,313
6,930,407
Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both
I am looking for color space converter from RGB to HSV, specifically for the range 0 to 255 for both color spaces.
I've used these for a long time - no idea where they came from at this point... Note that the inputs and outputs, except for the angle in degrees, are in the range of 0 to 1.0. NOTE: this code does no real sanity checking on inputs. Proceed with caution! typedef struct { double r; // a fraction between 0 and ...
3,018,418
3,018,475
Open Source Simple Speech Recognition in C++ in Windows
I was wondering, are there any basic speech recognition tools out there? I just want something that can distinguish the difference between "yes" and "no" and is reasonably simple to implement. Most of the stuff out there seems to make you start from scratch, and I'm looking for something more high level. Thanks!
Sphinx3 & PocketSphinx are written in C, so it shouldn't be too hard wrap it for C++. It's still an active project too, which is good.
3,018,511
3,018,602
g++ linker can't find const member function
I have a Point class (with integer members x and y) that has a member function withinBounds that is declared like so: bool withinBounds(const Point&, const Point&) const; and defined like this: bool Point::withinBounds(const Point& TL, const Point& BR) const { if(x < TL.getX()) return false; if(x > BR.getX()) r...
It looks like in the calling file, whatever header is included to give the declaration of withinBounds has the incorrect declaration, of a non-const version of the method (note that the undefined reference is to a non-const version). Make sure that your project include directories don't include multiple versions of the...
3,018,550
3,018,582
How to create pulsating value from 0..1..0..1..0 etc for a given duration?
I'm working on some code where I have a Time object with a member time. Time.time gives me the time since my application started in seconds (float value). Now I want to create a pulsating value between 0 and 1 and then from 1 to 0 again, which continues doing thins untill the application stops. I was thinking to use s...
You mention using sin(), so I guess you want it to pulse continuously between 0 and 1. Something like this will do: float pulse(float time) { const float pi = 3.14; const float frequency = 10; // Frequency in Hz return 0.5*(1+sin(2 * pi * frequency * time)); } 1/frequency = 0.1 second is the period, which ...
3,018,585
3,018,668
How to composite argb image data on top of xrgb image data
I have a pointer to an 32bit argb image's pixel data and a 32bit xrgb image's pixel data. How can I composite the argb on top of xrgb image while making use of the alpha component? Visual Studio 2008 C++ Edit: Is there a quicker (faster processing) way to do the compositing than this: float alpha = (float)Over...
Presumably by XRGB you mean a bitmap with four bytes per pixel, but what would be the alpha channel left at some constant value. An obvious starting point would be to draw the XRGB bitmap first, and the RGBA bitmap second. When you draw the second, enable blending (glEnable(GL_BLEND);) and set your blend function with ...
3,018,626
3,018,635
What is the motivation behind C++11 lambda expressions?
I am trying to find out if there is an actual computational benefit to using lambda expressions in C++, namely "this code compiles/runs faster/slower because we use lambda expressions" or is it just a neat development perk open for abuse by poor coders trying to look cool? I understand this question may seem subjective...
I don't think it's nearly as much about the computational performance as increasing the expressive power of the language.
3,018,681
3,019,063
wxWidgets running on other machine
I created application which uses wxWidgets library using visual studio 2008. Now I would like to create version which may be run on other machine. Because right now when I want to run It on another machine there is an error: the application failed to start because its side-by-side configuration is incorrect. What can ...
The Event Viewer should have a record showing what DLL was being searched for, what version of that DLL if found in the SxS cache, and what version it was looking for but couldn't find. You'll then want to (for example) include the correct version of that DLL to be installed with your program. Alternatively, just link ...
3,018,739
3,018,805
Common protected data member in base class?
I have a base class and several derived classes. The derived classes use some common data, can I just put those common data as protected member of the base class? I know the protected member breaks encapsulation sometimes, so I wonder if there is any good approach. Here is a specific example: class Base{ public: vi...
One design to consider is making mData private, and adding protected methods to Base that provide common manipulations to the data that can then be used by Dr1 and Dr2. But there are plenty of times it makes more sense to leave mData as a protected member. The best approach will very much depend on the details of your ...
3,018,821
3,018,836
Simple change results in make: Error 1
Had this: rtable.insert ( pair<string,string>(destination,nhop) ); // route insertion return 0; Changed it to this: if (rtable.insert ( pair<string,string>(destination,nhop)) == 0){ return 0; } First one compiles fine. Second one gives me a make error 1. I can go back and forth all day -- I can't see any issues. ...
That overload of std::map::insert() returns a std::pair<iterator, bool>. You can't compare that against zero. That bool element tells you whether a new element was inserted; if you want to compare against that you can simply use: if (rtable.insert(pair<string,string>(destination,nhop)).second) return 0
3,019,361
3,019,379
difference between -> and . for member selection operator
Possible Duplicate: what is the difference between (.) dot operator and (->) arrow in c++ in this book i have I'm learning pointers, and i just got done with the chapter about OOP (spits on ground) anyways its telling me i can use a member selection operator like this ( -> ). it sayd that is is like the "." except p...
Yeah, it actually does the same thing but for different kind of variables. If you have a pointer you have to use ->, while if you have a real value you will use .. So for example struct mystruct *pointer; struct mystruct var; pointer->field = ... var.field = ... That's not hard at all. Just remember that with a point...
3,019,416
3,019,511
How to use the callback method with a c++ directshow sample grabber
I have a sample grabber hooked into my directshow graph, based on this example http://msdn.microsoft.com/en-us/library/dd407288(VS.85).aspx the problem is that it uses one shot and buffers. I want to continuously grab samples, and i'd rather have a callback than i guess polling for the samples. How do use the SetCallb...
I come from a c# background, and thought that at some level i could just pass a reference to a method. This doesn't seem to be case. Instead it requires you create a class the implements its interface that defines the method that it will call. You then pass an instance of the class to the filter in the SetCallback m...
3,019,444
3,020,792
book "Programming Role Playing Games with DirectX 2nd edition" and newer DirectX api
I got the book "Programming Role Playing Games with DirectX 2nd edition" and I notice there are things in the book that are now considered deprecated. There is a whole Section on DirectPlay. And as much as I would like to avoid this section, I am afraid it might screw up the entire engine he is trying to build. So I wa...
Sure you can use it. You can write your entire game in DirectX 3 if you want. DirectX 9 includes ALL previous releases. The only issue you will have is finding the headers. TBH, though, you'd be best off ditching it and learning sockets programming instead. Sockets will NEVER go away. They aren't particularly di...
3,019,512
5,294,005
C++0x unique_ptr replaces scoped_ptr taking ownership?
I used to write code like this: class P {}; class Q: public P {}; class A { // takes ownership A(P* p): p_(p) {} scoped_ptr<P> p_; }; A a(new Q); With C++0x, should I rewrite class A as: class A { // takes ownership A(unique_ptr<P>&& p): p_(p) {} unique_ptr<P> p_; };
I've upvoted comonad's answer, but with a caveat: Whenever you want to explicitely disallow move semantics, use a scoped_ptr const unique_ptr. I have not come across any use cases where a const std::unique_ptr is inferior to a boost::scoped_ptr. However I'm open to education on the subject. Edit: Here is a use cas...
3,019,868
3,019,888
Can I tell direct3d to render with alpha channel?
I need to composite direct3d renders on top of a video feed, the way i have it setup the format i get the data in is 32 bit xrgb with a byte for red green blue and a throw away. Can I get it to render with an alpha channel so i can use it for better blending?
You sure can. Use D3DFMT_A8R8G8B8 for your back buffer. http://msdn.microsoft.com/en-us/library/bb172558(VS.85).aspx
3,019,977
3,020,014
Convert wchar_t to char
I was wondering is it safe to do so? wchar_t wide = /* something */; assert(wide >= 0 && wide < 256 &&); char myChar = static_cast<char>(wide); If I am pretty sure the wide char will fall within ASCII range.
assert is for ensuring that something is true in a debug mode, without it having any effect in a release build. Better to use an if statement and have an alternate plan for characters that are outside the range, unless the only way to get characters outside the range is through a program bug. Also, depending on your ch...
3,019,979
3,020,030
Microsoft sublanguage string to locale identifier
I can't seem to find a way to convert, or find, a local identifier from a sublanguage string. This site shows the mappings: http://msdn.microsoft.com/en-us/library/dd318693(v=VS.85).aspx I want the user to enter a sublanguage string, such as "France (FR)" and to get the local identifier from this, which in this case wo...
A good starting point would be the LCIDToLocaleName function and it's opposite - LocaleNameToLCID. Note that these allow converting between LCID and RFC4646 locale name; to get the humanreadable country and language names, use the GetLocaleInfoEx with the LOCALE_SENGLISH* flags. If you need localized names instead of E...
3,020,053
3,020,056
Casting/dereferencing member variable pointer from void*, is this safe?
I had a problem while hacking a bigger project so I made a simpel test case. If I'm not omitting something, my test code works fine, but maybe it works accidentally so I wanted to show it to you and ask if there are any pitfalls in this approach. I have an OutObj which has a member variable (pointer) InObj. InObj has a...
Yes, this is safe. A pointer to any type can be converted to a pointer to void and back again. Note that the conversion to void* is implicit, so you don't need the cast.