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
2,982,167
2,982,197
Integration (math) in C++
I'm looking for a library to find the integral of a given set of random data (rather than a function) in C++ (or C, but preferably C++). There is another question asking about integration in C but the answers discuss more how to integrate a function (I think...). I understand that this can be done simply by calculat...
This is trivial. If the points are (x0, y0), (x1, y1), ..., (xN, yN), and the points are ordered so that x0 <= x1 <= ... <= xN, then the integral is y0 * (x1 - x0) + y1 * (x2 - x1) + ... using no interpolation (summing areas of rectangles), and (y0 + y1)/2 * (x1 - x0) + (y1 + y2)/2 * (x2 - x1) + ... using linear in...
2,982,224
2,982,229
Access element of pointed std::vector
I have a function where I provide a pointer to a std::vector. I want to make x = to vector[element] but i'm getting compiler errors. I'm doing: void Function(std::vector<int> *input) { int a; a = *input[0]; } What is the right way to do this? Thanks
Should be: void Function(std::vector<int> *input) { // note: why split the initialization of a onto a new line? int a = (*input)[0]; // this deferences the pointer (resulting in) // a reference to a std::vector<int>), then // calls operator[] on it, returning an...
2,982,325
2,983,171
Quantifying the Performance of Garbage Collection vs. Explicit Memory Management
I found this article here: Quantifying the Performance of Garbage Collection vs. Explicit Memory Management http://www.cs.umass.edu/~emery/pubs/gcvsmalloc.pdf In the conclusion section, it reads: Comparing runtime, space consumption, and virtual memory footprints over a range of benchmarks, we show that the runt...
You seem to be asking two things: have GC's improved since that research was performed, and can I use the conclusions of the paper as a formula to predict required memory. The answer to the first is that there have been no major breakthroughs in GC algorithms that would invalidate the general conclusions: GC'ed memo...
2,982,369
2,982,382
rand () for c++ with variables
int userHP = 100; int enemyHP = rand() % ((userHP - 50) - (userHP - 75)) + 1; okay, for some reason this doesnt seem to work right, im trying to get 50 -25 hp for enemys. also id rather it be a percentage... like int enemyHP = rand() % ((userHP / 50%) - (userHP / 75%)) + 1; but id like to stick with integers and no...
Perform some algebra on this: rand() % ((userHP - 50) - (userHP - 75)) + 1; rand() % (userHP - 50 - userHP + 75) + 1; rand() % (userHP - userHP - 50 + 75) + 1; rand() % (-50 + 75) + 1; ...and you can quickly see what's going wrong. Why not use doubles?
2,982,387
2,982,486
global std::unordered_map com server init problems
I want to have a static global std::unordered_map in the cpp of my entry point for my COM server. relevant header code: typedef unordered_map<HWND,IMyInterface*> MyMapType; relevant body: static MyMapType MyMap; void MyFunction(HWND hWnd, IMyInterface* pObj){ MyMap[hWnd] = pObj; } HINSTANCE g_hInstModule = NULL;...
You need to modify DllMain to explicitly initialize the C runtime: http://support.microsoft.com/kb/814472 Search for "To Modify COM-based DLL" Static objects with constructors usually get initialized through the CRT entry point which for .exes then calls your program's main function. With DLLs, you have to the work you...
2,982,388
2,982,421
Translating C++'s sprintf format string to C#'s string.Format
I found the following C++ code (comments added myself): // frame_name is a char array // prefix is std::string // k is a for loop counter // frames is a std::vector string sprintf(frameName, "%s_%0*s.bmp", prefix.c_str(), k, frames[k].c_str()); I then try to translate it to C# // prefix is string // k is a for loop co...
To pad a string with zeros use string.PadLeft: frames[k].PadLeft(n, '0') In combination with string.Format: int n = 15; // Get this from somewhere. string frameName = string.Format("{0}_{1}.bmp", prefix, frames[k].PadLeft(n, '0')); Note that I have cha...
2,982,447
2,982,450
simple question on C
I have this snippet of the code char *str = “123”; if(str[0] == 1) printf("Hello\n"); why I can't receive my Hello thanks in advance! how exactly compiler does this comparison if(str[0] == 1)?
You want to do this: if (str[0] == '1') ... The difference is that you are comparing str[0] to the number 1, while my code above is comparing str[0] to the character '1' (which has ASCII value 49). Not all programming languages treat characters and numbers interchangeably in this way, but C does. Check out ASCII for m...
2,982,505
2,982,566
Did I implement this correctly?
I'm trying to implement line thickness as denoted here: start = line start = vector(x1, y1) end = line end = vector(x2, y2) dir = line direction = end - start = vector(x2-x1, y2-y1) ndir = normalized direction = dir*1.0/length(dir) perp = perpendicular to direction = vector(dir.x, -dir.y) nperp = normalized perpendicul...
You are calculating perp incorrectly. It should be (y, -x), not (x, -y). I don't know if that's the only bug. This one just jumped out at me. As an aside, I strongly recommend that you define a useful vec2 type, with useful helpers like: vec2 perp(vec2 v) { return vec2(v.y, -v.x); } That way, your code will look almos...
2,982,514
2,982,655
Boost.Asio: The difference between async_read and async_receive
What's the difference between async_read and async_receive?
async_receive is a function that just receives into a buffer, but may not receive the amount you asked for. (It'll be equal or less, never more.) async_read, however, will always receive the amount you asked for, as it states: This function is used to asynchronously read a certain number of bytes of data from a stream...
2,982,592
2,982,599
Does a no-op "do nothing" function object exist in C++(0x)?
I realize this is a ludicrous question for something that takes less than 2 seconds to implement. But I vaguely remember reading that one was introduced with the new standard. I grep'ed VC10's headers and came up with nothing. Can you help? It's bugging me! :) edit: On second thought, the new functor I was remembering ...
You could always write a no-op lambda: []{}
2,982,660
2,982,681
problem with template inheritance
I'm trying to understand whay i get an error on this code: (the error is under g++ unix compiler. VS is compiling OK) template<class T> class A { public: T t; public: A(const T& t1) : t(t1) {} virtual void Print() const { cout<<*this<<endl;} friend ostream& operator<<(ostream& out, const A<T>& a) { ...
You can also use this->t to access the base class template member. In B::get(), the name t is not dependent on the template parameter T, so it is not a dependent name. Base class A<T> is obviously dependent on the template parameter T and is thus a dependent base class. Nondependent names are not looked up in depende...
2,982,919
2,982,946
Loading and saving a class to a binary file
I don't know if this is possible but, I have a class and I'v made an instance of it. I also put things in it. It has vectors and other things. I was wondering if I could save its contents (the instance) to a binary file, then reload it and cast it in from the file. Thanks
Yes, sometimes, kinda... Serialization is a tricky problem. Don't solve it yourself (i.e. don't reinvent the wheel... plenty of smart people have already done this). What you've described works in a constrained environment: Your reading and writing machines have the same endianness. Your class contains data only wit...
2,982,985
2,983,012
Algorithm to zoom into mouse(OpenGL)
I have an OpenGL scene with a top left coordinate system. When I glScale it zooms in from (0,0) the top left. I want it to zoom in from the mouse's coordinate (relative to the OGL frame). How is this done? Thanks
I believe this can be done in four steps: Find the mouse's x and y coordinates using whatever function your windowing system (i.e. GLUT or SDL) has for that, and use gluUnProject to get the object coordinates that correspond to those window coordinates Translate by (x,y,0) to put the origin at those coordinates Scale ...
2,983,066
2,983,069
Rationale behind introducing protected access specifier
What was the rationale behind introducing protected access specifier in C++. An example would be helpful.
The protected access level is used when classes need to work together with their inheritors. For example, imagine an abstract Shape class that can report its area to the outside world. Different shapes, such as triangles, squares, and circles, are described differently (angle, side, radius) and calculate their areas di...
2,983,091
2,983,101
Templates and function overloading
If funciton overloading and templates serve more the less the same purpose then which one should we go for templates or function overloading and what are the corresponding benefits.
With overloaded functions, you have to explicitly write out each overload: int max(int x, int y) { return x > y ? x : y; } long max(long x, long y) { return x > y ? x : y; } char max(char x, char y) { return x > y ? x : y; } // etc. This is tedious, but can be beneficial if the function body needs to be different base...
2,983,146
2,983,211
Class templates and template class
Is there a difference between a class template and template class. If so what is it?
When both terms are used there is a very subtle difference. It is more linguistic than semantic, it depends on which word you are modifying. In short, a class template is a particular kind of template. Templates can define either classes or functions. A class template is a template that defines a class. See the differe...
2,983,182
2,983,185
New, delete, malloc, free
new and delete are said to be preprocessors while malloc and free are functions. What is meant by new and delete being preprocessors?
new and delete are C++ operators (like +, (), etc.) whereas malloc and free are (C) functions. Some operators (including new and delete) can be overloaded.
2,983,264
2,983,323
Will this SQL cause any problems?
I'm sure everyone knows the joys of concurrency when it comes to threading. Imagine the following scenario on every page-load on a noobily set up MySQL db: UPDATE stats SET visits = (visits+1) If a thousand users load the page at same time, will the count cause any issues? is this that table locking/row locking mecha...
You have two potential problems: Will you get the right answer? Will you get unreasonable locking, will your whole app go very slow or even deadlock. The right answer depends upon whether two users could compute (visit + 1) on the same value of visit. We can imagine that the database needs to do these actions: Rea...
2,983,270
2,983,334
Using a function with variable argument strings
I was playing around a bit with functions with variable arguments, and decided to make a function to create vectors with the arguments. My function for creating an int vector worked... vector<int> makeIntVector(int numArgs, ...) { va_list listPointer; va_start(listPointer, numArgs); vector<int> made; fo...
Attempting to pass a string as a varaidic parameter gives undefined behavior: "If the argument has a non-POD class type (clause 9), the behavior is undefined." (§5.2.2/7 of the standard).
2,983,278
2,983,333
Problem Initializing an Array Of Structs
I am trying to initialize the following array of the following struct, but my code isn't compiling. Can anybody help me out? The struct/array: struct DiningCarSeat { int status; int order; int waiterNum; Lock customerLock; Condition customer; DiningCarSeat(int seatNum) { char* tempLockN...
There are multiple issues here: These should both be pointers, since you are newing them in your constructor: Lock customerLock; Condition customer; You don't declare a type for seatNum: DiningCarSeat(seatNum) { You don't allocate memory for tempLockName or tempConditionName: char* tempLockName; sprintf(te...
2,983,289
2,983,296
syntax for calling virtual functions outside of the class?
what is the syntax for defining virtual functions outside the class body? class random{ public: random(int i = 0); virtual ~random(){}; virtual void print() const; protected: int id; }; is it? virtual void random::print() { } ?
Just: struct foo { virtual void bar(void) const; }; void foo::bar(void) const { } virtual only goes on the declaration.
2,983,315
2,983,336
Multiple Socket Connections
I need to write a server which accepts connections from multiple client machines, maintains track of connected clients and sends individual clients data as necessary. Sometimes, all clients may be contacted at once with the same message, other times, it may be one individual client or a group of clients. Since I need c...
Child processes are not nice, because you just move the goalpost. You will need to make your child processes communicate between each other, then you are back to the same problem. It is possible to use threads, but you will have other problems if your threads keep blocking on socket receive. select() (or poll() on newe...
2,983,341
2,983,381
What is a way to fill a multiline editbox with line of text
What im after is a greyed out editbox you see at the bottom of some programs. A list of results. Im having problems having the text properly formatted. so starting from scratch, how is it usually done? The filling of the half page sized editbox with text. one big long string with line breaks? Results->Text = System::Co...
.NET or WinAPI? Don't add too much tags. In Win32 dialog template, I use the following styles to create such editbox: Auto HScroll false, Auto VScroll false, Horizontal Scroll false, Multiline true, Read Only true, Vertical Scroll true. You can add new information by concatenating new text with existing. If you want ne...
2,983,383
2,983,465
destructor and copy-constructor calling..(why does it get called at these times)
I have the following code #include <iostream> using namespace std; class Object { public: Object(int id){ cout << "Construct(" << id << ")" << endl; m_id = id; } Object(const Object& obj){ cout << "Copy-construct(" << obj.m_id << ")" << endl; m_id = obj.m_id; } Object&...
Object v1(1); // Construct(1) Regular constructor call for an automatic stack variable (destroyed at the end of the function). cout << "( a )" << endl; // ( a ) Object v2(2); // Construct(2) Another constructor call. v2 = v1; // 2 = 1 The assignment operator is called because v2 was already created (we called the c...
2,983,418
2,983,509
C++ corrupt my thinking, how to trust auto garbage collector?
I use to program mainly with C/C++, that's make me dealing with pointers and memory management daily. This days I'm trying to develop using other tools, such as Java, Python and Ruby. The problem is that I keep thinking C++ style, I'm writing code as C++ usually written in almost every programming language, and the big...
One difference to bear in mind is that in C++ the destructor can be used to clean up any kind of resource, not just memory (i.e. RAII). In Java you have to explicitly close files, sockets, datastore connections etc in a try - finally block. If you put resource cleanup code in a Java finalize method then it may get ca...
2,983,558
2,983,579
Reuse C++ Header files
I have a Visual C++ solution with 2 projects AlgorithmA & AlgorithmB and both share a common header file RunAlgo.h with the class declaration. Each project in the solution has its own unique implementation for the header file. I am trying to compile a DLL out of the common header file RunAlgo.h and add reference to thi...
1 & 3: No, that doesn't make sense in C++. Libraries (dynamic or otherwise) are only used during linking. During compilation declarations must be visible to the compiler in source-code form. This is why, for example, you have to explicitly #include standard library headers in addition to linking against the standard li...
2,983,570
2,983,598
Can you recommend a full-text search engine?
Can you recommend a full-text search engine? (Preferably open source) I have a database of many (though relatively short) HTML documents. I want users to be able to search this database by entering one or more search words in my C++ desktop application. Hence, I’m looking for a fast full-text search solution to integ...
I have use with very success the dtSearch module. They have a dll, that you can use with your application to index just anything and do more than the one you ask. Note: Is not free. I do not see in question that you ask for free one, so I write my favor one. The dtSearch have inspire me and I create an indexer for my ...
2,983,708
3,028,901
Qt not displaying PNG images on Linux
I have a software written using Qt which is meant to work on both Windows and Linux. I use PNG images as icons for my QActions, embedded in a resource. I have the following tree directory: / resources/ icons.qrc image.png Here is the content of icons.qrc: <RCC> <qresource prefix="/resources" lang="fr"> ...
Actually, I found out what was wrong. It had nothing to do with being on Linux or Windows, it was due to the locale. My linux system is in english while my Windows is in french. Since the resources had the lang="fr" flag, nothing was shown on non-french OSes... A stupid mistake !
2,983,819
2,983,841
How initialize array of classes?
I have this class constructor: Pairs (int Pos, char *Pre, char *Post, bool Attach = true); How can I initialize array of Pairs classes? I tried: Pairs Holder[3] = { {Input.find("as"), "Pre", "Post"}, {Input.find("as"), "Pre", "Post"}, {Input.find("as"), "Pre", "Post"} }; Apparently it's not working, I als...
Call the constructor explicitly: Pairs Holder[3] = { Pairs(Input.find("as"), "Pre", "Post"), Pairs(Input.find("as"), "Pre", "Post"), Pairs(Input.find("as"), "Pre", "Post") };
2,984,148
2,984,218
Where does C++ really shine?
I know C and Python, and I'm moving toward another language for learning purposes. My problem is that I like to learn things with something to do (for example contributing to some project or do something amazing, not boring plain algebra). I would like to hear suggestions about the fields in which C++ shines and where ...
I will share which fields I use the language in and why I use the language over others. Perhaps you can decide if my reasons qualify as 'shines'. Which fields: Device drivers, file system drivers, GUI development, algorithm modules, protocols and communications, application frameworks, data manipulation, storage handl...
2,984,166
2,984,246
How to put/get INT to/from a WCHAR array?
how can I put a INT type variable to a wchar array ? Thanks EDIT: Sorry for the short question. Yes we can cast INT to a WCHAR array using WCHAR*, but when we are retrieving back the result (WCHAR[] to INT), I just realize that we need to read size of 2 from WCHAR array since INT is 4 BYTEs which is equal to 2 WCHARs. ...
Technically, the way you do it is unsafe due to strict aliasing and alignment. The safest and the most portable way would be to read chars one by one and combine them with bit shifts. While your code would work on a Windows PC, don't expect it to be portable or work for all compilers and compiler settings. Basic examp...
2,984,206
2,984,212
Is iterator being invalidated?
Is iterator invalidated after: string b "Some string"; auto beg_ = b.begin(); auto end_ = b.end(); b.erase(beg_);
Yes, but erase return a valid iterator you can use to continue in a loop : For the remaining members, the function returns an iterator of member type string::iterator referring to the character that now occupies the position of the first character erased, or, if no such character exists, returns end(). So...
2,984,211
2,990,232
Using custom coordinates with QGraphicsScene
I am experimenting with a WYSIWYG editor that allows a user to draw shapes on a page and the Qt graphics scene support seems perfect for this. However, instead of working in pixels I want all my QGraphicsItem objects to work in tenths of a millimetre but I don't know how to achieve this. For example: // Create a scene...
QGraphicsView::scale should do the job. But I prefer setting the transform. It gives me much more control over how the scene is displayed. But that's because I need things like rotation, flipping, etc. It also allow me to track what I did to the scene.
2,984,287
2,984,435
QTableWidget::itemAt() returns seemingly random items
I've just started using Qt, so please bear with me. When I use QTableWidget->getItemAt(), it returns a different item from if I used currentItemChanged and clicked the same item. I believe it's necessary to use itemAt() since I need to get the first column of whatever row was clicked. Some example code is below: Main...
Qt documenration says: QTableWidgetItem * QTableWidget::itemAt ( int ax, int ay ) const Returns the item at the position equivalent to QPoint(ax, ay) in the table widget's coordinate system, or returns 0 if the specified point is not covered by an item in the table widget. See also item(). So you should probably use i...
2,984,434
2,996,578
Small objects allocator
Has anybody used SmallObjectAllocator from Modern C++ Design by Andrei Alexandrescu in a big project? I want to implement this allocator but I need some opinions about it before using it in my project. I made some tests and it seems very fast, but the tests were made in a small test environment. I want to know how fast...
I suggest you ask Rich Sposato. He has done extensive work on Loki's small object allocator, including testing and benchmarks.
2,984,441
2,984,452
When to use () with classes?
This is really starting to confuse the hell out of me. When do I use them, when don't I? For example I was reading a .cpp on linked lists whose class declaration was: struct CarPart { long PartNumber; char Partname[40]; double UnitPrice; CarPart *next; }; class ListOfParts { int size; public: ...
Declaring an instance of ListOfParts class does not require () when allocating on the heap. Both forms are valid: ListOfParts *pPart1 = new ListOfParts(); ListOfParts *pPart2 = new ListOfParts; EDIT: As the commenters have pointed out, it makes a difference when initialising a POD type (however is's not relevant to yo...
2,984,505
2,987,159
simulating atm communication without atm switch
can anybody tell me how to make file descriptors behave like atm nodes in /dev directory. Since i dnt have atm switch to test my program, i have to test with normal files, is there any method to make special type of file descriptors that behave like atm nodes.
You can write a dummy device driver that simulates the behavior that you expect from your ATM switch. This dummy driver would then provide a device driver node in /dev/atmXYZ. Writing a minimal linux driver is not much work. See Linux Device Drivers, Third Edition http://lwn.net/Kernel/LDD3/ for the details. The link p...
2,984,693
2,984,731
Does Visual Studio 2008 use make utility?
I have checked in buid directory and have not found makefile there. How does Visual Studio 2008 buid the project? Does it use makefile?
The NMAKE utility has been distributed with Visual C++ since back when it was called Microsoft C/C++ Optimizing Compiler, and is very similar to Unix make. Previous versions of the IDE actually used NMAKE makefiles, but this isn't true anymore. You can write NMAKE makefiles yourself if you want, but it sounds like yo...
2,984,706
2,984,735
Special parameters for texture binding?
Do I have to set up my gl context in a certain way to bind textures. I'm following a tutorial. I start by doing: #define checkImageWidth 64 #define checkImageHeight 64 static GLubyte checkImage[checkImageHeight][checkImageWidth][4]; static GLuint texName; void makeCheckImage(void) { int i, j, c; for (i = 0; ...
It looks like from that code that you don't set any UVs. Edit: Does it make any difference using GL_MODULATE instead of GL_DECAL? (Am taking guesses here because I suspect the problem lies in code you haven't provided, or in gluTessVertex itself ...
2,984,729
2,984,816
C++ template overloading - wrong function called
template<typename T> T* Push(T* ptr); template<typename T> T* Push(T& ref); template<typename T, typename T1> T* Push(T1&& ref); I have int i = 0; Push<int>(i); But the compiler calls it ambiguous. How is that ambiguous? The second function is clearly the preferred match since ...
If i is an int, then the first isn't viable. Last two remain. Then, for deduction of i, the second and the third both yield the same function types for overload resolution (both int& as parameter). So you have to rely on partial ordering. However, partial ordering can't tell them apart. For a function call partial ord...
2,984,740
2,984,758
Error in creating template class
I found this vector template class implementation, but it doesn't compile on XCode. Header file: // File: myvector.h #ifndef _myvector_h #define _myvector_h template <typename ElemType> class MyVector { public: MyVector(); ~MyVector(); int size(); void add(ElemType s); ElemType getAt(int index); private: ElemTyp...
It's always a good idea to place your templates in a header file. That way you don't mess up the linker with multiple definitions of the same instantiations and such. And of course there's the circular inclusion :).
2,984,923
2,985,162
Drawing shapes with wxWidgets
I want to learn how to draw shapes with wxWidgets. Where do I start? In case there are multiple ways, I prefer ease of use over cross-platform compatibility. I'm a Windows user.
This is done by creating a wxPanel, connecting to the paint event, and using the DC provided in that paint event to draw various things. The DC has a number of drawing related functions. This will probably be using Windows GDI or something similar, which means performance probably won't be fantastic, but it should work...
2,985,004
2,985,062
Using Boost.Asio to get "the whole packet"
I have a TCP client connecting to my server which is sending raw data packets. How, using Boost.Asio, can I get the "whole" packet every time (asynchronously, of course)? Assume these packets can be any size up to the full size of my memory. Basically, I want to avoid creating a statically sized buffer.
typically, when you do async IO, your protocol should support it. one easy way is to prefix a byte array with it's length at the logical level, and have the reading code buffer up until it has a full buffer ready for parsing. if you don't do it, you will end up with this logic scattered all over the place (think about ...
2,985,034
2,985,069
GlGenTextures keeps returing 0's
I'm trying to generate textures like so: #define checkImageWidth 64 #define checkImageHeight 64 static GLubyte checkImage[checkImageHeight][checkImageWidth][4]; static GLubyte otherImage[checkImageHeight][checkImageWidth][4]; static GLuint texName[2]; void makeCheckImages(void) { int i, j, c; for (i = 0; i <...
Try calling glGetError. It should tell you in more detail what went wrong. In general, if an OpenGL function fails, the first thing you do should be to ask OpenGL why it failed. It knows, because it just tried to execute the function. It's much harder for us to guess at what might have gone wrong.
2,985,039
2,985,048
Pointer initialization
Sorry if this question has been asked before. On my search through SO I didn't find one that asked what I wanted to know. Basically, when I have this: typedef struct node { int data; node *node; } *head; and do node *newItem = new node; I am under the impression that I am declaring and reserving space, but no...
I am under the impression that I am declaring and reserving space, but not defining, a pointer to struct node, is that correct? No. You are declaring a pointer, allocating space on the stack for the pointer, and dynamically allocating storage for a node to it it. Don't confuse yourself by writing stuff like th...
2,985,058
2,985,295
Extremely big integer multiplication and addition
Greetings, I need to multiply two extremely long integer values stored in a text file (exported via GMP (MPIR, to be exact), so they can be any in any base). Now, I would usually just import these integers via the mpz_inp_str() function and perform the multiplication in RAM, however, these values are so long that I can...
I don't know if there is a library that supports this, but you could use GMP/MPIR on parts of each really big number (RBN). That is, start by breaking each RBN into manageable, uniformly sized chunks (e.g. 10M digit chunks, expect an undersized chunk for most significant digits, also see below). RBN1 --> A B C D ...
2,985,068
2,985,081
does memcpy params have to be of the same type?
I was reading that memcpy takes the number of bytes from a source location and adds it to a destination location. Does this mean that memcpy could possibly change datatype entirely ?? memcpy(DoubleOne, CharTwo, strlen(CharTwo)); considering that both values are empty still.
Yes, they dont have to. int test = 3; char dest[sizeof(int)]; memcpy(&dest[0], &test, sizeof(int)); Is valid c(++).
2,985,142
3,032,281
Exit code 3 (not my return value, looking for source)
Greetings, my program exits with the code 3. No error messages, no exceptions, and the exit is not initiated by my code. The problem occurs when I am trying to read extremely long integer values from a text file (the text file is present and correctly opened, with successful prior reading). I am using very large amo...
It appears this exit code was returned by MPIR(GMP) because it could not allocate a big amount of memory. It's a bit annoying that this was not in any of the documentation though.
2,985,173
2,985,186
Passing a template func. as a func. ptr to an overloaded func. - is there a way to compile this code?
Just a general c++ curiosity: This code below shouldn't compile because it's impossible to know which to instantiate: temp(const int&) or temp(const string&) when calling func(temp) - this part i know. What i would like to know is if there is anything i can do to the line marked PASSINGLINE to get the compiler to de...
func(temp<int>); There's no way to make the compiler infer the template argument, that is more succinct or clearer than just explicitly specifying it, in this case. Edit: The following code compiles without warning and produces the expected result: #include<iostream> #include<string> using std::string; using std::cout...
2,985,372
2,985,387
C++ - Where to code a member function for an inherited object
I have a few classes (heat, gas, contact, pressure) inheriting from a main one (sensor). I have a need to store them in a vector<Sensor *> (part of the specification). At some point in time, I need to call a function that indiscriminately stores those Sensor *. (also part of the specification, not open for discussion)...
You need to make it a pure virtual function, which you then implement in each of the derived classes. The implementation can be pretty simple: class sensor { .... virtual void storeSensor( ostream & os ) = 0; }; class heat : public sensor { .... void storeSensor( ostream & os ) { os << * this; } };...
2,985,449
2,985,471
Are compilers smart enough to detect a no-op function?
If I write a function like this: void doMaybeNothing() { #ifndef IM_LAZY doSomething(); #endif } Are modern compilers smart enough to detect a no-op function and optimize so that there are no cycles wasted? Or is there always a small performance impact?
Assuming the body of the function is available at compile-time or link-time (i.e., it's not in a dynamically linked library), most modern compilers should get rid of calls to functions that do nothing (if optimizations are enabled, of course). Effectively, this is just a form of inline expansion, which allows the body ...
2,985,461
2,985,712
Rich text edit control for C++?
I'm looking for a control to edit rich text. These are my requirements: Fast/lightweight Support for bulleted/numbered lists Colored text and highlighting Targeting Windows, but cross-platform would be a bonus Fine control over undo/redo and easy way to monitor what parts of the documents have changed All the other ...
My first choice would be Qt. From what I tested, it is the best toolkit around, and it is the only one I know that has all of your requirements. My second choice would be wxWidgets, but I didn't like its architecture and API very much.
2,985,478
3,026,066
How can I render 3d graphics in a directshow source filter
I need to render a simple texture mapped model as the output of a directshow source filter. The 3d rendering doesnt need to come from Direct3D, but that would be nice. OpenGL or any other provider would be fine assuming I can fit it into the context of the DirectShow source filter. visual studio 2008 c++
With direct3d I have found that you can call GetRenderTargetData from the d3d device to get you access to the raw image bytes that you can then copy into the source filters image buffer Here is example code of how to get the d3d render void CaptureRenderTarget(IDirect3DDevice9* pdev) { IDirect3DSurface9* pTargetSur...
2,985,492
2,985,503
What exactly are signals and slots in Qt?
I know how they work conceptually, but how are signals and slots implemented in the Qt framework? Qt Creator treats them as keywords, but are they simply a set of macros, or is a special pre-processor required before these source files can be compiled? In other words, if I use Qt's signal/slot features in my code, can...
Many features of Qt, including signals, require preprocessing the source using the Qt Meta-Object Compiler (MOC). If you use Qt's signals feature, you can compile your source code on any compiler and platform that is supported by Qt. If you need to compile on a platform not supported by Qt, you may be out of luck or a...
2,985,532
2,985,535
Overloading the == operator to compare two char[] using a string comparison
Can the == operator be overloaded so as to compare two char[] using a string comparison?
No; at least one parameter of an operator overload must be of class or enumeration type. char[] and char* are array and pointer types, which are not class or enumeration types.
2,985,571
2,985,578
Pass temporary object to function that takes pointer
I tried following code : #include<iostream> #include<string> using namespace std; string f1(string s) { return s="f1 called"; } void f2(string *s) { cout<<*s<<endl; } int main() { string str; f2(&f1(str)); } But this code doesn't compile. What I think is : f1 returns by value so it creates temporary, o...
The unary & takes an lvalue (or a function name). Function f1() doesn't return an lvalue, it returns an rvalue (for a function that returns something, unless it returns a reference, its return value is an rvalue), so the unary & can't be applied to it.
2,985,622
2,985,634
Making use of WCHAR as a CHAR?
GDI+ makes use of WCHAR instead of what the WinAPI allows which is CHAR. Usually I can do: char *str = "C:/x.bmp"; but how do I do this for wchar? I can't juse do wchar_t *file = "C:/x.bmp"; Thanks
wchar_t *file = L"C:/x.bmp"; L introduces a wide string. In Windows, it's customary to use macros that behave differently according to some preprocessor definitions. See http://msdn.microsoft.com/en-us/library/c426s321(VS.71).aspx You would write: _TCHAR *file = _TEXT("C:/x.bmp");
2,985,676
2,985,710
Setting Up OpenCV and .lib files
I have been trying to set up OpenCV for the past few days with no results. I am using Windows 7 and VS C++ 2008 express edition. I have downloaded and installed OpenCV 2.1 and some of the examples work. I downloaded CMake and ran it to generate the VS project files and built all of them but there with several errors...
If you're just getting started, you should probably grab the prebuilt libraries for OpenCV instead. It's OpenCV-2.1.0-win32-vs2008.exe from this page. Once you have that, there is really no setup. Just link to the (already built) lib files in any VS project you create, and make sure the OpenCV include directory is in t...
2,985,840
2,986,116
OpenGL texture misaligned on quad
I've been having trouble with this for a while now, and I haven't gotten any solutions that work yet. Here is the problem, and the specifics: I am loading a 256x256 uncompressed TGA into a simple OpenGL program that draws a quad on the screen, but when it shows up, it is shifted about two pixels to the left, with the ...
It sure looks like you are consuming the header twice (once in TGA::loadTGA and then again in LoadUncompressedTGA). But if that were the case then I'd think width, height, and bpp would all be radically wrong and it wouldn't look as correct as it does.
2,985,943
2,985,964
C++ MACRO that will execute a block of code and a certain command after that block
void main() { int xyz = 123; // original value { // code block starts xyz++; if(xyz < 1000) xyz = 1; } // code block ends int original_value = xyz; // should be 123 } void main() { int xyz = 123; // original value MACRO_NAME(xyz = 123) // the macro takes the code cod...
The cleanest way to do this is probably to use an RAII container to reset the value: // Assumes T's assignment does not throw template <typename T> struct ResetValue { ResetValue(T& o, T v) : object_(o), value_(v) { } ~ResetValue() { object_ = value_; } T& object_; T value_; }; used as: { ResetVal...
2,986,103
2,986,601
C++ constructor problem, values not being set
I'm new to C++ and I'm trying to figure out this problem I'm having with my constructor for one of my classes. What happens is... all my variables are initialized properly except two (health and type). #pragma once #include <irrlicht.h> #include <vector> #include <cassert> using namespace irr; using namespace core; us...
This lines: modelMap[id] = soldier; First default constructs the Model inside the map. The returned reference is then used with the assignment operator to copy the value of soldier into the value contained inside the map. To test if it is working try: Model soldier(id, model, SOLDIER); std::cout << "TYPE(" << soldier....
2,986,229
2,986,251
Is it good practice to use std::size_t all over the place?
Possible Duplicate: When to use std::size_t? I have a lot of constants in my code that are unsigned numbers, e.g. counters, frequency cutoffs, lengths, etc. I started using std::size_t for all of these, instead of int or unsigned int. Is that the right thing to do? I started it because the STL containers use it for...
std::size_t is the type to use for counting memory locations, like array lengths, the size of objects, etc. STL containers are using container_type::size_type, which will usually map to std::size_t, but isn't guaranteed to do so. If you need types for holding non-negative integrals which are not used for the above men...
2,986,306
2,986,331
Standard C++ method for validating a URLs format?
Is there a easy standards-compliant way to check if a URL string is a valid format? Either through a specific URL-type class or maybe someone could show me how to do a regex validation of it?
Nope, there isn't one. On windows, you could take a look at the IsValidURL() function
2,986,324
2,986,327
Float compile-time calculation not happening?
A little test program: #include <iostream> const float TEST_FLOAT = 1/60; const float TEST_A = 1; const float TEST_B = 60; const float TEST_C = TEST_A / TEST_B; int main() { std::cout << TEST_FLOAT << std::endl; std::cout << TEST_C << std::endl; std::cin.ignore(); return 0; } Result : 0 0.0166667 Tested on ...
In 1/60 Both of the operands are integers, so integer arithmetic is performed. To perform floating point arithmetic, at least one of the operands needs to have a floating point type. For example, any of the following would perform floating point division: 1.0/60 1.0/60.0 1/60.0 (You might choose to use 1.0f instea...
2,986,351
2,986,443
What's a good way to write XML in C++?
There are plenty of Libraries to parse XML, but it seems there aren't many good (?) ways to write XML in C++. Libraries I've been using so far: PugiXML: really lightweight, very straightforwarded API, but it seems to lack a way to write XML (Or I haven't found it yet) RapidXML: I don't have much experience with RapidX...
Xerces DOM Parser Xerces-C++ is a validating XML parser written in a portable subset of C++. Xerces-C++ makes it easy to give your application the ability to read and write XML data. A shared library is provided for parsing, generating, manipulating, and validating XML documents using the DOM, SAX, and SAX2 APIs. For ...
2,986,383
2,986,399
C++ - Implementing my own stream
Hello! My problem can be described the following way: I have some data which actually is an array and could be represented as char* data with some size I also have some legacy code (function) that takes some abstract std::istream object as a param and uses that stream to retrieve data to operate. So, my question is the...
If you're looking at actually creating your own stream, I'd look at the Boost.Iostreams library. It makes it easy to create your own stream objects.
2,986,570
2,986,602
C++ compiler maximum number of classes
In meta-programming number of classes grows quite fast. Is maximum number of classes modern compiler allows, for example g++, something to be concerned about? Thank you
I'd guess this question is best answered by the standard published by the C++ committee. But looking at this place, I can't see any upper limit on the number of classes although there is minimum quantity limit on many items (saying at least the given number of items of each type should be supported by the compiler but...
2,986,644
2,986,699
converting a timestring to a duration
At the moment I am trying to read in a timestring formatted and create a duration from that. I am currently trying to use the boost date_time time_duration class to read and store the value. boost date_time provides a method time_duration duration_from_string(std::string) that allows a time_duration to be created from...
From the documentation, it looks like you may want to try using the stream operators (operator<<, operator>>); error conditions are described at Date Time Input/Output. Alternately, I suppose you could validate the string before passing it in. Right offhand, it doesn't look like that particular method has any error han...
2,986,844
2,986,856
Reading Unicode files line by line C++
What is the correct way to read Unicode files line by line in C++? I am trying to read a file saved as Unicode (LE) by Windows Notepad. Suppose the file contains simply the characters A and B on separate lines. In reading the file byte by byte, I see the following byte sequence (hex) : FE FF 41 00 0D 00 0A 00 42 00 0...
std::wifstream exposes the wide character set to your program, which is typically UCS-2 on Windows and UTF-32 on Unix, but assumes that the input file is still using narrow characters. If you want it to behave using wide characters on disk, you need to use a std::codecvt<wchar_t, wchar_t> facet. You should just be able...
2,986,891
2,986,902
How to publicly inherit from a base class but make some of public methods from the base class private in the derived class?
For example, class Base has two public methods: foo() and bar(). Class Derived is inherited from class Base. In class Derived, I want to make foo() public but bar() private. Is the following code the correct and natural way to do this? class Base { public: void foo(); void bar(); }; class Derived : public...
Section 11.3 of the C++ '03 standard describes this ability: 11.3 Access declarations The access of a member of a base class can be changed in the derived class by mentioning its qualified-id in the derived class declaration. Such mention is called an access declaration. The effect of an access declarat...
2,986,974
2,986,985
Overloading stream insertion without violating information hiding?
I'm using yaml-cpp for a project. I want to overload the << and >> operators for some classes, but I'm having an issue grappling with how to "properly" do this. Take the Note class, for example. It's fairly boring: class Note { public: // constructors Note( void ); ~Note( void ); // public accessor...
The typical way to do this without violating encapsulation is to make the operator>> a friend function. There must have been a syntax problem with your declaration of a friend operator (not clear what exactly from the error message). I don't use YAML, but from your question the following is the jist of it: class Note{...
2,987,062
3,042,278
Configuring the GCC compiler switches in Qt, QtCreator, and QMake
I recently tried to use Qt Creator 1.3.2, Qt 4.6.2, and GCC 4.4.0 (32-bit version) on Windows 7 (64-bit) to compile an application using some of the experimental C++0x extensions and encountered the following (fatal) error: This file requires compiler and library support for the upcoming ISO C++ standard, C++0x. Thi...
It boils down to reading the manual. Instead of using CXXFLAGS in the .pro file, you need to use QMAKE_CXXFLAGS as in: main.cpp: #include <cinttypes> int main() { return 0; } main.pro: SOURCES += main.cpp QMAKE_CXXFLAGS += -std=c++0x
2,987,505
2,996,538
How can I modify the application file of an application that is currently running (on Linux)?
I have an application running called AppFS. This application has an ext2 filesystem just attached to the end of the file (it's positioned so that the application binary exists in a 1MB spacing area, followed by the ext2 data). Now I've got FUSE embedded in the program and I've managed to extract the filesystem out of ...
The solution to this problem was to rename the existing application name (to a location within a temporary directory) and to then move the new (generated) file back in it's place and apply the same umask / uid / gid that the old one had. Once it's moved, you can safely just unlink the running executable. It's a bit of...
2,987,524
2,987,542
Any high-level languages that can use c libraries?
I know this question could be in vain, but it's just out of curiosity, and I'm still much a newb^^ Anyways I've been loving python for some time while learning it. My problem is obviously speed issues. I'd like to get into indie game creation, and for the short future, 2d and pygame will work. But I'd eventually like ...
Python can call functions in dynamically loaded C libraries (.so in unix, .dll in Windows) using the ctypes module. There is also cython - a variation of python that compiles to C and can call C libraries directly. You can mix modules written in pure Python and cython. You may also want to look at the numerous 3D game...
2,987,741
2,987,748
What is the difference between bit shifting and arithmetical operations?
int aNumber; aNumber = aValue / 2; aNumber = aValue >> 1; aNumber = aValue * 2; aNumber = aValue << 1; aNumber = aValue / 4; aNumber = aValue >> 2; aNumber = aValue * 8; aNumber = aValue << 3; // etc. Whats is the "best" way to do operations? When is better to use bit shifting?
The two are functionally equivalent in the examples you gave (except for the final one, which ought to read aValue * 8 == aValue << 3), if you are using positive integers. This is only the case when multiplying or dividing by powers of 2. Bit shifting is never slower than arithmetic. Depending on your compiler, the a...
2,987,956
2,987,974
Copy constructor demo (crashing... case 2)
Please have a glance at this program: class CopyCon { public: char *name; CopyCon() { name = new char[20]; name = "Hai";//_tcscpy(name,"Hai"); } CopyCon(const CopyCon &objCopyCon) { name = new char[_tcslen(objCopyCon.name)+1]; _tcscpy(name,objCopyCon.name); } ~CopyCon() { if( name != NUL...
In the default constructor CopyCon() { name = new char[20]; name = "Hai";//_tcscpy(name,"Hai"); } you assign the address of a string literal to the pointer and in the destructor you call delete[] on it, that's undefined behavior. delete[] should only be called on addresses returned by new[]. When you ...
2,987,973
2,999,711
Problem with receiving data form serial port in c#?
hello i have problem with receiving data from serial port in c# in am inserting a new line operator at the end of data buffer. then i send this data buffer on serial port, after this my c# GUI receiver will take this data via Readline() function but it always give me raw data not the actual one how to resolve this prob...
Your question is a bit vague, but the ReadLine() method will return when the port receives a carriage return and line feed byte combination by default on Windows. Or \r\n, or 0x0d 0x0a if you prefer. If the 'buffer' you are sending in the fist place contains several messages delimited by \r\n, then ReadLine() will only...
2,988,066
2,988,077
Decorator pattern in C++
Can someone give me an example of the Decorator design pattern in C++ ? I have come across the Java version of it, but found it difficult to understand the C++ version of it (from the examples I found). Thanks.
Vince Huston Design Patterns, even though its layout is poor, has C++ implementation for most design patterns in the Gang of Four book. Click for Decorator. There isn't much difference with Java, except the manual memory handling that you'd better wrap with smart pointers :)
2,988,168
2,988,888
Where my memory is alloced, Stack or Heap, Can I find it at Run-time?
I know that memory alloced using new, gets its space in heap, and so we need to delete it before program ends, to avoid memory leak. Let's look at this program... Case 1: char *MyData = new char[20]; _tcscpy(MyData,"Value"); . . . delete[] MyData; MyData = NULL; Case 2: char *MyData = new char[20]; MyData = "Value";...
Is there a way to know where the pointer is pointing to heap or stack? You can know this only if you remember it at the point of allocation. What you do in this case is to store your pointers in smart pointer classes and store this in the class code. If you use boost::shared_ptr as an example you can do this: templat...
2,988,273
2,988,305
C++ pointer to objects
In C++ do you always have to initialize a pointer to an object with the new keyword? Or can you just have this too: MyClass *myclass; myclass->DoSomething(); I thought this was a pointer allocated on the stack instead of the heap, but since objects are normally heap-allocated, I think my theory is probably faulty? Pl...
No, you can have pointers to stack allocated objects: MyClass *myclass; MyClass c; myclass = & c; myclass->DoSomething(); This is of course common when using pointers as function parameters: void f( MyClass * p ) { p->DoSomething(); } int main() { MyClass c; f( & c ); } One way or another though, the poi...
2,988,347
2,988,366
Abstract class reference
Can i have a class Class Room{ ~Room(); virtual cost() =0; } Class Hotel{ map<int, Room> rooms; /* */ }; will my hotel become abstract ? Can it hold the list of concrete Room objects that are derived from Room ?
The code you have written is not valid C++. If you mean: class Room{ ~Room(); virtual int cost() =0; }; then yes, the class is abstract. You cannot then create a map like this: map <int, Room> rooms; but you can like this: map <int, Room *> rooms; Then assuming you have a class SingleRoom that is derived fro...
2,988,467
2,990,195
How to know coordinates in a real image from a scaled image
First of all thanks for your time reading my question :-) I have an original image (w': 2124, h': 3204) and the same image scaled (w: 512, h: 768). The ratio for width is 4.14 (rw) and the ratio for height is 4.17 (rh). I'm trying to know the coordinates (x', y') in the original image when I receive the coordinates in...
Or you can use QTransform::quadToQuad to create a transform and use it to map points, rects, lines, etc.: QVector<QPointF> p1; p1 << scaledRect.topLeft() << scaledRect.topRight() << scaledRect.bottomRight() << scaledRect.bottomLeft(); QVector<QPointF> p2; p2 << originalRect.topLeft() << originalRect.topRight() <<...
2,988,628
2,988,652
Inheritance vs specific types in Financial Modelling for cashflows
I have to program some financial applications where I have to represent a schedule of flows. The flows can be of 3 types: fee flow (just a lump payment at some date) floating rate flow (the flow is dependant of an interest rate to be determined at a later date) fixed rate flow (the flow is dependant of an interest rat...
Why do you actually need the dynamic casts? Make your flow subclasses implement the same interface polymorphically, then there is no need to cast anything. If they need very different inputs, you could try passing the different inputs as constructor parameters, thus clearing up the common interface. However, if you rea...
2,988,752
2,988,910
C++ finding pointer errors
I am currently on a project which has been buggy for a long while, now I suspect, among other things, that there is pointer errors in the code. The program is written in native C++ using COM and uses out-of-process COM servers. Can anybody give me some tips as how one would go about finding these errors? Is there spe...
I have a couple of suggestions here: How did you figure out there was a pointer error? Why don't you put it in the debugger and then see where the program crashes? That'd be a start. Put a watch on the offending variable(s). What makes you think something is messed up in the COM part of the code? On the contrary, I ...
2,988,964
2,988,982
C++ reference variable clarification
I think most would be surprised about the topic again, However I am referring to a book "C++ Common Knowledge: Essential Intermediate Programming" written by "Stephen C. Dewhurst". In the book, he quotes a particular sentence (in section under Item 5. References Are Aliases, Not Pointers), which is as below A refere...
You aren't binding ref to another object: when you do ref = k, it is as though you did i = k, which simply reassigned the value of i. In other words, you're calling i's operator=. Here's something that better demonstrates the idea: #include <iostream> int main() { std::ostream& stream = std::cout; stream = st...
2,989,016
2,989,024
Delete array of size 1
This is possibly a candidate for a one-line answer. I would like know it anyway.. I am writing a simple circular buffer and for some reasons that are not important for the question I need to implement it using an array of doubles. In fact I have not investiated other ways to do it, but since an array is required anyway...
If you allocate the memory with new T[x], you always delete it with delete[], even if x ≤ 1.
2,989,125
2,989,184
Using forward declarations for built in datatypes
I understand that wherever possible we shall use forward declarations instead of includes to speed up the compilation. I have a class Person like this. #pragma once #include <string> class Person { public: Person(std::string name, int age); std::string GetName(void) const; int GetAge(void) const; private:...
Since used string as std::string _name; //^^^^^^^^^ concrete member the whole structure of string would be needed, so the declaration must be needed. You must #include <string>. Declaration of string can be omitted possible if you write, e.g. std::string* _name; //^^^^^^^^^^ pointer or reference which you could ...
2,989,173
2,989,223
runtime error when calling a C++ dll from C# .NET windows application
I had a C# .NET windows application having C# user interface and all the code behind processing is done by calling C++ dll (C++ class library project) which is added as a reference to the C# project. However recently when I formatted my computer and again tried to run my project which was backed up, in visual studio 20...
It sounds like you have a missing dependency i.e. another dll that your C++ dll depends on, that is not present on your machine. You can use a utility like "Dependency Walker" to load your C++ dll on a machine where you have a problem, and it will point out any any missing dependencies. It is then a case of working out...
2,989,200
2,989,523
C++ Iterators and inheritance
Have a quick question about what would be the best way to implement iterators in the following: Say I have a templated base class 'List' and two subclasses "ListImpl1" and "ListImpl2". The basic requirement of the base class is to be iterable i.e. I can do: for(List<T>::iterator it = list->begin(); it != list->end(); i...
If you can get away with making List<T>::iterator non-virtual, then delegating the virtualness off add to List makes things simple: template<typename T> class List { virtual void add_assign(iterator& left, int right) = 0; public: class iterator { const List* list; const T* item; public:...
2,989,235
2,989,271
How to store an XML file content into a std::string or CString, at compilation time?
The XML contains symbols that the C++ may misinterpret (like the // in http://www.w3.org/2000/10/XMLSchema) I am wondering if you know about clean ways to include some hard-coded XML into a std::string or a CString, at compile time. (in deed I'm trying to encode an .xsd file for validating some xml input, because I don...
const char* XML_STRING = "<?xml version=\"1.0\"?><Test></Test>"; std::string aTestXmlStr(XML_STRING);
2,989,419
2,989,481
How can I programmatically find the IP address/netmask/gateway configured for a specific network device in Linux?
I would like to write a piece of code which checks, for each network device (e.g. eth0, lo, master devices) some statistics and configuration data about that device. I could find the statistics data (and most of the configuration data) in /sys/class/net/..., however, I couldn't find any C/C++ API or any entry in procfs...
There sure is using a struct of ifreq and ioctl() calls you can grab all interface information: Man page is here Ifreq manpage /* local interface info */ typedef struct{ char *iface; struct ether_addr hwa; struct in_addr ipa; struct in_addr bcast; struct in_addr nmask; ...
2,989,537
2,990,013
Deriving from streambuf without rewriting a corresponding stream
Some days ago, I decided that it would be fun to write a streambuf subclass that would use mmap and read-ahead. I looked at how my STL (SGI) implemented filebuf and realized that basic_filebuf contains a FILE*. So inheriting from basic_filebuf is out of the question. So I inherited from basic_streambuf. Then i wanted t...
Check out mapped_file in the Boost.Iostreams library. I've never used used it myself, but it seems like it might already do what you need. EDIT: Oops, reread your questions and I see you're doing this for fun. Perhaps you can draw inspiration from Boost.Iostreams?
2,989,713
2,993,774
Get drive type with SetupDiGetDeviceRegistryProperty
I would like to know whether i can get the drive information using the SP_DEVICE_INTERFACE_DETAIL_DATA's DevicePath my device path looks like below "\?\usb#vid_04f2&pid_0111#5&39fe81e&0&2#{a5dcbf10-6530-11d2-901f-00c04fb951ed}" also please tell me in the winapi they say "To determine whether a drive is a USB-type driv...
Probably what you are looking for you will be find here http://support.microsoft.com/kb/264203/en. Another link http://support.microsoft.com/kb/305184/en can be also interesting for you. UPDATED: Example from http://support.microsoft.com/kb/264203/en shows you how to use to determine whether USB-Drive is removable. You...
2,989,810
2,990,581
Which Cross Platform Preprocessor Defines? (__WIN32__ or __WIN32 or WIN32 )?
I often see __WIN32, WIN32 or __WIN32__. I assume that this depends on the used preprocessor (either one from visual studio, or gcc etc). Do I now have to check first for os and then for the used compiler? We are using here G++ 4.4.x, Visual Studio 2008 and Xcode (which I assume is a gcc again) and ATM we are using jus...
It depends what you are trying to do. You can check the compiler if your program wants to make use of some specific functions (from the gcc toolchain for example). You can check for operating system ( _WINDOWS, __unix__ ) if you want to use some OS specific functions (regardless of compiler - for example CreateProcess ...
2,990,051
2,992,149
Qt and finding partial matches in a QList
I have a struct viz: struct NameKey { std::string fullName; std::string probeName; std::string format; std::string source; } which are held in a QList: QList<NameKey> keyList; what I need to do is find an occurence in keyList of a partial match where the search is for a NameKey tha...
QList is compatible with STL. So you can use it with STL algorithm: struct NameKeyMatch { NameKeyMatch(const std::string & s1, const std::string & s2, const std::string & s3, const std::string & s4) : fullName(s1), probeName(s2), format(s3), source(s4) {} bool operator()(const NameKey & x) const { ...
2,990,055
2,990,108
does such a c++ tool exist? [I dont know what to call it]
I am going through the process of trying to figure out how a library of code works. I would like some sort of tool that would analyze the program that I run off of the library and tells me what functions are called in what order by each thread. Does such a tool exist? What google terms would I use to find such a progra...
I think a call graph may help you. Most profilers can generate a call graph after profiling. Profiling can also help you identified what code is being used most often. Another possibility is using a tool to generate sequence diagrams. This won't show you specifically what happened during runtime, but it will give a cle...
2,990,060
3,002,600
Qt - QPushButton text formatting
I have a QPushButton and on that I have a text and and icon. I want to make the text on the button to be bold and red. Looked at other forums, googled and lost my hope. Seems there is no way to do that if the button has an icon (of course if you don't create a new icon which is text+former icon). Is that the only way? ...
You really don't need to subclass to change the formatting of your button, rather use stylesheets e.g. QPushButton { font-size: 18pt; font-weight: bold; color: #ff0000; } Applying this to the button that you want to change will make the buttons text 18pt, bold and red. You can apply via widget->setStyleShe...
2,990,172
2,990,202
Is there a list of preprocessor defines for various operating systems (and versions)?
e.g. a mapping for Mac OS 10.6.3 aka Snow Leopard => __APPLE__ && __LP64__? Windows 7, Windows XP => __WIN32__ Linux => __LINUX__
Here you go: http://predef.sourceforge.net/
2,990,342
2,990,378
boost for each problem
std::map< std::string , std::string > matrix_int; typedef std::pair< std::string , std::string > lp_type; BOOST_FOREACH( lp_type &row, matrix_int ){ } this can not be complied: error C2440: 'initializing' : cannot convert from 'std::pair<_Ty1,_Ty2>' to 'lp_type &' when I have ',' in element type, boost doc says I can...
Your typedef is incorrect; it needs to be: typedef std::pair< const std::string , std::string > lp_type; ^ note the added const The key element in the map pair is const-qualified. It would be a bit cleaner to use the value_type typedef; this way you don't repeat the type information: typedef std::...
2,990,717
2,991,005
C++'s unordered_map / hash_map / Google's dense_hash - how to input binary data (buf+len) and insert operation
I have two questions about Google's dense_hash_map, which can be used instead of the more standard unordered_map or hash_map: How do I use an arbitrary binary data memory segment as a key: I want a buffer+length pair, which may still contain some NUL (\0) characters. I can see how I use a NUL-terminated char * string ...
I would disagree with Neil. I would use insert for number 2. Using find then insert causes 2 look-ups while using insert causes one look-up without overriding if the element is already present. Normally, insert returns an iterator to the key/value pair corresponding (even if not updated) + a boolean which indicates whe...