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
5,947,683
5,951,860
For input iterators, why a == b does not imply ++a == ++b?
§24.1.1/3 from C++03 Standard reads, For input iterators, a == b does not imply ++a == ++b. (Equality does not guarantee the substitution property or referential transparency.) Algorithms on input iterators should never attempt to pass through the same iterator twice. They should be single pass algorithms....
The properties referred to are: Substitution Property For any quantities a and b and any expression F(x), if a = b, then F(a) = F(b) (if either side makes sense, i.e. is well-formed). Referential Transparency Informally, it means that there is no difference between a value and a reference to this value (thus how the ...
5,947,814
5,947,918
Build Visual Studio 6 project without Visual Studio
I have inherited a Visual Studio 6 C++ project. The project builds fine in Visual Studio 6 but I failed to compile certain files in the project with a gcc compiler. These issues relate to forward declarations and probably other issues. For the mean-time, I'm not interested in fixing these problems since the code is hor...
You can try downloading the free (as in beer) windows SDK. It's been a while, but I believe that these low level tools, such cl, link and make are available though these. http://msdn.microsoft.com/en-us/windows/bb980924 But you probably will need to massage the code a little, so you might need to deal with the win api...
5,947,835
5,947,873
Wrapping C# code to be called from C++
Possible Duplicate: What are my options for C++ DLL to call a C# DLL? Okay so there is a load of material talking about how to wrap unmanaged code written in C++ or other languages and compiled to a DLL, and making a C# wrapping to make this unmanaged code something that can be called from C# directly. I can't seem ...
This might be worth looking at.
5,947,975
5,948,047
parser for c++ headers to extract functions with standard linux tools?
Possible Duplicate: parser for c++ headers to extract functions with standard linux tools? is there something like this? need to extract c++ functions from header files with all the parameters they use. would be nice if i can use standard linux programms
You can use a program called 'understand 4 c++'. What it does is parse your program like a compiler. However instead of spitting out executable code, it just creates relationships that you can browse your source code (Like Intellisense in visual studio). However it is very powerful. The best and my favorite part is th...
5,948,703
5,948,732
Difference in inlining functions by compiler or linker?
I am wondering whether there is any difference between inlining functions on a linker level or compiler level in terms of execution speed? e.g. if I have all my functions in .cpp files and rely on the linker to do inlining, will this inlining potentially be less efficient than say defining some functions in the headers...
The general rule is all else being equal the closer to execution (compiling->linking->(maybe JIT)->execution) the optimization is done the more data the optimizer has and the better optimization it can perform. So unless the optimizer is dumb you should expect better results when inlining is done by the linker - the li...
5,949,210
5,949,263
htmlcxx compile error
i try to use htmlcxx to parse a webpage. The problem is, the example isnt compileable atm. tree<HTML::Node>::iterator it = dom.begin(); tree<HTML::Node>::iterator end = dom.end(); for (; it != end; ++it) { if (it->tagName() == "A") { it->parseAttributes(); std::cout << it->attributes("href"); ...
I just had a look at the source. The function you want is attribute, not attributes: // attribute takes a string std::pair<bool, std::string> attribute(const std::string &attr) const { ... } // attributes takes nothing const std::map<std::string, std::string>& attributes() const { return this->mAttributes; }
5,949,248
5,949,356
How to animate a solid sphere over a curve
i am making a program in opengl to animate a solid-sphere over a curve it goes like //display function void display() { glClear(GL_DEPTH_BUFFER_BIT|GL_COLOR_BUFFER_BIT); glLoadIdentity(); //set of condition loop:j=1 to 5 loop:i=1 to 3 if(j==1) { ...
You are not clearing the frame buffer, which means that you are drawing each frame on top of the previous frame. Try using glClearColor(0.0f, 0.0f, 0.0f, 1.0f ); with the color you desire.
5,949,552
5,949,644
Issue with reading file content
I have a file which contains text. I read line by line of the entire file and append to a string object. But when i get the final string print out i am not getting the whole file content. I am sure it is due to the presence of special characters like '\n', '\r', '\t', etc. here is my sample code: // Read lines until en...
This is the way to read a file into memory in C++: #include <string> #include <vector> #include <iostream> #include <fstream> using namespace std; int main() { vector <string> lines; ifstream ifs( "myfile.txt" ); string line; while( getline( ifs, line ) ) { lines.push_back( line ); } /...
5,949,555
5,949,577
c++ member function binding
I read one of the book which deals with the issues of member function binding in c++. and it's giving the next example: void Window::oops() { printf("Window oops\n"); } void TextWindow::oops() { printf("TextWindow oops %d\n", cursorLocation); Window win; Window *winPtr; TextWindow *txtWinPrt = new TextWin...
This is caused by slicing. If you assign to an object of the super-class, the information from the subclass is lost. The problem is this statement: win = *txtWinPrt; Since you assign an object of a subclass (TextWindow) to an object of the super-class (Window), all the information of TextWindow that is not in Windo...
5,949,557
5,950,179
Convert existing C++ (.h and .cpp) files to java for Android
I am developing for Android under Eclipse. I have some c++ (.h and .cpp) files that I wish to use in my Android application. I have read Programmming in C/C++ with the Java Native Interface and now I know how to make .so file and import it to Android. But the main problem is that: Is there any tool that converts c++ (....
You don't "convert C++ file to java style". You need to create a JNI wrapper around your existing C++ code. This JNI wrapper is actually C++ code that can be called by Java. By wrapper I mean that you shouldn't have to modify your existing C++ code base. This wrapper, or better said this binding should generally be ver...
5,949,581
5,993,945
Packet oriented lossless compression library
Does anyone know of a free (non-GPL), decently performing compression library that supports packet oriented compression in C/C++? With packet oriented, I mean the kind of feature QuickLZ (GPL) has, where multiple packets of a stream can be compressed and decompressed individually while a history is being maintained acr...
zlib's main deflate() function takes a flush parameter, which allows various different flushing modes. If you pass Z_SYNC_FLUSH at the end of each packet, that should produce the desired effect. The details are explained in the zLib manual. bzip2 has flushing functionality as well, which might let you do this kind of t...
5,949,697
5,949,767
GCC Tail Call Optimization for the Following Situation
Below is a snippet that gets programmatically generated for a toy programming language, actual code is different but following shows what it does when executed, class Base{ }; Base b; class Derived{ int fibo(int i){ if(i SMALLER 2) return 1; else return (Derived)b.fibo(i-1...
How can it eliminate a tail call if there is no tail call? It's only a tail call if it's the very last thing done before a return - but you're calling it twice, storing the results somewhere, add them and then you return. So: Generally, no. If the method is not virtual (i.e. GCC can be sure there's only one implementat...
5,949,766
5,951,407
Is it ok to pass `int *[LENGTH]` instead `int [][LENGTH]`?
I have to add new features to old code. The old code have a problem, there are lot of functions which gets arrays as argument, something like this f(int x[][MAX_LENGTH]). So I wan't to ask is it ok (standard) to pass int *[MAX_LENGTH] instead? In other words is the code bellow standart? # include <iostream> using names...
Your question doesn't match your code, x in main has type int (*)[3], not int *[3]. In this instance the parentheses are important becuase the first is a pointer to an array and the second is an array of pointers. Your function call f(x) is valid because your function declaration is equivalent to void f(int (*x)[3]) F...
5,949,787
5,949,809
Problems declaring classes and namespace
I'm declaring a class like this: #include "BindableInterface.h" #include "../LuaHelper.h" #include <map> #include <string> namespace utils{ class CLuaHelper; }; namespace zel{ namespace utils{ class CAPIBindManager { typedef std::map<std::string, CBindeableInterface*> t_exposedCl...
Use ::utils::CLuaHelper to distinguish in between the two utils namespaces.
5,949,934
5,953,908
Can we convert PDF files to HTML using C,C++,or Java (any language)?
I need to convert PDF files into HTML files (IOS platform) so that I can annotate the HTML page using Javascript. I had some success in annotating HTML pages, so if I can convert PDF to HTML I can complete my task. How can I do the conversion?
Converting FROM PDF is generally Very Hard (at best). PDF contains drawing instructions. "Line from here to there", "these characters at these coordinates". There's usually no information about the logical meaning of these lines, characters, and images, though "Document Structure" is becoming more common. Without "do...
5,949,951
5,949,973
Cannot include boost.asio
I am trying to include boost.asio library, but whenever I do that I get this error message: undefined reference to `boost::system::generic_category()' I can include any other boost library, but not this one. I tried to link boost.System like this: icpc -lboost_system main.cpp -o out.o It gave me this message ld: can...
You need to link Boost.System in order for Asio to work. See here.
5,949,992
5,950,287
template class member function only specialization
I am reading the Complete Guide on Templates and it says the following: Where it is talking about class template specialization. Although it is possible to specialize a single member function of a class template, once you have done so, you can no longer specialize the whole class template instance that the specialized...
I think it is referring to the following case: template <typename T> struct base { void foo() { std::cout << "generic" << std::endl; } void bar() { std::cout << "bar" << std::endl; } }; template <> void base<int>::foo() // specialize only one member { std::cout << "int" << std::endl; } int main() { base<i...
5,950,005
5,950,115
How to convert form UTF-8 to Latin/Arabic and vice versa?
Is there a cross-platform way to convert from UTF-8 to Latin/Arabic and from Latin/Arabicto UTF-8 in C++?
There are libraries like icu available. But Erik is, of course, right: The round-trip from Unicode through ISO 8859-6 will be lossy. (Yes, UTF-8 is “Unicode.” UTF-16, is “Unicode,” too, just having different bit-patterns for the same code number. See Joel Spolsky's text if you didn't know that. Or if you haven't read i...
5,950,144
5,950,176
Weird c++ code snippet
I have this snippet: template<class T> class VECTOR_2D { public: T x,y; VECTOR_2D() :x(T()),y(T()) {} } What are x and y initialized to in the constructor?
x and y are copy-initialized to T's value-initialized value. From the C++03 standard, §8.5/7: An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized. And from §8.5/5: To value-initialize an object of type T means: if T is a class type with a user-declared constructor, then ...
5,950,220
5,950,912
How to work with float variables at asm in VS
I need to write a common task with inline asm: The Code I used is as Follows. Vector3 Matrix3x3::objectToInertial(const Vector3 &v) { return Vector3( m11 * v.x + m12 * v.y + m13 * v.z, m21 * v.x + m22 * v.y + m23 * v.z, m31 * v.x + m32 * v.y + m33 * v.z ); } How to make this equati...
If you really want to compute m11 * v.x + m12 * v.y by inline assembler try this (I am assuming you want to store the result in a variable result): __asm { fld m11 fmul v.x fld m12 fmul v.y faddp st(1), st fstp result } If you want to learn more about floating point arithmetic in assembly you can tak...
5,950,259
5,950,310
How to save the client area of a child Window to a Bitmap file?
I have created a windows application using core WIN32 and VC++. In my parent window I have a child window and two buttons "save" and "send". When user clicks the "save" button I want the savefileDialog to be opened and user should be able to save the image as a bitmap file. The same file should be sent to a remote user...
RECT rect = {0}; GetWindowRect( hwnd, &rect ); ATL::CImage* image_ = new CImage(); image_ -> Create( rect.right - rect.left, rect.bottom - rect.top, 32 ); HDC device_context_handle = image_ -> GetDC(); PrintWindow( hwnd, device_context_handle, PW_CLIENTONLY ); image_ -> Save( filename ); image_ -> ReleaseDC(); d...
5,950,291
5,950,407
How to keep alive an object for later use in another function?
I have a base class called Mijloc_transport and 2 derived classes called Masina and Tramvai. I must do an menu type program that can create different kind of objects from the derived classes and show them. I'm using the UPCASTING method and when I press 1 the if(tasta=="1") creates an object and I can see what type it ...
Instead of: Masina b(30); p=&b; tabp[i]=p; do: tabp[i] = new Masina(30); and do not forget to do: for ( unsigned int i = 0; i < MAX; ++i ) { delete tabp[i]; } When you no longer need tabp (before existing main).
5,950,457
5,951,103
... used without template parameters error
I am in need of your help once again... I had the following code, which was causing explicit specialization in non-namespace scope error: namespace __test { template <int A, int B, typename C> class Test { template <int V> void check(C & a) { } template <> void check<0>(C & a) { } //error: expli...
You need to either fully specialize everything, like this: namespace __test { template <int A, int B, typename C> class Test { template <int V> void check(C & a) { } }; template <> template <> void Test<1, 2, int>::check<0> (int &) { } } Or use a helper structure to avoid trying to partially specialize template...
5,950,593
5,950,618
C++: How is static class member implemented?
Where are static data members stored? Is there some kind of static members table (as in "virtual methods table")? I've performed an experiment - seems like static members don't affect sizeof() at all. Does it mean all references to static members are converted to a fixed address?
The C++ standard doesn't enforce a particular implementation. But typically static class members will be implemented in a similar fashion to "free" statics. However, your observation that sizeof shouldn't be affected by static members is correct.
5,950,623
5,950,737
How to tell what is in committed and reserved memory?
I am currently looking into an issue where an application is using alot of private memory for a C++ app. It looks like alot is in committed and reserve memory based on the dump analysis. I use Windbg. Is there any way I can see what excactly is in commited and reserve memory? I have narrowed it down to one specific ...
!address -Filter should be able to give that information. Here are the different filter options. MEM_COMMIT :- All memory that is currently committed for use by the target. Physical storage has been allocated for this memory, in physical memory or in the page file. MEM_RESERVE :- All memory that is reserv...
5,950,879
5,951,914
Validation XML for QDomDocument. How can I check it?
Is this XML is valid? I ask this question, because i don't load this document with .setContent() for QDomDocument in Qt.
No. According to W3's XML validator, the name of the topmost element much match the name of the doctype declaration.
5,950,916
5,951,892
C++ Dynamic multidimensional array problem
I'm developing a 2d-platformer. Everything was fine until I've got some hard to solve problem. Level map is stored in dynamic multidemension array(char **map). It works fine, until I want to redefine it Here's the part of code: Map& Map::operator=(const Map& rhs) { if(width!=0||height!=0) { for(int i=0;...
As always, Boost has an elegant and memory efficient multi-dimensional array class: http://www.boost.org/doc/libs/1_39_0/libs/multi_array/doc/user.html For example, to setup a 10 x 20 array of bool values: boost::multi_array mtaFlagMatrix(boost::extents[10][20]); Then to access its elements: mtaFlagMat...
5,951,031
5,951,700
cin.ignore(3) after failure to get a double with cin >> var
I'm learning c++ with c++ Primer Plus, and I'm on chapter 7 and trying to create the following function: double getDouble(const char * message){ double temp; std::cout << (message); if (!(std::cin >> temp)){ std::cin.clear(); std::cin.ignore(3); // Why does this work specifically? st...
The C++ standard guarantees (§27.6.1.3/23 in the '03 standard) that passing std::numeric_limits<std::streamsize>::max() will ignore everything in the stream until the specified delimiter or end of input is reached. So change std::cin.ignore(3); to std::cin.ignore(std::numeric_limits<std::streamsize>::max()); Using ma...
5,951,049
5,960,290
.NET Encoding.Default alternative in wxWIdgets?
I need to read files with different encodings. Unicode files are correctly read using wxFileInputStream fileInputStream(dialog->GetPath()); wxTextInputStream textInputStream(fileInputStream); If I need to read, say, Cyrillic (cp1251) files, I use: wxFileInputStream fileInputStream(dialog->GetPath()); wxTextInputStream...
The problem was solved by using wxConvAuto(wxFONTENCODING_SYSTEM) instead of wxCSConv(wxFONTENCODING_SYSTEM). The wxConvAuto function first tries to read the file as a Unicode document, and then if it fails, it uses system's encoding to read the ANSI file. It works great!
5,951,072
5,973,462
Using QtConcurrent to load a Pixmap and paint it
I'm trying to create a Tile rendering program. Heres some basic code. Header class Tile: public QGraphicsItem { public: Tile(void); ~Tile(void); QGraphicsPixmapItem *tileItem; void update(QPainter *painter, const QStyleOptionGraphicsItem *option,QWidget *widget); protected: QRectF boundingRect() const; void paint(QPai...
I solved the issue by avoiding paint and instead using the update function. From whatever documentation I've read update indirectly schedules a paint call. So in the end my code looks like this void LoadTilePixmap(Tile *temp) { QPixmap p("c:\\qt\\tile\\tile0-0.png"); temp->tileItem=new QGraphicsPixmapIt...
5,951,133
5,951,246
(C++) Very Basic Questions Regarding Syntax
C++ novice here. I have some basic questions. In int main( int argc, char *argv[] ) How is char *argv[] supposed to be read (or spoken out to humans)? Is it possible to clear/erase specific content(s), character(s) in this case, of such array? If yes, how? Can arrays be resized? If yes, how? How can I copy the entir...
1) It is supposed to be char **argv or char *argv[] which is a pointer to an array of characters more commonly known as an array of strings 2) CString is the std library to manipulate C strings (arrays of characters). You cannot resize an array without reallocating, but you can change the contents of elements by refer...
5,951,242
5,951,279
Default constructors in C++
if i have constructors with parameters in my class, we need to provide a do-nothing constructor like : 1) class A { A(){}; //To satisfy the compiler //some constructors with parameter }; just to satisfy the compiler. Now if my class has a default parameter like : 2) class A { //A(){} can't be used expilcilty or i...
A constructor with no parameters, or a constructor where all parameters have a default value, is the default construcor. The compiler will not generate one if you have provided it. You don't have to provide a default constructor if that doesn't make sense for your type. Of course that prohibits the use of your class in...
5,951,292
5,951,374
How do you delete a cvseq in OpenCV?
Bradski states that "When you want to delete a sequence, you can use cvClearSeq(), a routine that clears all elements of the sequence." HOWEVER, this function does not return allocated blocks in the memory store to either the store or to the system. He says that "If you want to retrieve that memory for some other purpo...
I'm convinced that he meant cvClearMemStorage(): Clears memory storage. This is the only way(!!!) (besides cvRestoreMemStoragePos) to reuse memory allocated for the storage - cvClearSeq,cvClearSet ... do not free any memory. A child storage returns all the blocks to the parent when it is cleared. Text ...
5,951,347
5,952,687
How can realloc not work but malloc can?
I have reached a point where realloc stops returning a pointer - I assume that there is a lack of space for the array to expand or be moved. The only problem is I really need that memory to exist or the application can't run as expected, so I decided to try malloc - expecting it not work since realloc would no work - b...
You are confusing size and pointer types. In the memory allocation, size is the number of bytes, and you are converting the pointer type to float *, essentially creating an array of float of size size / sizeof(float). In the memcpy-equivalent code, you are treating the array as float ** and copying size of them. Thi...
5,951,497
5,951,707
What to do with !address -filter Windbg
I am currently looking into an issue where an application is using alot of private memory for a C++ app. It looks like alot is in commited and reserve memory based on the dump analysis. I use Windbg. Is there any way I can see what excactly is in commited and reserve memory? I have narrowed it down to one specific heap...
You can use the !heap -s command to get memory usage info in WinDbg. There is a tutorial on Leak Detection with windbg here.
5,951,727
5,951,942
If fclose(0) is called, does this close stdin?
If fclose(0) is called, does this close stdin? The reason why I'm asking this is that for some reason, stdin is being closed in my application and I cannot figure out why. I checked for fclose (stdin) and this is not in the application and so I was wondering if fclose(0) could cause undefined behaviour such as closin...
The signature of fclose is this: int fclose ( FILE * stream ); That means, fclose expects a pointer to FILE object. So if you pass 0, instead of a pointer, 0 would be understood as NULL pointer1. If its NULL pointer, how do you expect it to close stdin? It will not close. Use fclose(stdin), as stdin itself is a point...
5,951,736
5,951,965
C++: Redefine one or the other operation in the child class
In the following code: class GraphicalCardDeck : public CardDeck, public GraphicalObject { public: virtual void draw () { return CardDeck::draw(); } virtual void paint () { GraphicalObject::draw(); } } GraphicalCardDeck gcd; gcd->draw(); // selects CardDeck draw gcd->paint(); ...
Yes, it will call the function draw in the CardDeck as we defined. But that might be surprising to someone not familiar with the internals of our class: GraphicalObject* g = new GraphicalCardDeck(); g->draw(); // opps, doing wrong method! Someone that wrote this might expect that GraphicalObject::draw() is called (or ...
5,952,103
5,952,471
Performance of vector assignment after function
I use this code: MainLoop() { for (int i = 0; i < length; i++) { XMVector3Rotate(rays[i], orientation); } } and I have fps 1900000, but when I use this one: MainLoop() { for (int i = 0; i < length; i++) { calculatedRays[i] = XMVector3Rotate(rays[i], orientation); } } I have fps = 200. ...
When you are doing this: XMVector3Rotate(rays[i], orientation); I am guessing that the compiler inlines the function - and sees that, because its result is never asigned anywhere - it doesn't actually do anything, and removes the function call completely. It's very fast because it's not actually doing anything. But th...
5,952,219
5,952,245
missing ';' before 'using'
I'm getting this compilation error with the following code: error C2143: syntax error : missing ';' before 'using' #include <iostream> #include <iomanip> #include <fstream> #include <string> #include "s.h" using namespace std; How is this possible? How can it be fixed?
"s.h" might contain a class declaration that wasn't terminated with a ; When you include a header, the C preprocessor puts substitutes header's contents in in-line, so if you look at s.h you will probably find something unterminated by ;
5,952,409
5,952,558
Table simulation for lua
Good day I have a specific task to give an access of c++ std::map to lua scripts. Desired script syntax is glob["tag"] = "value" or glob("tag") = "value" In research, have tried luabind binding std::string & glob(const std::string &tag) { static std::string value; return value; } ... luabind::module(&state) [...
glob("tag") = "asdasd" can never work, because it's not valid Lua syntax. glob["tag"] = "value" can work. You need to set glob as a userdata with index and newindex metamethods. I don't know anything about luabind, so I cannot help you there. But doing it using the standard Lua API is not hard. I just wonder why you n...
5,952,512
5,952,598
Memcpy, string and terminator
I have to write a function that fills a char* buffer for an assigned length with the content of a string. If the string is too long, I just have to cut it. The buffer is not allocated by me but by the user of my function. I tried something like this: int writebuff(char* buffer, int length){ string text="12345678901...
A C-style string must be terminated with a zero character '\0'. In addition you have another problem with your code - it may try to copy from beyond the end of your source string. This is classic undefined behavior. It may look like it works, until the one time that the string is allocated at the end of a heap memory b...
5,952,602
5,956,576
Using TR1 libraries in GCC and MSVC
I would like to use the TR1 libraries that ship with modern versions of GCC and MSVC, but there are subtle differences: in GCC, I have to say #include <tr1/memory> std::tr1::shared_ptr<int> X; while in MSVC I have to say #include <memory> std::shared_ptr<int> X; I have two questions: 1) Does MSVC automatically operat...
OK, after having several inconsistent and unsurmountable problems with Boost.TR1, especially when trying to use GCC's native TR1 libraries, I decided to ditch Boost entirely and use a small #define workaround. Here is my "tr1.h": #ifndef _TR1_INCLUDE_H #define _TR1_INCLUDE_H /** Usage: #include TR1INCLUDE(unordered_ma...
5,952,786
5,952,822
Problems building ICU samples under VS2008
I tried to build ICU4C sample "uncv" using visual studio 2008 without success I added the header directories (Configuration Properties > C/C++ > General > Additional Include Directories) referenced the lib folder (Configuration Properties > Linker > Additional Library Directories) I added the bin folder the PATH envir...
You did indeed miss one step -- you need to actually link to the ICU .lib files rather than just tell the linker where they reside. See .Lib Files as Linker Input for more information.
5,952,811
5,952,949
How do I send an ICU UnicodeString using a boost::asio:write call?
I'm currently using the ICU library to handle Unicode data, and am trying to send a UnicodeString over a socket. Currently looking at the example using a basic time server: Daytime.3 - An asynchronous TCP daytime server boost::asio::async_write(socket_, boost::asio::buffer(message_), boost::bind(&tcp_connection::ha...
Assuming you want to send the data using UnicodeString's default internal encoding (instead of forcing e.g. UTF-8 or UTF-32), then the following should work: // given UnicodeString ustr boost::asio::const_buffer(ustr.getBuffer(), ustr.length() * sizeof(UChar)); See UnicodeString::getBuffer() and UnicodeString::length(...
5,952,824
5,952,902
long double vs long int
I'm doing a program that calculates the probability of lotteries. Specification is choose 5 numbers out of 47 and 1 out of 27 So I did the following: #include <iostream> long int choose(unsigned n, unsigned k); long int factorial(unsigned n); int main(){ using namespace std; long int regularProb, megaProb; ...
Whether long is 64-bit or not depends on the model. Windows uses a 32-bit long. Use int64_t from <stdint.h> if you need to ensure it is 64-bit. But even if long is 64-bit it is still too small to hold factorial(47). 47! == 2.58623242e+59 2^64 == 1.84467441e+19 although 47C5 is way smaller than that. You should never...
5,952,837
5,952,872
Try / Catch block substituted for a method block in a destructor
I was recently tasked with hunting down a memory leak in a part of our code. The leak ended up being in the destructor for a particular object...and I found something really strange. A former coworker wrote this: File::~File() try { Clear(); } catch (...) { Log("caught exception"); } The file class inherits fr...
This is a function try block and it's completely legal. See, for example, here. The only time that you can do something in a function try block that you can't do in a normal try block in a function is catch exceptions thrown by expression in a constructor initializer list (and even then you end up having to throw somet...
5,953,124
5,953,187
C/C++: Creating simple graph library
I've been thinking about creating a class in C++ on graph theory. The idea is it'll be a class to hold indefinite number of vertices and edges for a simple graph (at most one edge between a pair of vertices). The problem is how'd I store this indefinite number of vertices/edges in the most efficient way. I came up wit...
If you do not plan to frequently add and remove items from inside the collections, I'd use STL vectors. They're fast for iterating through, but not terrible for inserts and removes in the middle. If you want to add / remove anywhere frequently, I'd use STL lists. They're slower for iterating, but insertion / removal is...
5,953,307
5,953,433
Getting mingw-get to install correctly - mingw/msys path missing plus more!
I'm running windows XP. I have been following this tutorial and so downloading mingw-get-inst here. I've done this a couple times and the last time I checked boes to install EVERYTHING including, but not limited to, gcc, g++, MSYS and the MinGW Compiling Suite. I told it to make a program menu shortcut, too. I believe...
The MSYS and MinGW installation procedure is a nightmare, and has got worse over the years. If you just want the compiler suite (no UNIX tools like sed, grep), then I suggest you go to Twilight Dragon Media and download GCC from there. If you also want all the tools, including the Bash shell, the easiest way I've found...
5,953,383
5,954,336
Does Valgrind have an API like Purify/Quantify that lets you disable data recording?
Something like this Purify/Quantify function: quantify_stop_recording_data()
The client program can use callgrind specific client requests to control the callgrind tool (enable and disable profiling), unfortunately the memcheck client requests (for obvious reasons1) don't allow the same sort of control. 1 memory error checking is dependant on having traced the entire memory state up to the curr...
5,953,541
5,953,641
Why does getline not result in the text I expected?
Possible Duplicate: Need help with getline() In the following code, my getline is skipped entirely and doesn't prompt for input. #include <cstdlib> #include <iostream> #include <iomanip> #include <string> #include <istream> using namespace std; int main () { int UserTicket[8]; int WinningNums[8]; char...
The problem is here: cin >> options; You can only extract (>>) from cin when the user hits enter. So the user types 1 Enter and that line executes. Since options is a char, it extracts a single character (1) from cin and stores it in options. The Enter is still in the stdin buffer, since nothing has consumed it yet. W...
5,953,629
5,953,958
Limiting the range for std::copy with std::istream_iterator
I have constructed a minimal working example to show a problem I've encountered using STL iterators. I'm using istream_iterator to read floatss (or other types) from a std::istream: #include <iostream> #include <iterator> #include <algorithm> int main() { float values[4]; std::copy(std::istream_iterator<float>(s...
As you requested a non-C++0x solution, here's an alternative that uses std::generate_n and a generator functor rather than std::copy_n and iterators: #include <algorithm> #include <string> #include <istream> #include <ostream> #include <iostream> template< typename ResultT, typename CharT = char, typename ...
5,953,955
5,954,112
Concurrent writes in the same global memory location
I have several blocks, each having some integers in a shared memory array of size 512. How can I check if the array in every block contains a zero as an element? What I am doing is creating an array that resides in the global memory. The size of this array depends on the number of blocks, and it is initialized to 0. ...
In the CUDA execution model, there are no guarantees that every simultaneous write from threads in the same block to the same global memory location will succeed. At least one write will work, but it isn't guaranteed by the programming model how many write transactions will occur, or in what order they will occur if mo...
5,954,267
5,954,435
can i convert from char* to UChar in ICU?
I have a char * (containing utf-8 string) that i want to pass to ICU to convert it to ANSI (ISO-8859-6) . Unfortunately it seems that most ICU functions take UChar not char*. How can I make this conversion?
Did you look at the docs? UnicodeString::fromUTF8 stands out... // given char* str UnicodeString ustr = UnicodeString::fromUTF8(StringPiece(str)); I assume you know how to then convert ustr to the desired codepage using UnicodeString::extract.
5,954,405
5,954,516
How can I configure std::priority_queue to ignore duplicates?
How can I configure std::priority_queue to ignore duplicates? When I add a key that is already contained then this new one should be ignored. (In my case, the priority for the old and the new one will always be exactly the same.) Complexity-wise it should not make a difference: It will try to insert at the appropriate ...
You can implement a priority_queue out of an STL set. Implementing a priority queue that can be iterated over in C++
5,954,591
5,954,741
C++: How do you convert the name of a function pointer to text?
Possible Duplicate: How to get function's name from function's pointer in C? I'm printing the configuration for the program to the command line each run, and one thing that I would like printed is the current hash function being used -- which is stored in a function pointer variable. Is there a way to do something a...
You can't get the function name at run-time since function names don't exist after compilation. You can however build a separate lookup function that would save the name and associate it with the function pointer: #include <iostream> #include <map> #include <string> #include <boost/preprocessor/stringize.hpp> typedef ...
5,954,617
5,955,272
c++: Excessive copying of large objects
While there is quite a few questions about copy constructors/assignment operators on SO already, I did not find an answer that fit my problem. I have a class like class Foo { // ... private: std::vector<int> vec1; std::vector<int> vec2; boost::bimap<unsigned int, unsigned int> bimap; // And a couple more...
Of course, and everyone says this, don't optimize prematurely. Don't bother with this until and unless you prove a) that your program goes too slowly, and b) it would go faster if you didn't copy so much data. If your program design requires you to hold multiple simultaneous copies of the data, there is nothing you ca...
5,954,843
5,954,913
RPC, sockets and performance considerations
I have two machines in the same subnet. I want to exchange objects between the two machines as quickly as possible. It is using g++ and it is on Debian/Ubuntu. The machines are loaded in traffic and CPU. One way is to send a compressed serialisation of the object over sockets as binary packets (using Google protocol ...
You could combine Google protobuf for serialization with Boost.ASIO to handle the actual I/O. That should offer a good balance between performance and implementation time.
5,955,082
7,045,819
Troubleshoot communication timing issues (C++ windows app)
I have a "legacy" (solve this problem for us issue) app that communicates with an embedded device - it's driven by an external OEM app that reflashes the car's Electonic Control Units (ECU) using this "app" -> communicates to the car ECU through an USB port -> some pass through device -> car ECU. It seems that there ar...
There has been quite a while for this question. The solution to this one was: "Done an in memory logger (that only flushes information at the end of the "profiling"/program)." Looking back that was good enough but now days the performance minded way on Windows would be to use Event Tracing for Windows (ETW) as this de...
5,955,140
5,955,555
JNI: Call a method from C++ that takes an Object
I have a simple problem that I can't seem to find an answer. I've written a method in C++ which should call a method in Java that takes an object. For example, my Java code has: public class MyClass { public class ReturnType { ... } public void methodToBeCalledFromC( ReturnType obj ) { ... }...
Check the compiler warning -- it may be telling you something important!
5,955,325
5,955,391
C++: What type do I use for the definition of this map?
So, I have a function pointer defined as: unsigned static int (*current_hash_function)(unsigned int); And I'm trying to make a map of pointers to function names: typedef std::map<fptr_t, std::string> function_map_t; But I get this error: src/main.h:24: error: ISO C++ forbids declaration of ‘fptr_t’ with no type Oth...
Your function pointer's typedef is: typedef unsigned int (*fptr_t)(unsigned int) ...then you can declare your map like this: typedef std::map<fptr_t, std::string> function_map_t;
5,955,392
5,955,437
no matching function for call to... error with template class
i have to do a generic double linked list, and i made it in vc++ 2010, and everything worked well, but i have to compile it with gcc, but it can't compile it. When i call a method which has an iterator as parameter, i got this error: no matching function for call to 'DLList<int>::Erase(DLList<int>::iterator, DLList<in...
void Erase(iterator const &_first, iterator const &_last){...} This allows your temporary iterators, returned from first() and last(), to be passed. You cannot get a non-const reference to a temporary. Alternatively, you could use this function signature and work on iterator copies (if you e.g. need to modify them wit...
5,955,444
5,955,512
C++ Any way to programmatically detect POD-struct?
I have data structure which stores POD-structs (each instantiation stores a single type only, since it is basically an array of a specific POD-struct). Sometimes another dev. will modify one of these structs, adding or modifying a data type. If a non-POD element is added, e.g. std::string, the data structure blows-up...
At runtime probably not, but at compile time, you can use is_pod trait from either C++0x standard library or Boost.TypeTraits. static_assert(std::is_pod<YourStruct>::value);
5,955,682
5,965,987
boost::make_shared causes access violation
I have a Visual Studio 2008 C++ application for ARMV4I Windows Mobile 6 where I'm using boost::shared_ptr<> to manage a fairly large object (4KB). Unfortunately, boost::make_shared<> causes an Access Violation exception. My code: struct Foo { char a[ 4 * 1024 - 1 ]; }; int _tmain( int argc, _TCHAR* argv[] ) { ...
It turns out this is a stack overflow issue. This was already reported in ticket #4256. Upgrading to the tips fixes it, so it should be available in the next Boost update. Thanks to Peter Dimov in the Boost Users ML.
5,955,804
5,968,022
Repainting image after going to full screen and back in C++/CLI
I'm building application, which paints raw bitmap images on label's hdc using StrechDIBits. ptr = g->GetHdc(); dc = (HDC)ptr.ToInt32 (); SetStretchBltMode (dc, COLORONCOLOR); StretchDIBits (dc, 0, 0, (int) (LabelPictureShow->Width), (int) (LabelPictureShow->Height), 0, 0, width, height, data, bitmapInfo, DIB_RGB_COLORS...
Solved by using custom PaintBox control used in other project. This control uses overwritten OnPaint method where the image is redrawn. Somehow this solution works, but previous almost same solution not.
5,955,805
5,956,232
C++: 'adding references' to namespaces (and class libraries)?
I'm curious about adding references through the "Property Pages" dialog in Visual Studio C++. Specifically adding 'class libraries' and, even more so, 'namespaces'. In what I'm reading it says that both 'class library's and 'namespaces' can be referenced in this way-- I can see what the reference for 'class libraries'...
'Add a reference' in .NET is somewhat like #includeing in normal C++. It allows you to use classes and namespaces inside another .cs file, that is not in the project, e.g., system libraries. If you're coding normal C++, don't worry about it.
5,955,860
5,955,932
Regular Expression Engine Testing
I wrote my own Regular Expression Engine. Does anybody know how to test it, I can go ahead the test with couple of Regular Expression and some input data. but I need some huge list of regular expressions to test with.
PCRE has some tests as well.
5,955,898
5,956,022
Disadvantages of passing around functions?
I'm learning C++ (coming from java) and recently discovered that you can pass functions around. This is really cool and I think immensely useful. Now I was thinking on how I could use this and one of the idea's that popped into my head was a completely customizable class. The best example of my train of though for com...
There is a slight performance hit since a pointer or reference must be dereferenced before calling the function. This is a very advantageous feature. Many design patterns and polymorphism depend on pointers to functions. Check out the "Visitor Design Pattern". Another usage is for a table of functions. For examp...
5,956,041
5,972,290
Why are header guards unnecessary in stdafx.h?
I don't understand why header guards are not used in pre-compiled headers... Any ideas?
Usually, stdafx.h will be included only once per cpp file, as the first statement, and normally, no other files will include it. So, chances of recursively including stdafx.h are minimal, thus the "unnecessariness" of the include guard. I would still advise to use one, just in case, or potentially use #pragma once at t...
5,956,272
5,956,340
Determining the type from a smart pointer
I have a function that currently takes in two template parameters. One is expected to be the smart pointer, and the other is expected to be the object type. For example, SmartPtr<MyObject> as the first template parameter and MyObject as the second template parameter. template <typename T, typename TObject> I would lik...
If you know that the first template parameter will be the smart pointer type, why not declare your function with only one parameter and use it as such: template<typename T> void WhatIsIt(SmartPtr<T> ptr) { printf("It is a: %s" typeid(T).name()); }
5,956,493
5,956,526
Why is it a compile error to assign the address of an array to a pointer "my_pointer = &my_array"?
int my_array[5] = {0}; int *my_pointer = 0; my_pointer = &my_array; // compiler error my_pointer = my_array; // ok If my_array is address of array then what does &my_array gives me? I get the following compiler error: error: cannot convert 'int (*)[5]' to 'int*' in assignment
my_array is the name of an array of 5 integers. The compiler will happily convert it to a pointer to a single integer. &my_array is a pointer to an array of 5 integers. The compiler will not treat an array of integers as a single integer, thus it refuses to make the conversion.
5,956,704
5,986,716
WIndows service run desktop program in Remote Desktop
I need launch program in remote desktop, this program open a window and need user interact, but my application is a windows service. I'm using windows 2008. I'm created an application with success but launch program only session connect with mouse, keyboard, but I need launch in RDP. Now I'm using these functions. WTSE...
So you're trying to launch a GUI application in a particular RDP session on the machine? You have the right idea, more or less, though you may be missing a few pieces. Take a look at the ProcessHelper class in the source for automated tests of the Cassia library. You can remove a lot of the managed cruft for use in C++...
5,956,710
5,956,747
Given a number n and two integers p1,p2 determine if the bits in position p1 and p2 are the same or not. Positions p1,p2 and 1 based
I've been doing some little code quizes just to catch back up on my coding after graduating but this one got my stump. Here's the question: Given a number n and two integers p1,p2 determine if the bits in position p1 and p2 are the same or not. Positions p1,p2 and 1 based. Example 22,3,2 would be true because it's 0001...
You could shift the interesting bits to the least significant position and then mask off all the other bits with &. Assuming p1 and p2 are zero-based indexes counting from the least significant bit: bool same_bits = (((n >> p1) & 1) == ((n >> p2) & 1))
5,957,134
11,583,676
How do I set up CMake to generate header-only projects?
I want to set up header-only C++ (or C) library projects, but can't find a clean way. After some searches I've found that you can't set up a normal library using add_library to do this because it requires a compilable source file. A way to do this would be to use add_custom_target instead, this way: # Get all headers ...
Update: CMake will soon include a library target called INTERFACE that is ideal for header-only projects. This feature is currently in the master branch. Reference. Using the command add_custom_target as you propose works for me (VS2010). The files are neatly listed within my project but it has the drawback that you ca...
5,957,421
5,957,608
Can't sort unordered_set
I have an unordered_set of a class ActiveStatusEffect The set is declared as follows: boost::unordered_set<StatusEffects::ActiveStatusEffect> ActiveStatusEffects; ActiveStatusEffect is defined as follows: class ActiveStatusEffect { public: StatusEffect* effect; int ReminaingTurns; bool ...
boost::unordered_set<Foo> a; a.insert(...); ... std::set<Foo> b(a.begin(), a.end()); std::set<Foo> c; std::copy(a.begin(), a.end(), std::inserter(c, c.end()); Voilà, a sorted set.
5,957,490
5,957,770
Incrementing pointers in C++
Why are the two following code segments not equivalent? void print (char* s) { if (*s == '\0') return; print(s+1); cout << *s; } void print (char* s) { if (*s == '\0') return; print(++s); cout << *s; }
Since it looks like the OP changed print(s++) to print(++s), which is hugely different, here's an explanation for this new version. In the first example, you have: print(s+1); cout << *s; s+1 does not modify s. So if s is 4, and you print(s+1), afterwards s will still be 4. print(++s); cout << *s; In this case, ++s m...
5,957,621
5,957,676
A function that returns a digit within a number
I want to create a function which will a number and the position of the digit that I want to retrieve, int getDigit(int value, int positionFromLeft) Say, getDigit(534, 2) will return 3. What could be the easiest / efficient way to write this function?
All these string-based solutions scare me... Really guys? :-/ int getDigit(int value, int positionFromLeft) { int posFromRight = 1; { int v = value; while (v /= 10) ++posFromRight; } posFromRight -= positionFromLeft - 1; while (--posFromRight) value /= 10; val...
5,957,679
5,957,810
Is there a way to use C++ preprocessor stringification on variadic macro arguments?
My guess is the answer to this question is no, but it would be awesome if there was a way. To clarify, assume I have the following macro: #define MY_VARIADIC_MACRO(X...) // Does some stuff here in the macro definition What I would like to do is somehow perform stringification on all the variables of X before passing i...
Okay, I didn't mean to answer my own question here, but I've come up with a decent solution that is somewhat of a combination of Mark Wilkins answer and the example I gave in the question. It is possible to stringify the entire set variadic set, which then includes the delimiting commas in the string. Here's a quick ex...
5,957,799
5,957,869
another mysqld process using the same InnoDB data or log files
I have a mysql server running on linux system. i'm already running one c++ prog which is building up the data base with current date and time stamp. I'm trying to run another process in c++ which is accessing different db but i'm having error. error is as below: InnoDB: check that you do not have another mysqld proces...
This page: http://dev.mysql.com/doc/refman/5.0/en/external-locking.html Talks about "external locking" which can be turned on or off for MyISAM databases to support multiple servers on one set of data. It does not seem to apply to InnoDB however. And this page: http://book.opensourceproject.org.cn/lamp/mysql/mysql5ce...
5,957,932
5,957,954
C++ If and if else error messages
I am making a collection of math functions. I used if statements to create error messages and cut down on user errors.. I don't think I did it right. string error_0; string error_i; if (num1 == 0;) {error_0 = "You cannot divide by zero. Fail."} else {error_0 = "";} if (num1=<0;) {error_i = "Sorry, can't do imagin...
You need a semicolon after your strings and don't need one inside the if conditions. Also, the operator is <=, not =<. string error_0; string error_i; if (num1 == 0) {error_0 = "You cannot divide by zero. Fail.";} else {error_0 = "";} if (num1 <= 0) {error_i = "Sorry, can't do imaginary numbers.";} //for sqroot f...
5,958,253
5,958,284
Find 'new' items from two containers
I have two containers (the actual container is flexible, unsorted vs sorted doesn't matter to me, so whatever works best for answering my question is what I'll use) which contain some data. I want to compare these two containers, and either remove all 'duplicates' from the second, or create a new container with only th...
Looks like STL set_difference might be right for you. Example from here: // set_difference example #include <iostream> #include <algorithm> #include <vector> using namespace std; int main () { int first[] = {5,10,15,20,25}; int second[] = {50,40,30,20,10}; vector<int> v(10); // 0 0 0...
5,958,274
5,958,303
C++ Can't link Boost library
I'm trying to compile this little piece of code from the boost documentation: (http://www.boost.org/doc/libs/1_46_1/libs/iostreams/doc/tutorial/filter_usage.html) #include <boost/iostreams/device/file_descriptor.hpp> #include <boost/iostreams/filtering_stream.hpp> namespace io = boost::iostreams; int main() { ...
I assume you are refering to the example at http://www.boost.org/doc/libs/1_46_1/libs/iostreams/doc/tutorial/filter_usage.html If you read carefully, you will notice that the tutorial page states that If you have appropriate OutputFilters compressor and base64_encoder, you can do this as follows The code on this ...
5,958,429
5,958,771
Why getline does not work in a switch, and cin does not take the data appropriately?
I need to take in the make model and years of the car the particular product fits. The program is going to write a file with text in it that will be an outline of the html. I need with the crucial information inserted into the correct spots to quickly be able to add products to our web page. When I use a switch stateme...
Change year[256] to string year; Change cin >> year; to getline(cin, year); Add the line cin.ignore(); before the getline. Your main problem is that the stream operator >> leaves the newline in the stream so when you try to use getline it reads an empty line. ignore() will chew up the newline and let you read the str...
5,958,572
5,959,435
How can I avoid std::vector<> to initialize all its elements?
EDIT: I edited both the question and its title to be more precise. Considering the following source code: #include <vector> struct xyz { xyz() { } // empty constructor, but the compiler doesn't care xyz(const xyz& o): v(o.v) { } xyz& operator=(const xyz& o) { v=o.v; return *this; } int v; // <will be i...
The initialization of the elements allocated is controlled by the Allocator template argument, if you need it customized, customize it. But remember that this can get easily wind-up in the realm of dirty hacking, so use with caution. For instance, here is a pretty dirty solution. It will avoid the initialization, but i...
5,959,076
5,959,084
Why isn't my pointer NULL?
I have a linked list of families. I delete one of the childs siblings like so. p->myWife->myChildren=p->myWife->myChildren->mySibling; //makes the sibling the child so the list is not broken when deleting delete p->myWife->myChildren->mySibling; and later i print the child/siblings attributes based upon this if(p->myW...
Deleting a pointer doesn't set it to zero. It just deallocates the memory being pointed to by the pointer. To set it to NULL you will have to set it to NULL yourself. p->myWife->myChildren->mySibling = NULL /*defined to be zero */;
5,959,103
5,959,118
C++ stl vector for classes with private copy constructor?
There is a class in our code, say class C. I want to create a vector of objects of class C. However, both the copy constructor and assignment operator are purposely declared to be private. I don't want to (and perhaps am not allowed) to change that. Is there any other clean way to use/define vector<C> ?
You could use a vector<C*> or vector<shared_ptr<C>> instead.
5,959,296
5,959,311
Can't seem to break a while loop on collision, hashing
I don't know why this code is not breaking out of the while loop: int table_size = 953; store hash_table[953]; for(int i = 0; i < table_size; i++) hash_table[i].count = 0; //bunch of stuff to get hash value here while(hash_table[hashNum].data != pString || hash_table[hashNum].count != 0){ hashNum++; if(ha...
you probably mean: while(hash_table[hashNum].data != pString && hash_table[hashNum].count != 0) In your code the loop will continue if either case is true, hash_table[hashNum].count == 0 is NOT sufficient to make the clause false.
5,959,352
5,959,376
Merging multiple csv files
I have many 1GB csv files. What is the easiest way to merge them. Can this be done using shell commands or do I have to write a C++ program for it.
cat *.csv > mega-merged.csv2 mv mega-merged.csv2 mega-merged.csv (The use of the .csv2 is so that the *.csv doesn't catch it.) Re Joce's comment, if you have headers, you can trim off all the headers (on GNU/Linux or any other platform with GNU tools) using something like: tail -qn +2 *.csv > mega-merged.csv2
5,959,496
5,961,264
QCheckBox inside QTableWidget, clicking on label won't alter state
If I call QTableWidget.setCellWidget with a widget that contains a QCheckBox then clicking on the label of that checkbox will not alter the state. It appears as though the table is consuming part of the mouse events. If I click on the box directly it will alter state. Clicking on the box or the label will cause the ch...
This is not a real answer but what you want seems to work in my small test program. I'll show it here in the hope it will help you: int main(int argc, char* argv[]) { QApplication app(argc, argv); QTableWidget table(1, 1); QCheckBox check("Test"); table.setCellWidget(0, 0, &check); table.show(); ...
5,959,517
5,959,548
Where to download C++ STLsource code both .h and .cpp files?
I downloaded the STL source code from http://www.sgi.com/tech/stl/download.html , but it only has the .h for the function declaration. Where can I download the .cpp files to read the actual implementation? For example, in the stl_multimap.h or in stl_map.h, it has: template <class _Key, class _Tp, class _Compare, class...
The .h files contains the implementations. Many of the headers on that page are just wrappers around other headers or provide typedefs, but if you look at a file like stl_set.h, you will see that it has all the definitions of functions for the set class. Even the page itself states that it is a header-only library, whi...
5,959,657
5,959,824
Code giving SEG FAULT only when the class is being derived!
I am unable to find out the bug in the below code which i had written[Not for any purpose though]. #include &lt iostream &gt #include &lt cstdlib &gt using namespace std; class Base{ public: Base(){cout &lt&lt "Base class constructor" &lt&lt endl;} void funv() {}; ~Base(){cout &lt&lt "Ba...
This is an Undefined behavior. It will cause problem in any case, whether you derive it or not. When you assign a const char* to a char* like below: ptr -> ch = const_cast < char* >("ar0"); That means, you are assigning a character string which is defined in non-heap segment (mostly in data segment). One should only d...
5,959,908
5,989,862
C++ program written in Eclipse using Windows and MinGW cannot display output to console view
I'm using Windows 7 64bit. I installed eclipse version 3.6.2, cdt, and MinGW. I have a C++ console program in Eclipse as follows: #include <iostream> #include <cstdio> using namespace std; int main() { setbuf(stdout, NULL); for (int i = 0; i < 10000000; i++) { cout << "!!!Hello World!!!" << endl; // p...
I find the reason, just because I'm using 64bit eclipse! I turn to 32 bit eclipse, the same code works fine.
5,959,946
5,960,105
How can I test for the last element in a vector when using BOOST_FOREACH?
I have a vector which I iterate over. The final element of the vector is special case, and I'd like to test for it separately. For example, I may do something as such: for (iterator = vector.begin(); iterator != vector.end(); ++iterator) { if ((iterator + 1) == (vector.end())) { ... } else { ......
if(!vec.empty()) { BOOST_FOREACH(int e, boost::make_iterator_range(vec.begin(), vec.end()-1)) { // Handle each element but the last } // Handle last element here }
5,959,978
5,959,994
Deleting array of class objects?
It's almost common knowledge that the code below correctly frees the memory of 100 integers. int* ip = new int[100]; delete [] ip; And I think even for user defined classes it works: Node* ip = new Node[100]; delete [] ip; In the first case, is the size of memory to be freed (400 bytes), determined at compile time...
No. The memory allocator invisibly keeps track of the size. The size cannot be determined at compile time, because then the allocation would not be truly dynamic and the following would not work: size_t n; std::cin >> n; a = new int[n]; // do something interesting delete[] a; Yes. To convince yourself of this fact...
5,960,188
5,960,281
interdependent classes in same namespace problem
I'm in a real fix... I need to port code, which has a lot of interdependent classes and uses namespaces in order to avoid includes. This works in MSVC, but I can't find a way to deal with this situation in GCC :( Contents of myString.h file: #include "baseBuffer.h" //I can't forward declare a base class, so I have to i...
You are missing guards in your header files. MSVC most likely allows you to do that through an extension. Therefore, there are two ways how to solve this : 1. the 1st solution is to merge those two headers. 2. the 2nd solution is forward declare template class myContainer, and create it dynamically in the basebuffer.hp...
5,960,192
5,960,581
QML Qt openUrlExternally
I've just discovered strange behavior when using this code Qt.openUrlExternally(someurl); I would like to let my users open facebook sharer url, but I cannot use this code, as it does nothing. Tested on S60 5th and Symbian^3 devices (C5, C7, 5230, N8) So please tell me (if you know) 1) Is there any BUG about this com...
Qt.openUrlExternally("http://www.stackoverflow.com/"); opens the native browser for me. The only problem I have found with it is, if the browser is already running on the handset (in the background), it will not be brought in to the foreground, and therefore looks as though it has had no effect.
5,960,249
5,960,310
Adding consecutive integers from an input (Translated from Python to C++)
I'd like to request some help on my HW. I think I'm really close to figuring this out. Our CompSci class is currently shifting from learning Python to (introductory) C++. Since the two are vaguely similar, we've been advised, since we're beginners, to code the problem in Python (which we're very familiar with) and to t...
This: for (i=0; 1 <= num; i++) should be: for (i=0; i <= num; i++)
5,960,256
5,960,303
Are arrays in C++ same as C?
Does the C++ compiler treat the arrays same way as in C? E.g In C, An array access using subscript operator is always interpreted as a pointer. In function argument, array declarations are treated as pointer to start of element.
Yes and no. Arrays work the same in both languages for the most part (C99 supports variable-length arrays, while C++ doesn't, and there may be a few other subtle differnces as well). However, what you're saying isn't exactly true either. The compiler doesn't treat an array access as a pointer, not even in C. An array a...
5,960,329
5,960,371
Why the CString(LPCTSTR lpsz) constructor check the high two bytes of lpsz?
I am reading the source code of CString in MFC. I am very curious about the implementation way of constructor CString::CString(LPCTSTR lpsz). In my understanding, before copying the string indicated by lpsz, it only needs check whether lpsz is NULL but no need to combine with checking if HIWORD(lpsz) is NULL. Is any ...
It checks whether it is passed an actual pointer or an integer resource identifier from MAKEINTRESOURCE. In the latter case it loads the string from the resources.
5,960,395
5,960,662
Boost log select destination file
Is it possible with one instance of Boost log, to log into severeal files. I mean is it possible to specify in which file the log will be written: BOOST_LOG_..(...) << "aaa" <- go to **A.log** BOOST_LOG_..(...) << "bbb" <- go to **B.log**
Yes, it's possible - using filters. How you do it exactly depends on your preferences, but here's an example with scoped logger tags: void SomeFunction() { { // everything in this scope gets logged to A.log BOOST_LOG_SCOPED_LOGGER_TAG(lg, "Log", std::string, "LogA") BOOST_LOG(lg) << "aaa"; ...
5,960,520
5,960,580
Where Should Shared Object Files Be Placed?
I am venturing into the land of creating C/C++ bindings for Python using pybindgen. I've followed the steps outlined under "Building it ( GCC instructions )" to create bindings for the sample files: http://packages.python.org/PyBindGen/tutorial.html#a-simple-example Running make produces a .so file. If I understand ho...
Python looks for .so modules in the same directories where it searches python ones. So you have to install it as you would normal python module either somewhere that is on python's sys.path by default (/usr/share/python/site-lib or something like that—it'd distribution-dependent) or add the directory to PYTHONPATH envi...