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,751,316
2,751,340
Boost lambda: Invoke method on object
I'm looking at boost::lambda as a way to to make a generic algorithm that can work with any "getter" method of any class. The algorithm is used to detect duplicate values of a property, and I would like for it to work for any property of any class. In C#, I would do something like this: class Dummy { public String ...
Assuming, I understand what you're looking for, you can use boost::bind: FindNonUniqueValues<Dummy>(boost::bind(&Dummy::GetId, _1)); Actually, you just need boost::mem_fn or even std::mem_fun, but boost::bind will allow you a bit more generality. In this case, you would define FindNonUniqueValues as something like: te...
2,751,458
2,751,509
Fibonacci Function Question
I was calculating the Fibonacci sequence, and stumbled across this code, which I saw a lot: int Fibonacci (int x) { if (x<=1) { return 1; } return Fibonacci (x-1)+Fibonacci (x-2); } What I don't understand is how it works, especially the return part at the end: Does it call the Fibonacci functi...
Yes, the function calls itself. For example, Fibonacci(4) = Fibonacci(3) + Fibonacci(2) = (Fibonacci(2) + Fibonacci(1)) + (Fibonacci(1) + Fibonacci(0)) = ((Fibonacci(1) + Fibonacci(0)) + 1) + (1 + 1) = ((1 + 1) + 1) + 2 = (2 + 1) + 2 = 3 + 2 = 5 Note that the Fibonacci function is called 9 times here. In general, th...
2,751,487
2,751,749
Why there is no scoped locks for multiple mutexes in C++0x or Boost.Thread?
C++0x thread library or Boost.thread define non-member variadic template function that lock all lock avoiding dead lock. template <class L1, class L2, class... L3> void lock(L1&, L2&, L3&...); While this function avoid help to deadlock, the standard do not includes the associated scoped lock to write exception safe ...
I think that by providing defer_lock_t (and adopt_lock_t) the expectation is that usage will be like your second example, or probably more like: std::unqiue_lock ul1(l1, std::deferred); std::unique_lock ul2(l2, std::deferred); std::lock(ul1, ul2); This is exception safe and all that good stuff. I certainly can't pr...
2,751,528
2,751,611
Scope quandary with namespaces, function templates, and static data
This scoping problem seems like the type of C++ quandary that Scott Meyers would have addressed in one of his Effective C++ books. I have a function, Analyze, that does some analysis on a range of data. The function is called from a few places with different types of iterators, so I have made it a template (and thus i...
You could use a class with a static member to hold the data if it's really important that nothing but specializations of your function template can access the data. class AnalysisTable { static const int data[]; template <typename InputIterator> friend int Analyze(InputIterator begin, InputIterator end); }...
2,751,670
2,751,699
What does this C++ construct do?
Somewhere in lines of code, I came across this construct... //void* v = void* value from an iterator int i = (int)(long(v)) What possible purpose can this contruct serve? Why not simply use int(v) instead? Why the cast to long first?
It most possibly silences warnings. Assuming a 32bit architecture with sizeof(int) < sizeof(long) and sizeof(long) == sizeof(void *) you possibly get a warning if you cast a void * to an int and no warning if you cast a void * to a long as you're not truncating. You then get a warning assigning a long to an int (possib...
2,751,761
2,751,785
Polygonal gradients with OpenGL
I'm wondering how I could create a gradient wuth multiple stops and a direction if I'm making polygons. Right now I'm creating gradients by changing the color of the verticies but this is limiting. Is there another way to do this? Thanks
One option you may have is to render a simple polygon with a gradient to a texture, which you then use to texture your actual polygon. Then you can rotate the source polygon and anything textured with its image will have its gradient rotate as well, without the actual geometry changing.
2,751,819
2,751,893
How do I make Boost multithreading?
I am trying to compile the latest Boost c++ libraries for Centos. I 've used bjam install and it has placed the libraries in /usr/lib and /usr/lib64. The problem is I need the -mt variants for a specific application to run. I cannot understand in the documentation how to create the multithreading variants. :( Please gi...
-mt is just distribution specific extension. either edit your config file or create symbolic link to libboost_thread andrey@localhost:~$ ls -l /usr/lib/libboost_thread* -rw-r--r-- 1 root root 174308 2010-01-25 10:36 /usr/lib/libboost_thread.a lrwxrwxrwx 1 root root 41 2009-11-04 10:10 /usr/lib/libboost_thread-gcc41...
2,751,820
2,751,962
Download File from Web C++ (with winsock?)
I need to download files/read strings from a specified url in C++. I've done some research with this, cURL seems to be the most popular method. Also, I've used it before in PHP. The problem with cURL is that the lib is huge, and my file has to be small. I think you can do it with winsock, but I can't find any simple ex...
I can repeat me answer Is it possible to handle proxies at socket level? (see also comments) about two important interfaces Windows Internet (WinINet) API and Windows HTTP Services (WinHTTP). An important restriction of WinINet is that WinINet should be not used in a service (only in GUI app.) because of possible dialo...
2,751,874
2,751,914
Make openGL lines connected
Right now I'v created a polygon, then I do the same thing but with line_loop to draw the outline. My issue right now is if I set the line thickness to high, the lines arn't connected. Their ends would need to be (linewidth) longer... is there a way to fix this? Thanks glMatrixMode (GL_PROJECTION); glLoadIdenti...
The article here shows how to achieve rounded line caps and antialised lines using a texture trick.
2,751,900
2,752,609
Why timed lock doesn't throw a timeout exception in C++0x?
C++0x allows to lock on a mutex until a given time is reached, and return a boolean stating if the mutex has been locked or not. template <class Clock, class Duration> bool try_lock_until(const chrono::time_point<Clock, Duration>& abs_time); In some contexts, I consider an exceptional situation th...
Can't you just check the return value and throw your own exception? if ( ! my_lock.try_lock_until( my_start_time ) ) { throw realtime_error( "Couldn't start in time!" ); } Also, a quick look through the threading and exceptions libraries in the FCD doesn't show any time-related exception classes, so there's no typ...
2,752,006
2,752,080
Generate texture from polygon (openGL)
I have a quad and I would like to use the gradient it produces as a texture for another polygon. glPushMatrix(); glTranslatef(250,250,0); glBegin(GL_POLYGON); glColor3f(255,0,0); glVertex2f(10,0); glVertex2f(100,0); glVertex2f(100,100); glVertex2f(50,50); glVertex2f(0,100); glEnd(); //End quadrilateral c...
Keep it simple! It is very simple to create a gradient texture in code, e.g.: // gradient white -> black GLubyte gradient[2*3] = { 255,255,255, 0,0,0 }; // WARNING: check documentation, I am not quite sure about syntax and order: glTexture1D( GL_TEXTURE_1D, 0,3, 2, 0, GL_RGB, GL_UNSIGNED_BYTE, gradient ); // setup te...
2,752,144
2,752,179
Why doesn't this for-loop execute?
I'm writing a program for an exercise that will read data from a file and format it to be readable. So far, I have a bit of code that will separate a header from the data that goes under it. Here it is: int main() { ifstream in("records.txt"); ofstream out("formatted_records.txt"); vector<string> temp; ...
If the loop still doesn't run after ensuring that you're reading into a valid string reference, then you should check that the stream you're reading from is valid. The stream will be invalid if the file doesn't exist or if you lack permission to read it, for instance. When the stream isn't valid, getline won't read any...
2,752,175
2,752,271
Getting the vector points of a letter in a truetype font
Since True Type fonts are just vectors, I was wondering if there was a way to get the vectors (array of points) for a letter given that i'm using the WinAPI. Thanks
Use the GetGlyphOutline function with the GGO_NATIVE option. http://msdn.microsoft.com/en-us/library/dd144891%28v=VS.85%29.aspx Actually, True Type fonts are defined by Bezier curves, not vectors, so you get back a list of curves. Most graphics libraries have a way of drawing Bezier curves anyway so you can get by jus...
2,752,229
2,774,591
F# performance in scientific computing
I am curious as to how F# performance compares to C++ performance? I asked a similar question with regards to Java, and the impression I got was that Java is not suitable for heavy numbercrunching. I have read that F# is supposed to be more scalable and more performant, but how is this real-world performance compares ...
F# does floating point computation as fast as the .NET CLR will allow it. Not much difference from C# or other .NET languages. F# does not allow vector instructions by itself, but if your CLR has an API for these, F# should not have problems using it. See for instance Mono. As far as I know, there is only one F# compi...
2,752,295
2,752,304
C++ LPTSTR to int (but memory overwrite problem using atoi)
I have the following code, m_edit is a MFC CEdit (I know I would never use MFC but project demanded it). It's a simple loop, that gets the text from a text edit, converts it to integer after getting the first line, then stores it in m_y vector. LPTSTR szTemp; vector<int> m_y; for(int i = 0; i < m_edit->GetLineCount()...
From the MFC CEdit::GetLine documentation: Remarks: The copied line does not contain a null-termination character. So you need to pay attention to GetLine's return value to determine how many bytes were copied into the buffer and then add your own NUL-terminator. Also, I would recommend that you pass in the buffer ...
2,752,349
2,752,387
Fast rectangle to rectangle intersection
What's a fast way to test if 2 rectangles are intersecting? A search on the internet came up with this one-liner (WOOT!), but I don't understand how to write it in Javascript, it seems to be written in an ancient form of C++. struct { LONG left; LONG top; LONG right; LONG bottom; } RECT; ...
This is how that code can be translated to JavaScript. Note that there is a typo in your code, and in that of the article, as the comments have suggested. Specifically r2->right left should be r2->right < r1->left and r2->bottom top should be r2->bottom < r1->top for the function to work. function intersectRect(r1, r2)...
2,752,469
2,752,476
Help with these warnings. [inheritance]
I have a set of code, which mimics a basic library cataloging system. There is a base class named items, in which the the general id,title and year variables are defined and 3 other derived classes (DVD,Book and CD). Base [Items] Derived [DVD,Book,CD]. The programs runs, however I get the following warnings, I'm not su...
When you declare member variables in a class, they're initialized in the order you declare them. But you may write them in any order in your constructor's initializer list. For example, struct foo { int a; int b; foo(): b(5), a(3) {} }; will construct a and then b, even though it appears that you're initiali...
2,752,499
2,752,512
floating exception using icc compiler
I'm compiling my code via the following command: icc -ltbb test.cxx -o test Then when I run the program: time ./mp6 100 > output.modified Floating exception 4.871u 0.405s 0:05.28 99.8% 0+0k 0+0io 0pf+0w I get a "Floating exception". This following is code in C++ that I had before the exception and after: // befor...
You are almost certainly dividing by zero in foo. A simple program of int main() { int bad = 0; return 25/bad; } also prints Floating point exception on my system. So, you should check whether e is 0 when s % 4 is zero, or whether t is 0 when s % 4 is 2 or 3. Then return whatever value makes sense for you...
2,752,549
2,752,558
Why can't I pass const map structure to a function in c++?
I tried to pass const with vector it works: Ex: void damn(const vector <bool> &bb) { for (int i=0; i<bb.size(); i++) cout<<bb[i]<<endl; } But when trying with map, it does not: void pas(const map <string, float> &mm) { cout<<mm["a"]; cout<<mm["b"]; } I wonder why it doesn't.
I believe that it is because [] in map isn't const, as it creates new pair with default value, if you address to nonexisting one. Try void pas(const map <string, float> &mm) { cout<<mm.find("a")->second; cout<<mm.find("b")->second; }
2,752,869
2,752,883
How to remove an item from a structure array in C++?
I have the following array structure (linked list): struct str_pair { char ip [50] ; char uri [50] ; str_pair *next ; } ; str_pair *item; I know to create a new item, I need to use item = new str_pair; However, I need to be able to loop through the array and delete a ...
What you've shown is not an array of struct, but a linked list of struct containing arrays (of type char). An array of struct would look like this: str_pair array_of_structs[10]; // or: str_pair* dynamically_allocated_array_of_structs = new str_pair[10]; If you actually have something like this, you don't need to...
2,752,893
2,753,091
Is there a way to implement OnReady() callback in Qt4?
I want to do something which will access network when a QMainWindow is ready. I suppose I should not do it in the constructor, so I try to find a signal the widget will get and try to implement something like a OnReady() call back in other UI library. But I still can not find a way to do this. Thanks a lot in advance.
If I understand correctly, you need to do something as soon as the application's event loop is ready to process events. The reason you can't do it in the constructor because the application's event loop isn't ready until some time after the constructor has finished running. What you can do is create a slot in your Main...
2,752,925
2,752,954
how to write any custom data type to file using ifstream?
as question says, i want to write custom data type data of a class maybe to a file using ifstream in c++. Need help.
For an arbitrary class, say, Point, here's a fairly clean way to write it out to an ostream. #include <iostream> class Point { public: Point(int x, int y) : x_(x), y_(y) { } std::ostream& write(std::ostream& os) const { return os << "[" << x_ << ", " << y << "]"; } private: int x_, y_; }...
2,752,974
2,752,994
Invoking MSYS bash from Windows cmd
I'm using GCC on Windows 7 (using the TDM's build). I installed MSYS to be able to execute Make and compile using makefiles. However, it is tedious to every time start up the MSYS Bash shell, navigate to the directory of the project and run make. What I want is to automate this process. I prefer to have a batch file in...
Not an MSYS expert, but does something like this work for you: rem Call this something like compile-project.bat c: cd \src\project bash -c "make"
2,752,987
2,752,996
C++ macros explanation
Can somebody explain the following code please? #if 1 // loop type #define FOR_IS_FASTER 1 #define WHILE_IS_FASTER 0 // indexing type #define PREINCREMENT_IS_FASTER 1 #define POSTINCREMENT_IS_FASTER 0 #else // loop type #define FOR_IS_FASTER 1 #define WHILE_IS_FASTER 0 // indexing type #define PREINCREMENT_IS_FASTER...
The #if 1 triggers the first group of #defines, which set PREINCREMENT_IS_FASTER to 1. Because of this, #if PREINCREMENT_IS_FASTER triggers the first #define ZXP.... There is nothing exceptional about 1 and 0 in this context. The #if preprocessor directive succeeds if its argument is non-zero. You can switch to the alt...
2,752,999
2,753,020
How do I define an implicit typecast from my class to a scalar?
I have the following code, which uses a Unicode string class from a library that I'm writing: #include <cstdio> #include "ucpp" main() { ustring a = "test"; ustring b = "ing"; ustring c = "- -"; ustring d; d = "cafe\xcc\x81"; printf("%s\n", (a + b + c[1] + d).encode()); } The encode method of the ustring c...
First, I would recommend that you consider not providing an implicit conversion. You may find that the situations where unexpected conversions are not caught as errors outweighs the cost of calling encode when you want a char*. If you do decide to provide an implicit conversion you declare it like this (inside your cla...
2,753,060
2,753,099
Who architected / designed C++'s IOStreams, and would it still be considered well-designed by today's standards?
First off, it may seem that I'm asking for subjective opinions, but that's not what I'm after. I'd love to hear some well-grounded arguments on this topic. In the hope of getting some insight into how a modern streams / serialization framework ought to be designed, I recently got myself a copy of the book Standard C++...
Several ill-conceived ideas found their way into the standard: auto_ptr, vector<bool>, valarray and export, just to name a few. So I wouldn't take the presence of IOStreams necessarily as a sign of quality design. IOStreams have a checkered history. They are actually a reworking of an earlier streams library, but were ...
2,753,197
2,755,211
Any free memory leak detector for Qt?
I'm looking for free memory leak detector for Qt. I use Qt Creator 1.3 with Qt version 4.6 (32 bit). The platform is Windows 7 Ultimate. Thanks.
Although this question is not Qt-specific, the answers do refer to various general-purpose memory leak detection tools which are available on Windows. The two which are mentioned in the accepted answer are commercial tools, but there are some free alternatives referred to in other answers.
2,753,349
2,753,357
C++ Class Static variable problem - C programmer new to C++
I am a C programmer, but had learnt C++ @school longtime back. Now I am trying to write code in C++ but getting compiler error. Please check and tell me whats wrong with my code. typedef class _filter_session { private: static int session_count; /* Number of sessions count -- Static */ public: _filter_sess...
static variables need to be defined outside of the class body somewhere. The declaration inside the class body is just a declaration. E.g. at global scope: int _filter_session::session_count; You need to ensure that this definition occurs only once in the program so usually you would place it in a source file (.cc or ...
2,753,381
2,753,637
Performance of vector::size() : is it as fast as reading a variable?
I have do an extensive calculation on a big vector of integers. The vector size is not changed during the calculation. The size of the vector is frequently accessed by the code. What is faster in general: using the vector::size() function or using helper constant vectorSize storing the size of the vector? I know that ...
Interesting question. So, what's going to happened ? Well if you debug with gdb you'll see something like 3 member variables (names are not accurate): _M_begin: pointer to the first element of the dynamic array _M_end: pointer one past the last element of the dynamic array _M_capacity: pointer one past the last elemen...
2,753,590
2,753,657
signature output operator overload
do you know, how to write signature of a function or method for operator<< for template class in C++? I want something like: template <class A> class MyClass{ public: friend ostream & operator<<(ostream & os, MyClass<A> mc); } ostream & operator<<(ostream & os, MyClass<A> mc){ // some code return os; } But t...
All the below said, if you don't need an operator to be a friend, then don't make it a friend. For output operators in particular, in my opinion you should not make them friends. That is because if your class can be output to a stream, it should have equivalent get functions that provide the same data programmatically....
2,753,670
2,753,723
What's the best way to resolve this scope problem?
I'm writing a program in python that uses genetic techniques to optimize expressions. Constructing and evaluating the expression tree is the time consumer as it can happen billions of times per run. So I thought I'd learn enough c++ to write it and then incorporate it in python using cython or ctypes. I've done some ...
The Node object returned by make_tree() is just a temporary object, it will automatically be destroyed again at the end of the expression in which the function is called. When you create a pointer to such a temporary object, like in &make_tree(depth), this pointer will not point to anything useful anymore once the temp...
2,753,774
2,753,823
C++: Help with cin difference between Linux and Windows
I have a Win32 console program that I wrote and it works fine. The program takes input from the user and performs some calculations and displays the output - standard stuff. For fun, I am trying to get the program to work on my Fedora box but I am running into an issue with clearing cin when the user inputs something t...
I think it's a bad idea to use formatted input to read user responses. I'd use getline - something like this: #include <iostream> #include <string> #include <sstream> using namespace std; template <typename T> bool Read( T & t, istream & is ) { string s; if ( ! getline( is, s ) ) { return false; } ...
2,753,857
2,753,933
is there a simple timed lock algorithm avoiding deadlock on multiple mutexes?
C++0x thread library or Boost.thread define a non-member variadic template function that locks all mutex at once that helps to avoid deadlock. template <class L1, class L2, class... L3> void lock(L1&, L2&, L3&...); The same can be applied to a non-member variadic template function try_lock_until, which locks all the ...
The classic (and best) approach is to define an order in which mutexes are to be locked, and make sure that any code that holds more than one locked mutex at a time always locks its mutexes in that order. Is that approach insufficient here?
2,753,996
2,761,450
Is there a way to access the locale used by gettext under windows?
I have a program where i18n is handled by gettext. The program works fine, however for some reason I need to know the name of the locale used by gettext at runtime (something like 'fr_FR') under win32. I looked into gettext sources, and there is a quite frightening function that computes it on all platforms (gl_locale_...
Turns out the "gl_locale_name" function was not part of gettext directly, but rather part of gnulib - http://www.gnu.org/software/gnulib. I just discovered the package today. So getting the infamous localename.h header in my project was a matter of gnulib-tool --import localename Then the gl_locale_name function wor...
2,754,073
2,757,463
Writing a program which uses voice recogniton... where should I start?
I'm a design student currently dabbling with Arduino code (based on c/c++) and flash AS3. What I want to do is to be able to write a program with a voice control input. So, program prompts user to spell a word. The user spells out the word. The program recognizes if this is right, adds one to a score if it's correct, ...
What you need is most likely not a speech recognition program. You are looking for a speech recognition library. You're probably not that familiar with programming yet, so the term may be unfamiliar. Basically, a library is an intermediate step between source code and a whole program. In your case, you are really aski...
2,754,150
2,754,156
+= Overloading in C++ problem
I am trying to overload the += operator for my rational number class, but I don't believe that it's working because I always end up with the same result: RationalNumber RationalNumber::operator+=(const RationalNumber &rhs){ int den = denominator * rhs.denominator; int a = numerator * rhs.denominator; int b =...
operator+= is supposed to modify the object itself and return a reference. You are instead creating a new object and returning that. Something like this might work (untested code): RationalNumber &RationalNumber::operator+=(const RationalNumber &rhs){ int den = denominator * rhs.denominator; int a = numerator *...
2,754,152
2,754,253
Question about Virtual Inheritance hierarchy
I encounter this problem when tackling with virtual inheritance. I remember that in a non-virtual inheritance hierarchy, object of sub-class hold an object of its direct super-class. What about virtual inheritance? In this situation, does object of sub-class hold an object of its super-class directly or just hold a poi...
The virtual base object is somewhere in the memory block that belongs to the object (the memory with size = sizeof(object)). Because several sub objects of different types can be combined in various ways but must share the same base object, a offset pointer is needed for each sub object to find out the virtual base obj...
2,754,176
2,754,201
Virtual class problem
What i think about virtual class is, if a derived class has a public base, let's say, class base, then a pointer to derived can be assigned to a variable of type pointer to base without use of any explicit type conversion. But what if, we are inside of base class then how can we call derived class's functions. I will g...
It can't be done. Virtual functions cannot be called whithin constructors -- at least they cannot be called with virtual behavior. The problem is that the derived class constructor is responsible for setting up the vtbl to point to it's particular instance of the virtual functions. The base class' constructor is execut...
2,754,235
2,847,296
Lua + SWIG Monkey Patching
I have used SWIG to bind a set of classes to lua. I know C++ itself doesn't support monkey patching, and I'm not trying to modify my C++ objects, merely their lua representations. The problem comes if I want to start monkey patching the lua tables and objects exported by SWIG, so that I can modify the API presented on ...
I've successfully monkeypatched lua userdata by adding and replacing existing methods. It involved modifying their metatables. Here's a sample of what I had to do in order to add a couple methods to an existing userdata object. As you can see, instead of modifying the object iself, I had to modify its metatable. This s...
2,754,342
2,754,468
printing double in binary
In 'Thinking in C++' by Bruce Eckel, there is a program given to print a double value in binary. (Chapter 3, page no. 189) int main(int argc, char* argv[]) { if(argc != 2) { cout << "Must provide a number" << endl; exit(1); } double d = atof(argv[1]); unsigned char* cp = reinterpret_cast...
A1: Yes, it would be undefined behaviour when it accesses cp[8]. A2: Yes, it also does not print cp[0]. As shown, it prints bytes 7, 8, 5, 6, 3, 4, 2, 1 of the valid values 0..7. So, if you have copied the code correctly from the book, there is a bug in the book's code. Check the errata page for the book, if there is...
2,754,386
2,754,409
Using delete[] (Heap corruption) when implementing operator+=
I've been trying to figure this out for hours now, and I'm at my wit's end. I would surely appreciate it if someone could tell me when I'm doing wrong. I have written a simple class to emulate basic functionality of strings. The class's members include a character pointer data (which points to a dynamically created c...
Following chunk of code makes p pointed beside the array. while (*p++ = *q++) ; *p = '\0'; Better (and safe) solution you have used in copy constructor: while (*q) *p++ = *q++; *p = '\0';
2,754,586
2,754,592
Reading function pointer syntax
Everytime I look at a C function pointer, my eyes glaze over. I can't read them. From here, here are 2 examples of function pointer TYPEDEFS: typedef int (*AddFunc)(int,int); typedef void (*FunctionFunc)(); Now I'm used to something like: typedef vector<int> VectorOfInts ; Which I read as typedef vector<int> /* as *...
The actual type of the first one is int (*)(int,int); (that is, a pointer to a function that takes two parameters of type int and returns an int) The * identifies it as a function pointer. AddFunc is the name of the typedef. cdecl can help with identifying particularly complex type or variable declarations.
2,754,600
2,754,639
Use C function in C++ program; "multiply-defined" error
I am trying to use this code for the Porter stemming algorithm in a C++ program I've already written. I followed the instructions near the end of the file for using the code as a separate module. I created a file, stem.c, that ends after the definition and has extern int stem(char * p, int i, int j) ... It worked fine...
That error means that the symbol (stem) is defined in more than one module. You can declare the symbol in as many modules as you want. A declaration of a function looks like this: int stem(char * p, int i, int j); You don't need the "extern" keyword, although it doesn't hurt anything. For functions declarations, it'...
2,754,650
2,754,656
Getting value of std::list<>::iterator to pointer?
How can i loop thru a stl::List and store the value of one of the objects for use later in the function? Particle *closestParticle; for(list<Particle>::iterator p1 = mParticles.begin(); p1 != mParticles.end(); ++p1 ) { // Extra stuff removed closestParticle = p1; // fails to compile (edit from co...
Either Particle *closestParticle; for(list<Particle>::iterator it=mParticles.begin(); it!=mParticles.end(); ++it) { // Extra stuff removed closestParticle = &*it; } or list<Particle>::iterator closestParticle; for(list<Particle>::iterator it=mParticles.begin(); it!=mParticles.end(); ++it ) ...
2,754,673
2,754,732
Drawing connected lines with OpenGL
I'm drawing convex polygons with OpenGL. I then do the same thing but use GL_LINE_LOOP. The problem I have is the lines are not always connected. How could I ensure that the lines are always connected? In the photo below, Iv highlighted in green, the corners that are connected and in red, those that are not. I would li...
What you're looking for is called endpoint capping / mitering. OpenGL doesn't support this natively, see 14.100 Using wide lines (line width 50) amplifies the problem. You might want to try using OpenGL tesselation. This example might seem a bit much, but I think there is some valuable interfacing between Java2D shapes...
2,754,707
2,754,974
Moving from Windows to Ubuntu
I used to program in Windows with Microsoft Visual C++ and I need to make some of my portable programs (written in portable C++) to be cross-platform, or at least I can release a working version of my program for both Linux and Windows. I am total newcomer in Linux application development (and rarely use the OS itself)...
How can I execute my compiled linux programs externally (outside IDE)? In Windows, I simply run the generated executable (.exe) file On Linux you do the same. The only difference is that on Linux the current directory is by default not in PATH, so typically you do: ./myapp If you add current dir to the path PA...
2,754,925
2,754,951
C++ User-Defined Vector
How do you declare a vector in c++ while allowing user input to define the vector's name? Okay, after reviewing your responses, here is more detail; Here is the error message from VS08 C++ console application - Error 2 error C2664: 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::get(_Elem *,std...
You want to have users give you a name and to be able to associate that with a vector of things? That's what a std::map is for, with a std::string as the key type and a std::vector as the payload type.
2,755,242
3,328,899
Passing around objects to network packet handlers?
I've been writing a networking server for a while now in C++ and have come to the stage to start looking for a way to properly and easily handle all packets. I am so far that I can figure out what kind of packet it is, but now I need to figure out how to get the needed data to the handler functions. I had the following...
I have implemented a handler class in conjunction with an array of function pointers, works beautifully.
2,755,258
2,916,036
How to use folders in VC10
When making a .NET project, then you can create folders in your solution explorer and these are real folders on the hard drive. When using C++ however they are only filters. Is there a way to set filters to be actually folders?
There's a button to show the hard-drive in the solution explorer.
2,755,298
2,755,464
Good style for handling constructor failure of critical object
I'm trying to decide between two ways of instantiating an object & handling any constructor exceptions for an object that is critical to my program, i.e. if construction fails the program can't continue. I have a class SimpleMIDIOut that wraps basic Win32 MIDI functions. It will open a MIDI device in the constructor a...
Personally, I prefer the first style you've used - Method 1 - that of allocating the SimpleMIDIOut object as local to the scope of the try-catch block. For me, one of the benefits of a try-catch block is that is provides a neat, tidy place for that error handling code - the catch block - that allows you to specify yo...
2,755,351
2,755,889
How to list all installed ActiveX controls?
I need to display a list of ActiveX controls for the user to choose. It needs to show the control name and description. How do I query Windows on the installed controls? Is there a way to differentiate controls from COM automation servers?
Googling for "enumerate activex controls" give this as the first result: http://www.codeguru.com/cpp/com-tech/activex/controls/article.php/c5527/Listing-All-Registered-ActiveX-Controls.htm Although I would add that you don't need to call AddRef() on pCatInfo since CoCreateInstance() calls that for you. This is how I w...
2,755,352
2,756,425
wrapping boost::ublas with swig
I am trying to pass data around the numpy and boost::ublas layers. I have written an ultra thin wrapper because swig cannot parse ublas' header correctly. The code is shown below #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/lexical_cast.hpp> #include <algorithm> #i...
You may want to replace copy(ptr, ptr+sizeof(double)*size, &(dv::data()[0])); by copy(ptr, ptr+size, &(dv::data()[0])); Remember that in C/C++ adding or subtracting from a pointer moves it by a multiple of the size of the datatype it points to. Best,
2,755,395
2,755,912
How to return the handle of a window when we click on it, without any DLL injection?
For one of my projects, I need to create a function that will return a handle to a window when the user click on it (any window displayed on screen, and anywhere inside that window). I know it is possible to use a global hook, but I think there must be a more simple way of doing that, without using any DLL injection. I...
You could use a LowLevelMouseProc hook to intercept the click, and then use WindowFromPoint to determine the window. (I haven't actually tried this.)
2,755,447
2,755,496
Importing a C DLL's functions into a C++ program
I have a 3rd party library that's written in C. It exports all of its functions to a DLL. I have the .h file, and I'm trying to load the DLL from my C++ program. The first thing I tried was surrounding the parts where I #include the 3rd party lib in #ifdef __cplusplus extern "C" { #endif and, at the end #ifdef __cplu...
Linker errors like that suggest you've defined all the functions in function_pointers.cpp, but forgotten to add it to the project/makefile. Either that, or you've forgotten to "extern C" the functions in function_pointers.cpp too.
2,755,497
2,755,585
Can't Include winhttp.h (with code::blocks/mingw) c++
I've been trying to include winhttp.h and I get this error: Winhttp.h: No such file or directory Mingw doesn't have it, how would I add it?
You can use runtime dynamic linking to link to the function(s) you want directly. You can't use the plain winhttp.h that ships with the Windows SDK because it contains Microsoft-specific features. You could also compile with Visual C++ 2010 Express Edition which would include the header you want. Hope that helps :)
2,755,652
2,758,124
How to generate one large dependency map for the whole project that builds with makefiles?
I have a gigantic project that is built using makefiles. Running make at the root of the project takes over 20 minutes when no files have changed (i.e. just traversing the project and checking for updated files). I'd like to create a dependency map that will tell me which directories I need to run 'make' in based on th...
One thing you could look for is "makefile graph" -- there are a few projects out there to make dependency trees from large makefile projects. Here's one: http://sailhome.cs.queensu.ca/~bram/makao/index.html . I think it will both create a pretty graph, and actually build things. If you want to roll your own Makefile ...
2,755,670
2,755,810
How to attach boost::shared_ptr (or another smart pointer) to reference counter of object's parent?
I remember encountering this concept before, but can't find it in Google now. If I have an object of type A, which directly embeds an object of type B: class A { B b; }; How can I have a smart pointer to B, e. g. boost::shared_ptr<B>, but use reference count of A? Assume an instance of A itself is heap-allocated I...
D'oh! Found it right in shared_ptr documentation. It's called aliasing (see section III of shared_ptr improvements for C++0x). I just needed to use a different constructor (or a corresponding reset function overload): template<class Y> shared_ptr( shared_ptr<Y> const & r, T * p ); Which works like this (you need to co...
2,755,797
2,771,883
How to determine Scale of Line Graph based on Pixels/Height?
I have a problem due to my terrible math abilities, that I cannot figure out how to scale a graph based on the maximum and minimum values so that the whole graph will fit onto the graph-area (400x420) without parts of it being off the screen (based on a given equation by user). Let's say I have this code, and it automa...
You are using ax^2 + bx + c (quadratic equation). You will get list of (X,Y) values inserted by user. Let us say 5 points you get are (1,1) (2,4) (4,1) (5,6) (6,7) So, here your best_max_y will be 7 and best_min_y will be 1. Now you have total graph area is Dx = right_side - left_side //here, 400 (710 - 310) Dy = bo...
2,756,153
2,823,616
Why would GDI+ colours vary based off whether a tooltip is visible?
I'm displaying a bitmap using GDI+. After loading the bitmap from a DLL resource I set the background colour (blue - #0000FF) to transparent using TransparentBlt. On Windows Vista and later this works as expected. However, on a Windows XP system we're testing on this only works when any tooltip (e.g. the "title" prop...
What I ended up doing was more of a workaround, but it did work. I changed the background colour to black and added the following code before the DrawImage call: Gdiplus::ImageAttributes imAtt; imAtt.SetColorKey(Gdiplus::Color(0, 0, 0), Gdiplus::Color(0, 0, 0), Gdiplus::ColorAdjustTypeBitmap); For some reason using t...
2,756,233
2,756,265
Why should pop() take an argument?
Quick background I'm a Java developer who's been playing around with C++ in my free/bored time. Preface In C++, you often see pop taking an argument by reference: void pop(Item& removed); I understand that it is nice to "fill in" the parameter with what you removed. That totally makes sense to me. This way, the pers...
To answer the question: you should not implement the pop function in C++, since it is already implemented by the STL. The std::stack container adapter provides the method top to get a reference to the top element on the stack, and the method pop to remove the top element. Note that the pop method alone cannot be used...
2,756,243
2,756,277
Network programming and Packets interactions
Greeting, This month I will start working on my master thesis. My thesis's subject is about network security. I need to deal with network interfaces and packets. I've used shappcap before to interact with packets but I'm not sure if C# is the most powerful language to deal with network programing and packets. I worked ...
You'd be able to do network programming using almost any language you want to. If you are equally comfortable in all of the languages you've mentioned, you should determine what system libraries or APIs will you be interfacing with. For example, if you will be doing packet-level network programming on a Unix system, C ...
2,756,273
2,756,304
Does OpenGL stencil test happen before or after fragment program runs?
When I set glStencilFunc( GL_NEVER, . . . ) effectively disabling all drawing, and then run my [shader-bound] program I get no performance increase over letting the fragment shader run. I thought the stencil test happened before the fragment program. Is that not the case, or at least not guaranteed? Replacing the fragm...
Take a look at the following outline for the DX10 pipeline, it says that the stencil test runs before the pixel shader: http://3.bp.blogspot.com/_2YU3pmPHKN4/Sz_0vqlzrBI/AAAAAAAAAcg/CpDXxOB-r3U/s1600-h/D3D10CheatSheet.jpg and the same is true in DX11: http://4.bp.blogspot.com/_2YU3pmPHKN4/S1KhDSPmotI/AAAAAAAAAcw/d38b4o...
2,756,415
2,756,439
Console output window in DLL
I am trying to redirect the output from my DLL to an external console window for easy debugging. I have been told about AllocConsole but I am not able to reproduce it, i.e. the console window does not appear. My current environment is Visual Studio 2005. I tried the following example which is gotten off the Internet, A...
The proper way to output debug strings is via OutputDebugString(), with an appropriate debugging tool listening for output strings.
2,756,859
2,756,878
Transfer data between C++ classes efficiently
Need help... I have 3 classes, Manager which holds 2 pointers. One to class A another to class B . A does not know about B and vise versa. A does some calculations and at the end it puts 3 floats into the clipboard. Next, B pulls from clipboard the 3 floats, and does it's own calculations. This loop is managed by the M...
It kind of sounds like you are writing a producer / consumer pair, who may communicate more easily over a (probably thread-safe) queue of floats. In other words: the "queue" is like the vector you are currently using. Both A and B will have a reference to this queue. A runs calculations, and writes floats to the qu...
2,757,424
2,757,479
Discrepancy between the values computed by Fortran and C++
I would have dared say that the numeric values computed by Fortran and C++ would be way more similar. However, from what I am experiencing, it turns out that the calculated numbers start to diverge after too few decimal digits. I have come across this problem during the process of porting some legacy code from the form...
In Fortran, by default, floating point literals are single precision, whereas in C/C++ they are double precision. Thus, in your Fortran code, the expression for calculating NUMERATOR is done in single precision; it is only converted to double precision when assigning the final result to the NUMERATOR variable. And the ...
2,757,492
2,759,822
Display using QtWebKit, whilst parsing xml
I wish to use QtWebKit to load a url for display, but, that's the easy part, I can do that. What I wish to do is record / log xml as I go. My attention here is to record and database certain details on the fly, by recording those details. My problem is, how to do this all on the fly, without requesting the same url fro...
In your loadUrl do the download of the url yourself using the HTTP download facilities Qt already provides (QNetworkRequest and friends). Once you got the data, parse and log it and use: void QWebView::setHtml ( const QString & html, const QUrl & baseUrl = QUrl() ) To set it into the QWebView manually. The second url ...
2,757,713
2,759,347
Optimizing C++ Tree Generation
I'm generating a Tic-Tac-Toe game tree (9 seconds after the first move), and I'm told it should take only a few milliseconds. So I'm trying to optimize it, I ran it through CodeAnalyst and these are the top 5 calls being made (I used bitsets to represent the Tic-Tac-Toe board): std::_Iterator_base::_Orphan_me std::bit...
The tic-tac-toe game tree is very redundant. Eliminating rotated and mirrored boards will reduce the final ply of the game tree by 3 or 4 orders of magnitude. No amount of optimizations will make bubblesort as fast as introsort. struct Game_board; struct Node { Game_board game_board; Node* parent; std::vect...
2,757,816
2,798,382
Class template specializations with shared functionality
I'm writing a simple maths library with a template vector type: template<typename T, size_t N> class Vector { public: Vector<T, N> &operator+=(Vector<T, N> const &other); // ... more operators, functions ... }; Now I want some additional functionality specifically for some of these. Let's say I wan...
I think you can use CRTP to solve this problem. This idiom is used in boost::operator. template<typename ChildT, typename T, int N> class VectorBase { public: /* use static_cast if necessary as we know that 'ChildT' is a 'VectorBase' */ friend ChildT operator*(double lhs, ChildT const &rhs) { /* */ } f...
2,758,080
2,758,100
How to sort an STL vector?
I would like to sort a vector vector<myClass> object; Where myclass contains many int variables. How can I sort my vector on any specific data variable of myClass.
Overload less than operator, then sort. This is an example I found off the web... class MyData { public: int m_iData; string m_strSomeOtherData; bool operator<(const MyData &rhs) const { return m_iData < rhs.m_iData; } }; std::sort(myvector.begin(), myvector.end()); Source: here
2,758,158
2,758,164
Which casting technique is better for doing casting from upper class to lower class in C++
i want to cast from upper class pointer to lower class i.e from the base class pointer to derived class pointer. Should i use "Dynamic_cast" or "reinterpret_cast"? please advice me
Don't use reinterpret_cast - either use static_cast or dynamic_cast. If you're sure that the pointer is to exactly that derived class object use static_cast, otherwise use dynamic_cast (that will require the base class to be polymorhic) and check the result to ensure that the pointer is indeed to the class you want.
2,758,259
2,758,304
How can I know the jpeg quality of the read image using graphicsmagick
When I read a jpeg image using Magick::readImages(...) function. How can I know the estimated jpeg quality of the image? I know how to set the quality when I wanna write the image, but it is not relevant to the quality of the original image, so for example: when I read a jpeg image that its quality is 80% and I write i...
This is impossible, period. The JPEG quality settings is just a number that is passed to the encoder and affects how the encoder treats the data. It's not even percentage of anything - it is just some setting that affects how aggressively the encoder manipulates and transforms data. Wherever you see the percent sign ne...
2,758,449
2,758,833
Is my method for avoiding dynamic_cast<> faster than dynamic_cast<> itself?
I was answering a question a few minutes ago and it raised to me another one: In one of my projects, I do some network message parsing. The messages are in the form of: [1 byte message type][2 bytes payload length][x bytes payload] The format and content of the payload are determined by the message type. I have a clas...
Implementations of dynamic_cast will of course vary by compiler. In Visual C++, the vtable points to a structure which contains all of the RTTI about a structure. A dynamic_cast therefore involves dereferencing this pointer, and checking the "actual" type against the requested type, and throwing an exception (or return...
2,758,848
2,758,889
boost timer usage question
I have a really simple question, yet I can't find an answer for it. I guess I am missing something in the usage of the boost timer.hpp. Here is my code, that unfortunately gives me an error message: #include <boost/timer.hpp> int main() { boost::timer t; } And the error messages are as follows: /usr/include/boost...
It should be fine, on a side note, are you sure you are typing #include instead of include? You shouldn't need to, but you can try to also include: #include <limits> Before the boost include as it seems that may fix at least some of your problems.
2,758,863
2,758,906
C++ instantiation question
Want to verify that my understanding of how this works. Have a C++ Class with one public instance variable: char* character_encoding; and whose only constructor is defined as: TF_StringList(const char* encoding = "cp_1252"); when I use this class in either C++/CLI or C++, the first thing I do is declare a poi...
The one problem i see, is that your constructor takes a const char*, but you're storing it in a char*. That's going to cause the compiler to complain unless you cast away the constness. (Alternatively, is there any reason not to make your field a const char* ? i don't see you needing to edit the chars of the name......
2,758,994
2,759,087
text from a file turned into a variable?
If I made a program that stores strings on a text file using the "list"-function(#include ), and then I want to copy all of the text from that file and call it something(so I can tell the program to type in all of the text I copied somewhere by using that one variable to refer to the text), do I use a string,double,int...
To take some pity on you, this is about the simplest C++ program that reads a file into memory and then does something with it: #include <iostream> #include <string> #include <vector> #include <fstream> using namespace std; int main() { ifstream input( "foo.txt" ); if ( ! input.is_open() ) { cerr << ...
2,759,205
2,759,235
Cryptic C++ "thing" (function pointer)
What is this syntax for in C++? Can someone point me to the technical term so I can see if I find anything in my text? At first I thought it was a prototype but then the = and (*fn) threw me off... Here is my example: void (*fn) (int&,int&) = x;
It can be rewritten to typedef void (*T) (int&, int&); T fn = x; The 2nd statement is obvious, which should have solved that = x; question. In the 1st statement, we make T as a synonym as the type void(*)(int&, int&), which means: a pointer to a function ((*…)) returning void and taking 2 arguments: int&, int&.
2,759,350
2,759,596
Can I use const in vectors to allow adding elements, but not modifications to the already added?
My comments on this answer got me thinking about the issues of constness and sorting. I played around a bit and reduced my issues to the fact that this code: #include <vector> int main() { std::vector <const int> v; } will not compile - you can't create a vector of const ints. Obviously, I should have known th...
Well, in C++0x you can... In C++03, there is a paragraph 23.1[lib.containers.requirements]/3, which says The type of objects stored in these components must meet the requirements of CopyConstructible types (20.1.3), and the additional requirements of Assignable types. This is what's currently preventing you from usin...
2,759,702
2,759,712
class member access specifiers and binary code
I understand what the typical access specifiers are, and what they mean. 'public' members are accessible anywhere, 'private' members are accessible only by the same class and friends, etc. What I'm wondering is what, if anything, this equates to in lower-level terms. Are their any post-compilation functional difference...
Access specifiers only exist for compilation purposes. Any memory within your program's allocation can be accessed by any part of the executable; there is no public/private concept at runtime
2,759,725
2,768,023
Preventing symbols from being stripped in IBM Visual Age C/C++ for AIX
I'm building a shared library which I dynamically load (using dlopen) into my AIX application using IBM's VisualAge C/C++ compiler. Unfortunately, it appears to be stripping out necessary symbols: rtld: 0712-002 fatal error: exiting. rtld: 0712-001 Symbol setVersion__Q2_3CIF17VersionReporterFRCQ2_3std12basic_stringXT...
I figured this out. The trick is to use an export list so that symbols used in the plugin but not used in the binary aren't stripped out. # version.exp: setVersion__Q2_3CIF17VersionReporterFRCQ2_3std12basic_stringXTcTQ2_3std11char_traitsXTc_TQ2_3std9allocatorXTc__ And then when linking the application use: -brtl -bex...
2,759,738
2,760,860
Navigation graphics overlayed over video
Imagine I have a video playing.. Can I have some sort of motion graphics being played 'over' that video.. Like say the moving graphics is on an upper layer than the video, which would be the lower layer.. I am comfortable in a C++ and Python, so a solution that uses these two will be highly appreciated.. Thank you in ...
I'm not sure I understand the question correctly but a video file is a sequence of pictures that you can extract (for instance with the opencv library C++ interface) and then you can use it wherever you want. You can play the video on the sides of an opengl 3D cube (available in all opengl tutorials) and other 3D eleme...
2,759,845
2,759,875
Why is address zero used for the null pointer?
In C (or C++ for that matter), pointers are special if they have the value zero: I am adviced to set pointers to zero after freeing their memory, because it means freeing the pointer again isn't dangerous; when I call malloc it returns a pointer with the value zero if it can't get me memory; I use if (p != 0) all the t...
2 points: only the constant value 0 in the source code is the null pointer - the compiler implementation can use whatever value it wants or needs in the running code. Some platforms have a special pointer value that's 'invalid' that the implementation might use as the null pointer. The C FAQ has a question, "Seriousl...
2,760,167
2,760,215
C++ to bytecode compiler for CLR?
I'd like to be able to compile a C/C++ library so that it runs within a managed runtime in the CLR. There are several tools for doing this with the JVM (NestedVM, LLJVM, etc) but I can't seem to find any for the CLR. Has anyone tried doing this?
Microsoft already provides such a tool with Visual Studio. The C++ compiler cl.exe accepts the /clr option to tell it to generate managed code instead of native code. See the MSDN document How To: Migrate to /clr for information on changing your native project to support managed code.
2,760,180
2,760,204
Is it possible to change a exe's icon without recompiling it?
I have lot of executable that I have compiled (long time back) for many of which I don't have sourcecode now. But when I compiled them I didn't put any icons for them, so they all look like same dull, bald default icon. So my questions are, (1) is it possible for me to write a software that can change the resources se...
It is possible to read and write resoures from an exe or DLL file. Reading the resources is easy(ish) - just use LoadLibraryEx(LOAD_AS_DATA_FILE) to load it, then you can enumerate the resources using the standard resource API's. All of this is documented on MSDN. Writing the resources can also be done using the Update...
2,760,310
2,760,329
How to resolve location of %UserProfile% programmatically in C++?
I'd like to find the directory of the current user profile programmatically in C++.
SHGetSpecialFolderLocation is the best way to get at most of the special paths on Windows. Passed CSIDL_PROFILE it should retrieve the folder you are interested in. If you are actually interested in the contents of the %UserProfile% environment variable you could try ExpandEnvironmentStrings
2,760,549
2,760,573
C++ to bytecode compiler for Silverlight CLR?
I'd like to be able to compile a C/C++ library so that it runs within a safe managed runtime in the Silverlight CLR. There are several tools for doing this with the JVM that allows C++ code to run within a CRT emulation layer (see NestedVM, LLJVM, etc), which effectively allows C++ code to be run within a Java Applet. ...
Then I think you are plain out of luck. If your code can't use the /clr:safe flag then it won't be compilable into something that can run in Silverlight. If the C++ is doing something that the CLR does not allow or support, then there is no way around this directly. Depending what your code does, you could possibly exe...
2,760,692
2,760,798
Sorting and displaying a custom QVariant type
I have a custom type I'd like to use with QVariant but I don't know how to get the QVariant to display in a table or have it sort in a QSortFilterProxyModel. I register the type with Q_DECLARE_METATYPE and wrote streaming operators registered via qRegisterMetaTypeStreamOperators but for whatever reason when I use the t...
Display: It sounds like your model isn't returning sensible content for the DisplayRole. The QAbstractItemDelegate (often a QStyledItemDelegate) that is used to display all content from the model needs to understand how to render the content of returned by data() for the Qt::DisplayRole. You have two main options: Mo...
2,760,716
2,760,876
Avoiding stack overflows in wrapper DLLs
I have a program to which I'm adding fullscreen post-processing effects. I do not have the source for the program (it's proprietary, although a developer did send me a copy of the debug symbols, .map format). I have the code for the effects written and working, no problems. My issue now is linking the two. I've tried...
SetDllDirectory probably won't work. Cg.dll likely just links to OpenGL.dll. When the OS loads Cg.dll, it sees that there's already a module loaded with that name (yours), so it links Cg with that instead of going off to find some other copy. That is, the search order that SetDllDirectory modifies never even comes into...
2,760,875
2,760,894
How to use class templates as function arguments?
I have a class declared along the lines of template<int a, int b> class C { public: array[a][b]; } and I want to use it as argument in a function like this: bool DoSomeTests(C &c1, C &c2); but when I compile, it tells me 'use of class template requires template argument list.' I tried template<int a, int b> bool...
You need to provide arguments to the class template C in the declaration of DoSomeTests: template<int a, int b> bool DoSomeTests(C<a, b> &c1, C<a, b> &c2); Both the class template C and your function template DoSomeTests take two int template parameters but the fact that you want to map them from the function template...
2,761,045
2,761,061
c++ strings and file input
Ok, its been a while since I've done any file input or string manipulation but what I'm attempting to do is as follows while(infile >> word) { for(int i = 0; i < word.length(); i++) { if(word[i] == '\n') { cout << "Found a new line" << endl; lineNumber++; } ...
There is getline function.
2,761,242
2,761,307
Test for external undefined references in Linux
Is there a built in linux utility that I can use to test a newly compiled shared library for external undefined references? Gcc seems to be intelligent enough to check for undefined symbols in my own binary, but if the symbol is a reference to another library gcc does not check at link time. Instead I only get the me...
Usually, undefined references are allowed when linking shared objects, but you can make the linker generate an error if there are undefined symbols in the object files that you are linking to create the shared library by supplying -z defs to the linker (or equivalently -Wl,-z,defs in the gcc command that calls the link...
2,761,266
2,761,308
Writing a C++ wrapper for a C library
I have a legacy C library, written in an OO type form. Typical functions are like: LIB *lib_new(); void lib_free(LIB *lib); int lib_add_option(LIB *lib, int flags); void lib_change_name(LIB *lib, char *name); I'd like to use this library in my C++ program, so I'm thinking a C++ wrapper is required. The above would all...
A C++ wrapper is not required - you can simply call the C functions from your C++ code. IMHO, it's best not to wrap C code - if you want to turn it into C++ code - fine, but do a complete re-write. Practically, assuming your C functions are declared in a file called myfuncs.h then in your C++ code you will want to incl...
2,761,360
2,761,494
Could I ever want to access the address zero?
The constant 0 is used as the null pointer in C and C++. But as in the question "Pointer to a specific fixed address" there seems to be some possible use of assigning fixed addresses. Is there ever any conceivable need, in any system, for whatever low level task, for accessing the address 0? If there is, how is that so...
Neither in C nor in C++ null-pointer value is in any way tied to physical address 0. The fact that you use constant 0 in the source code to set a pointer to null-pointer value is nothing more than just a piece of syntactic sugar. The compiler is required to translate it into the actual physical address used as null-poi...
2,761,542
2,779,052
Changes to data inside class not being shown when accessed from outside class
I have two classes, Car and Person. Car has as one of its members an instance of Person, driver. I want to move a car, while keeping track of its location, and also move the driver inside the car and get its location. However, while this works from inside the class (I have printed out the values as they are calculated)...
So I think that I figured it out. I think the problem was that I was passing the object by value into the move() function. I switched to passing it as a pointer to the object, and it worked!
2,761,570
2,761,601
C++ std::vector memory/allocation
From a previous question about vector capacity, Mr. Bailey said: In current C++ you are guaranteed that no reallocation occurs after a call to reserve until an insertion would take the size beyond the value of the previous call to reserve. Before a call to reserve, or after a call to reserve when the size is between t...
I think you're reading the statement wrong. Reserve is allowed to set capacity to a larger amount than what you reserved. The special language is to allow an implementation to reallocate if you're reserving more than you did the last time, but before you've reached the current capacity.
2,761,591
2,761,611
error in assigning a const character to an unsigned char array in C++
#include <iostream> #include <fstream> #include <cstring> using namespace std; typedef unsigned long int WORD; /* Should be 32-bit = 4 bytes */ #define w 32 /* word size in bits */ #define r 12 /* number of rounds */ #define b 16 ...
Change: key="111111000001111"; to strncpy((char *)key, "111111000001111", sizeof(key));
2,761,605
2,761,749
Getting website source with C++ - content is repeated
So, I have this source: #include <winsock2.h> #include <windows.h> #include <iostream> #pragma comment(lib,"ws2_32.lib") using namespace std; int main (){ WSADATA wsaData; if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) { cout << "WSAStartup failed.\n"; system("pause"); ...
Try changing while (buffer[i] || buffer[i] == '\n' || buffer[i] == '\r') { cout << buffer[i]; i += 1; } to for(; i != nDataLength; ++i) cout << buffer[i]; It looks like you are reading past the end of the buffer into garbage data used by recv and friends. Nobody said th...
2,761,679
2,761,692
Can anyone explain C++ exception specifications to me?
Can anyone explain Exception Specifications as used in C++ ? When are they used (I have rarely seen it used in code) What are the pros and cons (benefits/disadvantages) of using exception specifications?
When are they used (I have rarely seen it used in code) Hopefully never as they are deprecated in the next version of C++ due for standardization next year. What are the pros and cons (benefits/disadvantages) of using exception specifications? They provide a way for readers of your code to know exactly what exceptions ...
2,761,918
2,761,921
How do I use "this" in a member function?
I've written a member function of class Node to read a tree of Nodes in postfix order. It will be called by the Node instance which is the root node of the tree. So: N.postfix(); these appear to be illeagal: *this->left.postfix(); *this->right.postfix(); What is the proper way to do this? class Node { public: cons...
In a member function, you don't generally need to use this to access class members; you can simply use: left->postfix(); etc. If you have function parameters or other local variables that have the same name as a class member variable, you can use this to refer to the member variable, e.g., this->left->postfix(); The ...
2,762,017
2,762,022
C++ Singleton Constructor and Destructor
Does it matter if the constructor/destructor implementation is provided in the header file or the source file? For example, which way is preferred and why? Way 1: class Singleton { public: ~Singleton() { } private: Singleton() { } }; Way 2: class Singleton { public: ~Singleton(); private: Si...
It does not matter, but usually it's better (in my humblest of opinions) to define them in the .cpp file, in order to hide the implementation from users of the class.
2,762,078
2,762,099
Why is C++0x's `noexcept` checked dynamically?
I am curious about the rationale behind noexcept in the C++0x FCD. throw(X) was deprecated, but noexcept seems to do the same thing. Is there a reason that noexcept isn't checked at compile time? It seems that it would be better if these functions were checked statically that they only called throwing functions within ...
If I remember throw has been deprecated because there is no way to specify all the exceptions a template function can throw. Even for non-template functions you will need the throw clause because you have added some traces. On the other hand the compiler can optimize code that doesn't throw exceptions. See "The Debate ...