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,731,170
2,731,370
Multiple Producers Single Consumer Queue
I am new to multithreading and have designed a program that receives data from two microcontroller measuring various temperatures (Ambient and Water) and draws the data to the screen. Right now the program is singly threaded and its performance SUCKS A BIG ONE. I get basic design approaches with multithreading but n...
Here's a suggestion: 1. Have two threads, that are responsible for obtaining data and placing into a buffer. Each thread has it's own (circular) buffer. 2. There will be a third thread that is responsible for getting data from the buffers and displaying on the screen. 3. The screen thread sends messages to the data thr...
2,731,210
2,732,214
Type to use as template parameter to compare double values
I got this n-dimensional point object: template <class T, unsigned int dimension> class Obj { protected: T coords[dimension]; static const unsigned int size = dimension; public: Obj() { }; Obj(T def) { for (unsigned int i = 0; i < size; ++i) coords[i]=def; }; Obj(const Obj& o) { for (unsigned int i ...
If you want one epsilon value for all instances of a given floating type, it's actually quite simple: template <> bool operator<(const Point3DBase<double>& lhs, const Point3DBase<double>& rhs) { } If not, then I shall orient you toward Policy-based Design as Alexandrescu showed: namespace detail { template <class U>...
2,731,211
2,731,300
Windows Build System: How to build a project (from its source code) which doesn't have *.sln or Visual C++ proj file (*.vcproj)
I'm facing this problem. So, I need to build the support libraries (zlib, libtiff, libpng, libxml2, libiconv) with "Multithreaded DLL" (/MD) & "Multithreaded DLL Debug" (/MDd) run-time options. But the problem is there is no direct way . I mean there is no *.sln / *.vcproj file which I can open in Visual C++ and build ...
I believe all those projects include a .vcproj file (open/build in VC) and/or VC makefile (build with nmake).
2,731,262
2,739,174
Where can I find simple beta cdf implementation
I need to use beta distribution and inverse beta distribution in my project. There is quite good but complicated implementation in GSL, but I don't want to use such a big library only to get one function. I would like to either, implement it on my own or link some simple library. Do you know any sources that could hel...
Well, I found some other libraries/implementations: Boost library for C++ Some code in C# at google code And simple but not exactly perfect implementation of inverse beta cdf
2,731,419
2,732,105
What does enabling STL iterator debugging really do?
I've enabled iterator debugging in an application by defining _HAS_ITERATOR_DEBUGGING = 1 I was expecting this to really just check vector bounds, but I have a feeling it's doing a lot more than that. What checks, etc are actually being performed? Dinkumware STL, by the way.
There is a number of operations with iterators which lead to undefined behavior, the goal of this trigger is to activate runtime checks to prevent it from occurring (using asserts). The issue The obvious operation is to use an invalid iterator, but this invalidity may arise from various reasons: Uninitialized iterator...
2,731,459
2,734,185
C++ program to calculate quotients of large factorials
How can I write a c++ program to calculate large factorials. Example, if I want to calculate (100!) / (99!), we know the answer is 100, but if i calculate the factorials of the numerator and denominator individually, both the numbers are gigantically large.
expanding on Dirk's answer (which imo is the correct one): #include "math.h" #include "stdio.h" int main(){ printf("%lf\n", (100.0/99.0) * exp(lgamma(100)-lgamma(99)) ); } try it, it really does what you want even though it looks a little crazy if you are not familiar with it. Using a bigint library is going to be ...
2,731,594
2,739,100
Exporting DLLs in a C++ project
I've encountered a strange behavior in __declspec(dllexport) in my project. I have a C++ project that uses classes, namespaces, try-catches and more cpp elements. When exporting any dummy function in this DLL, no other C project will be able to load it with LoadLibrary (Getting error 'module not found'). Is it possible...
I found the problem. It was really a dependency dll problem. It was not found in the directory of the loading DLL. Thank you all.
2,731,598
2,731,747
LINK : fatal error LNK1104: cannot open file "Iphlpapi.lib"
So I'm using Visual C++ 6.0, and trying to compile some source code, but upon compilation I get this: Linking... LINK : fatal error LNK1104: cannot open file "Iphlpapi.lib" Error executing link.exe. I'm using the correct SDK, and the directories are correct. I've checked, double checked, and triple checked. The file i...
I'm sure that you have some problems with your project configuration. Try moving that file to the folder with your source code. Check the way you add it (via input libraries) to your project. Try creating a new project and moving that .lib into your code folder (after adding it to used libraries).
2,731,610
4,819,544
Stopping Windows Mobile 6.5 tab reordering
I have a C++ Visual Studio 2008 Windows Mobile 6.5 application that uses a tab control. I've noticed that depending on how careful you are with the stylus, when using the tab control you can accidentally re-order the tabs. It's difficult to do deliberately, but it's very easy to do when you're not trying. I assume this...
Turns out it is a feature of the WTL tab class I was using. I ended up subclassing it and removing the tab reordering feature. -PaulH
2,732,085
2,732,111
Is there a way to make `enum` type to be unsigned?
Is there a way to make enum type to be unsigned? The following code gives me a warning about signed/unsigned comparison. enum EEE { X1 = 1 }; int main() { size_t x = 2; EEE t = X1; if ( t < x ) std::cout << "ok" << std::endl; return 0; } I've tried to force compiler to use unsigned underlying typ...
You might try: enum EEE { X1 = 1, XN = -1ULL }; Without the U, the integer literal is signed. (This of course assumes your implementation supports long long; I assume it does since the original question uses LL; otherwise, you can use UL for a long).
2,732,178
2,740,095
Extracting text from PDF with Poppler (C++)
I'm trying to get my way through Poppler and its (lack of) documentation. What I want to do is a very simple thing: open a PDF file and read the text in it. I'm then going to process the text, but that doesn't really matter here. So... I saw the poppler_page_get_text function, and it kind of works, but I have to specif...
You should be able to set the selection rectangle to the pageSize/MediaBox of the page and get all the text. I say should because before you start wondering why you get surprised by the output of poppler_page_get_text, you should be aware of how text gets laid out on a page. All graphics are laid out on a page using a...
2,732,246
2,732,252
Proper use of of typedef in C++
I have coworkers who occasionally use typedef to avoid typing. For example: typedef std::list<Foobar> FoobarList; ... FoobarList GetFoobars(); Personally, I always hate coming across code like this, largely because it forces me to go lookup the typedef so I can tell how to use it. I also feel like this sort of thing i...
The two big arguments for this type of typedef are the reduced typing, which you've already mentioned, and the ease of changing over to a new type of container. A FoobarList could be backed by a vector or a list or a deque and switching would often just require changing a typedef. Your dislike of them when it comes to...
2,732,287
2,732,422
Read All Files in Directory?
How would I go about reading all files in a directory? In C# I would get a DirectoryInfo object, and get all files into a FileInfo[] object. Is there similar functionality in the STD namespace in C++?
Using Windows API, you can find all the files in a directory using FindFirstFile() with FindNextFile() in a loop.
2,732,292
2,732,323
Setting the Cursor Position in a Win32 Console Application
How can I set the cursor position in a Win32 Console application? Preferably, I would like to avoid making a handle and using the Windows Console Functions. (I spent all morning running down that dark alley; it creates more problems than it solves.) I seem to recall doing this relatively simply when I was in college...
See SetConsoleCursorPosition API Edit: Use WriteConsoleOutputCharacter() which takes the handle to your active buffer in console and also lets you set its position. int x = 5; int y = 6; COORD pos = {x, y}; HANDLE hConsole_c = CreateConsoleScreenBuffer( GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NU...
2,732,322
2,732,560
Custom Windows GUI library
I always wondered how software such as iTunes, Winamp etc is able to create its own UI. How is this accomplished under the Windows platform? Is there any code on the web explaining how one would create their own custom GUI?
WinAmp doesn't usually supply its own GUI at all -- it delegates that to a "skin". You can download dozens of examples and unless memory fails me particularly badly, documentation is pretty easily available as well. From the looks of things, I'd guess iTunes uses some sort of translation layer to let what's basically w...
2,732,694
2,732,769
Copy vector of values to vector of pairs in one line
I have the following types: struct X { int x; X( int val ) : x(val) {} }; struct X2 { int x2; X2() : x2() {} }; typedef std::pair<X, X2> pair_t; typedef std::vector<pair_t> pairs_vec_t; typedef std::vector<X> X_vec_t; I need to initialize instance of pairs_vec_t with values from X_vec_t. I use the follo...
something like this? using boost::lambda; X2 x; transform(..., (bind(std::make_pair<X,X2>, _1, ref(x)))); I cant check at the moment, but if recalled correctly from memory, the above is valid.
2,732,700
2,732,803
C++: Switching from MSVC to G++: Global Variables
I recently switched to Linux and wanted to compile my Visual Studio 2010 C++ source code, which uses only the STL, on G++. My Linux machine currently isn't available but I can try to tell you what is going on, first: As I try to compile my project, all global variables I use in main and which perfectly work on MSVC re...
you need to compile as follow: g++ main.cpp myclass.cpp -o myapp NOT as follow: g++ main.cpp -o myapp which will miss global variable declaration in myclass.cpp file.
2,732,978
2,733,015
C++, how to declare a struct in a header file
I've been trying to include a structure called "student" in a student.h file, but I'm not quite sure how to do it. My student.h file code consists of entirely: #include<string> using namespace std; struct Student; while the student.cpp file consists of entirely: #include<string> using namespace std; struct Student {...
You should not place an using directive in an header file, it creates unnecessary headaches. Also you need an include guard in your header. EDIT: of course, after having fixed the include guard issue, you also need a complete declaration of student in the header file. As pointed out by others the forward declaration is...
2,733,125
2,733,137
kill unsigned / signed comparison error
In general, I want warnings of unsigned vs signed. However, in this particular case, I want it suppressed; std::vector<Blah> blahs; for(int i = 0; i < blahs.size(); ++i) { ... I want to kill this comparison. Thanks! (using g++)
You should fix, not suppress. Use an unsigned type: for (size_t i = 0; i < blahs.size(); ++i) You can also use unsigned, but size_t is more appropriate here (and may have a different, larger, range). If you're only using i to iterate and don't need its value in the loop, use iterators instead: for (auto iter = blahs.b...
2,733,141
2,733,798
Strassen's Algorithm for Matrix multiplication c# implementation
I'm just doing a self-study of Algorithms & Data structures and I'd like to know if anyone has a C# (or C++) implementation of Strassen's Algorithm for Matrix Multiplication? I'd just like to run it and see what it does and get more of an idea of how it goes to work.
Disclaimer: I haven't tried any of these out, but they appear to be what OP is looking for. These links were just from looking through some Google Code Search results. I found a C# version. The project doesn't have any frills; it's just the source. However, it appears to be doing the algorithm just from my first cursor...
2,733,158
2,733,177
What is the difference between declaring an enum with and without 'typedef'?
The standard way of declaring an enum in C++ seems to be: enum <identifier> { <list_of_elements> }; However, I have already seen some declarations like: typedef enum { <list_of_elements> } <identifier>; What is the difference between them, if it exists? Which one is correct?
C compatability. In C, union, struct and enum types have to be used with the appropriate keyword before them: enum x { ... }; enum x var; In C++, this is not necessary: enum x { ... }; x var; So in C, lazy programmers often use typedef to avoid repeating themselves: typedef enum x { ... } x; x var;
2,733,377
2,742,729
Is there a way to test whether a C++ class has a default constructor (other than compiler-provided type traits)?
Traits classes can be defined to check if a C++ class has a member variable, function or a type (see here). Curiously, the ConceptTraits do not include traits to check if a C++ class defines a default constructor or given constructor? Can traits be used to check the constructor presence? If yes, how? If not, why it ...
Sorry for answering may own question. Googling I have found that the actual reason we can not check if a class has constructor or a destructors is that, the known technique used to detect if a class has a member is based on taking the address of the member. But constructors and destructors have no name, we can not take...
2,733,379
2,737,579
How do I get Eclipse CDT to ignore files
I have a C++ project in Eclipse. The project uses Perforce and Eclipse has the Perforce plugin installed. Everything was fine, until I decided to create a git repo in my project. I created the git repo to snapshot some changes which I wasn't ready to commit. Everything was fine until I refreshed my files in Eclipse...
Just add a file .p4ignore in your project root and add everything you want P4WSAD to ignore, such as .git See the docu on P4WSAD for more info. That should take care of the Perforce part of your question. For the Eclipse part, please see this SO question.
2,733,459
2,733,526
What is the rationale to not allow overloading of C++ conversions operator with non-member functions
C++0x has added explicit conversion operators, but they must always be defined as members of the Source class. The same applies to the assignment operator, it must be defined on the Target class. When the Source and Target classes of the needed conversion are independent of each other, neither the Source can define a c...
With the current rules, to work out whether you can convert between two classes you only need to look in two places: the source and target definitions. If you could define conversions as non-member functions the conversion function could be anywhere which might make finding the cause of unwanted or ambiguous conversion...
2,733,668
2,734,726
QWidget keyPressEvent override
I'm trying for half an eternity now overriding QWidgets keyPressEvent function in QT but it just won't work. I've to say i am new to CPP, but I know ObjC and standard C. My problem looks like this: class QSGameBoard : public QWidget { Q_OBJECT public: QSGameBoard(QWidget *p, int w, int h, QGraphicsScene *s); signal...
EDIT: As pointed out by other users, the method I outlined originally is not the proper way to resolve this. Answer by Vasco Rinaldo Use Set the FocusPolicy to Qt::ClickFocus to get the keybordfocus by mouse klick. setFocusPolicy(Qt::ClickFocus); The previous (albeit imperfect) solution I gave is given below: Looks...
2,733,816
2,733,999
How do I declare and initialize a 2d int vector in C++?
I'm trying to do something like: #include <iostream> #include <vector> #include <ctime> class Clickomania { public: Clickomania(); std::vector<std::vector<int> > board; }; Clickomania::Clickomania() : board(12, std::vector<int>(8,0)) <<<<<<< { srand((unsigned)time(0)); fo...
Compiling your code with g++, the error I get is that neither srand() nor rand() were declared. I had to add #include <cstdlib> for the code to compile. But once I did that, it worked just fine. So, I'd say that other than adding that include statement, your code is fine. You're initializing the vector correctly. Perha...
2,734,401
2,734,470
Having template function defination in cpp file - Not work for VC6
I have the following source code : // main.cpp #include "a.h" int main() { A::push(100); } // a.cpp #include "a.h" template <class T> void A::push(T t) { } template void A::push(int t); // a.h #ifndef A_H class A { public: template <class T> static void push(T t); }; #endif The code compiled ch...
The problem solved by using // main.cpp #include "a.h" int main() { A::push<int>(100); } It seems that you need to provide more hint to VC6, compared with VC2008.
2,734,562
2,734,568
C++ Char without Limit
I'm pretty well versed in C#, but I decided it would be a good idea to learn C++ as well. The only thing I can't figure out is chars. I know you can use the string lib but I also want to figure out chars. I know you can set a char with a limit like this: #include <iostream> using namespace std; int main() { char c...
You can use a vector of char.
2,734,884
2,740,824
ISO/IEC Website and Charging for C and C++ Standards
The ISO C Standard (ISO/IEC 9899) and the ISO C++ Standard (ISO/IEC 14882) are not published online; instead, one must purchase the PDF for each of those standards. I am wondering what the rationale is behind this... is it not detrimental to both the C and C++ programming languages that the authoritative specification ...
For what it's worth, Herb Sutter wrote an article touching on this issue, and there's a fair bit of discussion in the comments: http://herbsutter.com/2010/03/03/where-can-you-get-the-iso-c-standard-and-what-does-open-standard-mean/ As he mentions, "open" does not necessarily mean "no-cost". As far as students or ot...
2,734,920
2,734,942
Question regarding inheritance in wxWidgets
Currently I'm attempting to write my own wxObject, and I would like for the class to be based off of the wxTextCtrl class. Currently this is what I have: class CommandTextCtrl : public wxTextCtrl { public: void OnKey(wxKeyEvent& event); private: DECLARE_EVENT_TABLE() }; Then later on I have thi...
C++ does not inherit constructors (you may be thinking of Python, which does;-). A class w/o explicitly declared ctors, like your CommandTextCtrl, in C++, only has default and copy ctors supplied implicitly by C++ rules. So, you need to explicitly define a ctor with your desired signature, which basically "bounces bac...
2,734,990
2,735,100
What are the disadvantages of using templates?
Some of the disadvantages would be its syntax is complex compiler generates extra code
They are hard to validate. Template code which doesn't get used tends to be seldom compiled at all. Therefore good coverage of test cases is a must. But testing is time-consuming, and then it may turn out the code never needed to be robust in the first place.
2,735,101
2,735,111
number of digits in a hex escape code in C/C++
I'm having a dispute with a colleague of mine. She says that the following: char* a = "\x000aaxz"; will/can be seen by the compiler as "\x000aa". I do not agree with her, as I think you can have a maximum number of 4 hex characters after the \x. Can you have more than 4 hex chars? Who is right here?
§2.13.2/4: The escape \xhhh consists of the backslash followed by x followed by one or more hexadecimal digits that are taken to specify the value of the desired character. There is no limit to the number of digits in a hexadecimal sequence. A sequence of octal or hexadecimal digits is terminated by the ...
2,735,151
2,735,161
How do I output an individual character when using char *[] = "something"
I've been playing with pointers to better understand them and I came across something I think I should be able to do, but can't sort out how. The code below works fine - I can output "a", "dog", "socks", and "pants" - but what if I wanted to just output the 'o' from "socks"? How would I do that? char *mars[4] = { "a"...
mars[i][j] will print the j'th character of the i'th string. So mars[2][1] is 'o'.
2,735,194
2,737,133
Operator issues with cout
I have a simple package class which is overloaded so I can output package data simply with cout << packagename. I also have two data types, name which is a string and shipping cost with a double. protected: string name; string address; double weight; double shippingcost; ostream &operator<<( ostream &...
You must be including a wrong string header. <string.h> and <string> are two completely different standard headers. #include <string.h> //or in C++ <cstring> That's for functions of C-style null-terminated char arrays (like strcpy, strcmp etc). cstring reference #include <string> That's for std::string. string refere...
2,735,294
2,735,354
Templates, Function Pointers and C++0x
One of my personal experiments to understand some of the C++0x features: I'm trying to pass a function pointer to a template function to execute. Eventually the execution is supposed to happen in a different thread. But with all the different types of functions, I can't get the templates to work. #include <functional> ...
How about using decltype? template <class C> auto func(C&& c) -> decltype(c()) { auto result = c(); return result; }
2,735,315
2,735,337
C++ cin whitespace question
Programming novice here. I'm trying to allow a user to enter their name, firstName middleName lastName on one line in the console (ex. "John Jane Doe"). I want to make the middleName optional. So if the user enters "John Doe" it only saves the first and last name strings. If the user enters "John Jane Doe" it will save...
Use getline and then parse using a stringstream. #include <sstream> string line; getline( cin, line ); istringstream parse( line ); string first, middle, last; parse >> first >> middle >> last; if ( last.empty() ) swap( middle, last );
2,735,417
2,735,500
How do explicit template instantiations affect what the linker can find?
See the following code and please clear my doubts. As ABC is a template, why does it not show an error when we put the definition of the ABC class member function in test.cpp? If I put test.cpp code in test.h and remve 2, then it works fine. Why? . // test.h template <typename T> class ABC { public: void foo( ...
In both cases you are doing an explicit instantiation. In the second case, only ABC<char>::foo is being instantiated, while in the first case ABC<char>::bar is also being instantiated. A different similar example may clarify the implications: // test.h template <typename T> class ABC { public: void foo( T& ); voi...
2,735,605
2,735,637
Pointer to auto_ptr instead of a classical double pointer
I'm quite new to smart pointers and was trying to refactor some existing code to use auto_ptr. The question I have is about double pointers and their auto_ptr equivalent, if that makes sense. I have a function that accepts a double pointer as its parameter and the function allocates resources for it: void foo ( Image**...
std::auto_ptr<> has weird copy semantics (actually it's move semantics, rather than copy semantics) and is often not what you want when you want a smart pointer. For example, it cannot be put into STL containers. If your standard library comes with TR1 support, use std::tr1::shared_ptr<> instead. (If it doesn't, use bo...
2,735,918
2,735,928
sizeof derived already from base
is it possible to return the sizeof a derived class already from base class/struct? imho the size of a class is a kind of property of itself, like the weight of a human being. But I don't want to write the same function in every class. many thanks in advance Oops PS: so code to make my question more clear: template <...
You can't overload the sizeof operator. And I'm not sure what you are asking: class A { int x, y; }; then: size_t n = sizeof( A ); gives you the size of class A - I don't see where derivation comes into this. Edit: and regarding your expanded question, I don't see why you can't say: MyStruct m; std::cout << sizeof...
2,735,982
2,736,086
Memory leak using shared_ptr
Both code examples compile and run without problems. Using the second variant results in a memory leak. Any ideas why? Thanks in advance for any help. Variant 1: typedef boost::shared_ptr<ParameterTabelle> SpParameterTabelle; struct ParTabSpalteData { ParTabSpalteData(const SpParameterTabelle& tabelle, const s...
Have you checked, that you do not have cyclic shared pointer references? For example: class A { public: shared_ptr<A> x; }; shared_ptr<A> a1(new A()); shared_ptr<A> a2(new A()); a1->x = a2; a2->x = a1; Here a1 and a2 will never be released, because they have pointers to each other which keeps them alive. So in your...
2,736,060
2,736,300
lexical_cast int to string
Is it safe to ignore exception of boost::lexical_cast when converting int to std::string?
Exception raised by lexical cast when converting an int to std::string are not associated to the conversion, but to resource unavailable. So you can ignore this in the same way you ignore the exception bad_alloc raised by operator new.
2,736,062
2,736,495
How to determine the end of an integer array when manipulating with integer pointer?
Here is the code: int myInt[] ={ 1, 2, 3, 4, 5 }; int *myIntPtr = &myInt[0]; while( *myIntPtr != NULL ) { cout<<*myIntPtr<<endl; myIntPtr++; } Output: 12345....<junks>.......... For Character array: (Since we have a NULL character at the end, no problem while iterating) char myChar[] ={ 'A', 'B', 'C', 'D', 'E...
C-strings convention is that a char* finish by a '\0' char. For array or any other C++ container there are other idioms that can be applied. Next follows my preferences The best way to iterate on sequences is to use the Range-based for-loop included on C++0x int my_array[] = {1, 2, 3, 4, 5}; for(int& x : my_array) { ...
2,736,454
2,736,489
C++: retrieve map values and insert into second map
I have one map within one header file class: class One { // code typedef map<string, int> MapStrToInt; inline MapStrToInt& GetDetails(unsigned long index) { return pData[index]; } // populate pData.... private: MapStrToInt *pData; }; And a second class which implements another map and wants to ge...
You are using pointers to your maps, instead of plain map objects. Thus, indexing them is the same as indexing into an array of maps. (This may actually be what you want, judging from your comments.) However, first and second are members of an element within your map, not of the map itself. So you should iterate over t...
2,736,828
2,736,879
Is Ogre's use of Exceptions a good way of using them?
I've managed to get through my C++ game programming career so far virtually never touching exceptions but recently I've been working on a project with the Ogre engine and I'm trying to learn properly. I've found a lot of good questions and answers here on the general usage of C++ exceptions but I'd like to get some out...
You don't need to wrap every last call to Ogre in try { ... } catch. You do it wherever you can meaningfully deal with the exception. This may be at the individual call site in some cases, or it could be in a high-level loop of some sort. If you can't deal with it meaningfully anywhere, don't catch it at all; let the d...
2,736,829
2,736,839
show a simple progress bar in C++
Here is the problem: I want to show a progress bar (just as a text like "Remaining 35%...") during a C++ function execution. I've done the first part which is the progress bar but the problem is how do I show the progress bar during the other functions execution? I just want to start showing the bar when execution ente...
Use a separate thread to update the progress bar. That should give "near real" progress of your application.
2,737,013
2,737,022
Static variables in static method in base class and inheritance
I have these C++ classes: class Base { protected: static int method() { static int x = 0; return x++; } }; class A : public Base { }; class B : public Base { }; Will the x static variable be shared among A and B, or will each one of them have it's own independent x variable (which is wh...
There will only be one instance of x in the entire program. A nice work-around is to use the CRTP: template <class Derived> class Base { protected: static int method() { static int x = 0; return x++; } }; class A : public Base<A> { }; class B : public Base<B> { }; This will create a differ...
2,737,058
2,737,457
How to migrate Cppunit tests into GoogleTest?
I have a bunch of module tests written in CPPunit with some mocks created by hand. I am looking for a way to migrate them to GoogleTest as smoothly as possible. Have you tried such an operation? What was the effort needed?
Google Test and Cppunit seem to share somewhat the same syntax for invoking tests but as I suspect have too much differences in that syntax. I'm almost sure you can't somehow automate it and this operation would require rethinking and recompositioning of your tests to follow the Google Test semantics (if you use someth...
2,737,131
2,737,146
c++: Reference array of maps
I have a function which creates an array of Maps: map<string, int> *pMap And a function which writes maps to the array: int iAddMap(map<string, int> mapToAdd, map<string, int> *m, int i) { m = &(pMap[i]); memcpy(m, mapToAdd, sizeof(map<string, int>)); } And a function to get maps from the array map<string, in...
You cannot use memcpy() to copy objects like maps, or indeed any other kind of C++ container - you need to use assignment, which takes into account the map's underlying structure and se,mantics. And you should be using a vector <map>, as you actually seem to want a copy rather than a pointer.
2,737,500
2,737,575
How to pass a const unsigned char * from c++ to c#
So I have a function in unmanaged c++ that gets called when some text happens to have "arrived": #using <MyParser.dll> ... void dump_body(const unsigned char *Body, int BodyLen) { // Need to pass the body to DumpBody, but as what type? ... MyParser::Parser::DumpBody(???); } DumpBody is a static function defi...
void dump_body(const unsigned char *body, int bodyLen) { // you might want a different encoding... String ^str = gcnew String((sbyte*)body, 0, bodyLen, gcnew ASCIIEncoding); MyParser::Parser::DumpBody(str); } DumpBody will take a string.
2,737,541
2,738,804
c++ quick sort running time
I have a question about quick sort algorithm. I implement quick sort algorithm and play it. The elements in initial unsorted array are random numbers chosen from certain range. I find the range of random number effects the running time. For example, the running time for 1, 000, 000 random number chosen from the range...
Most likely it's not performing well because quicksort doesn't handle lots of duplicates very well and may still result in swapping them (order of key-equal elements isn't guaranteed to be preserved). You'll notice that the number of duplicates per number is 100 for 10000 or 500 for 2000, while the time factor is also ...
2,737,921
2,766,936
Thumbnail Provider not working
I'm trying to write a Windows Explorer thumbnail handler for our custom file type. I've got this working fine for the preview pane, but am having trouble getting it to work for the thumbnails. Windows doesn't even seem to be trying to call the DllGetClassObject entry point. Before I continue, note that I'm using Windo...
I stumbled across this since you mentioned my blog ( codemonkeycodes.com ). What problem are you having with my sample? Did you register you DLL using regsvr32? What version of Windows 7 are you on, 32 or 64? Update: I can't say what is or isn't working for you. I just downloaded the sample from my site, followed t...
2,737,954
2,738,023
Binding to object properties in C++
I've seen in WPF where you can bind control values to properties of other controls. How is that binding accomplished in C++? For example, if I have a class called Car and a guage control called RPM, how do I tie the value of RPM to the member variable Car.RPM, so that when Car.RPM changes, it is automatically (as in wi...
It sounds like you want to have a pointer to the value Car.RPM in the gauge control. But the control will never be updated like you want to. In pure C++ this sounds like work for the Observer-Observable pattern, or a simple callback function.
2,738,015
2,738,087
WINAPI SetLastError versus C++ Keword Throw
What is the difference between the WINAPI SetLastError() and the C++ keyword throw? For example, are SetLastError(5); and throw 5; the same?
SetLastError sets a simple global variable, it does nothing to the flow of the program. throw would stop the flow of the running program, unwind the stack until it is caught somewhere with a try - catch clause. The program flow would then continue from the end of the catch. I suggest reading this article, which explain...
2,738,076
2,740,226
Boost ASIO read X bytes synchroniously into a vector
I've been attempting to write a client/server app with boost now, so far it sends and receives but I can't seem to just read X bytes into a vector. If I use the following code vector<uint8_t> buf; for (;;) { buf.resize(4); boost::system::error_code error; size_t len = socket.read_some(boost::asio::buffer(buf), err...
You say that the socket has more than 4 bytes available to read, in which case your code is correctly continuously looping since an eof won't be encountered until all the data is read. It seems to me that you want to use read() rather than read_some() since the latter might return with less than the four bytes you wan...
2,738,260
2,738,302
False sense of security with `snprintf_s`
MSVC's "secure" sprintf funcions have a template version that 'knows' the size of the target buffer. However, this code happily paints 567890 over the stack after the end of bytes... char bytes[5]; _snprintf_s( bytes, _TRUNCATE, "%s", "1234567890" ); Any idea what I do wrong, or is this a known bug? (I'm working in V...
It does appear to be a bug in Visual C++ 2005 (I'm having trouble getting to that link; Google also has it cached). I was able to reproduce the problem in Visual C++ 2005. In Visual C++ 2008 and 2010, the string is correctly truncated (bytes contains 1234\0) and -1 is returned as expected.
2,738,435
2,738,576
Using numeric_limits::max() in constant expressions
I would like to define inside a class a constant which value is the maximum possible int. Something like this: class A { ... static const int ERROR_VALUE = std::numeric_limits<int>::max(); ... } This declaration fails to compile with the following message: numeric.cpp:8: error: 'std::numeric_limits::max()...
While the current standard lacks support here, for integral types Boost.IntegerTraits gives you the compile time constants const_min and const_max. The problem arises from §9.4.2/4: If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-in...
2,738,521
2,738,539
Function that copies into byte vector reverses values
Hey, I've written a function to copy any variable type into a byte vector, however whenever I insert something it gets inserted in reverse. Here's the code. template <class Type> void Packet::copyToByte(Type input, vector<uint8_t>&output) { copy((uint8_t*) &input, ((uint8_t*) &input) + sizeof(Type), back_inserter(o...
If you are on a little-endian machine (e.g., an x86), the bytes will appear reversed (i.e., the lower order bytes will appear before the higher order bytes). If you really want to reverse the order of the bytes, you can use std::reverse.
2,738,669
2,747,440
Getting the System tick count with basic C++?
I essentially want to reconstruct the getTickCount() windows function so I can use it in basic C++ without any non standard libraries or even the STL. (So it complies with the libraries supplied with the Android NDK) I have looked at clock() localtime time But I'm still unsure whether it is possible to replicate the...
On Android NDK you can use the POSIX clock_gettime() call, which is part of libc. This function is where various Android timer calls end up. For example, java.lang.System.nanoTime() is implemented with: struct timespec now; clock_gettime(CLOCK_MONOTONIC, &now); return (u8)now.tv_sec*1000000000LL + now.tv_nsec; This e...
2,738,760
2,738,888
gcc problem with explicit template instantiation?
It is my understanding that either a declaration or typedef of a specialization ought to cause a template class to be instantiated, but this does not appear to be happening with gcc. E.g. I have a template class, template class Foo {}; I write class Foo<double>; or typedef Foo<double> DoubleFoo; but after ...
The syntax for explicit instantiation is template class Foo<double>; See C++03 §14.7.2. Hoping the functions get generated and linked, but not stripped after creating, but not using, an instance (the most minimal implicit instantiation), is quite a gamble.
2,738,840
2,738,931
npruntime example plugin (c++) of NPAPI fails to run on mac OSX 10.5
I have compiled Mozilla NPAPI plugin example npruntime on Mac OSX 10.5. It give me a libnprt.dylib I am bundling this dylib with proper plist. On loading the plugin, NP_GetMIMEDescription() is getting called (i am logging this), but its not going inside NP_GetEntryPoints(). How a part of code is getting loaded and a pa...
Solving your problem with the npruntime sample is a bit hard with the details given. I suggest checking out WebKits examples from their repository. Mac-wise Mozillas samples are somewhat outdated. To spare yourself from implementing it all, you can also take a look at: QtBrowserPlugin FireBreath (Cocoa support is work...
2,738,868
2,738,958
Variable Argument list with no named argument?
Is it possible to have a function with variable arguments and no named argument? For example: SomeLogClass("Log Message Here %d").Log(5); SomeLogClass("Log Message Here %d").Error(5);
Take a look at QString's arg methods. Those seem to be something you're looking for. You can definitely roll your own, although implementation might turn out to be not really trivial, especially if you would like it to support printf format specifiers. If printf style is not necessary, chaining a replace_all kind of ca...
2,738,896
2,739,188
What is a truly empty std::vector in C++?
I've got a two vectors in class A that contain other class objects B and C. I know exactly how many elements these vectors are supposed to hold at maximum. In the initializer list of class A's constructor, I initialize these vectors to their max sizes (constants). If I understand this correctly, I now have a vector of...
A vector has capacity and it has size. The capacity is the number of elements for which memory has been allocated. Size is the number of elements which are actually in the vector. A vector is empty when its size is 0. So, size() returns 0 and empty() returns true. That says nothing about the capacity of the vector at t...
2,738,967
2,738,999
Vector clear vs. resize
I read on the Internet that if you are clearing a std::vector repetitively (in a tight loop), it might be better to use resize(0) instead of clear(), as it may be faster. I am not sure about this. Does anyone have a definitive answer to this?
I assume you mean resize(0) instead of setsize, and calling that instead of clear(), and that you're talking about std::vector. IIRC a recent answer discussed this (can't find the link), and on modern STL implementations, clear() is likely identical to resize(0). Previously clearing a vector might have freed all its m...
2,738,985
2,739,016
Using member variables inherited from a templated base class (C++)
I'm trying to use member variables of a templated base class in a derived class, as in this example: template <class dtype> struct A { int x; }; template <class dtype> struct B : public A<dtype> { void test() { int id1 = this->x; // always works int id2 = A<dtype>::x; // always works ...
You are probably compiling in non-strict mode in icc. Anyway, since x is unqualified, it shall not be looked up in any base classes that depend on the template parameters. So in your code, there is no place where x is found, and your code is invalid. The other names are looked up using another form of lookup (class me...
2,739,049
2,739,156
c++ inline functions
i'm confused about how to do inline functions in C++.... lets say this function. how would it be turned to an inline function int maximum( int x, int y, int z ) { int max = x; if ( y > max ) max = y; if ( z > max ) max = z; return max; }
As others have said, you can use the inline keyword to tell the compiler you want your function inlined. But the inline keyword is just a compiler hint. The compiler can and will chose to ignore your request if it wants or needs to. An alternative is to make your function a function template, which will often be blow...
2,739,146
2,739,194
C++ OOP: Which functions to put into the class?
Assume I have a class a: class a { public: void load_data( ); private: void check_data( ); void work_data( ); void analyze_data( ); } Those functions all do something with the class or one of its members. However this function: bool validate_something( myType myData ) { if ( myData.blah > 0 && myData.bla...
Make it a private static class member. I used to tend to make these non-class members and put them in an nameless namespace in the implementation file, but it seems that they almost always do end up needing to be class members (or need to be moved elsewhere - perhaps to a validation library, in your example), as the co...
2,739,191
2,739,314
implement SIMD in C++
I'm working on a bit of code and I'm trying to optimize it as much as possible, basically get it running under a certain time limit. The following makes the call... static affinity_partitioner ap; parallel_for(blocked_range<size_t>(0, T), LoopBody(score), ap); ... and the following is what is executed. void operator(...
Your question represents some confusion on what is going on. The i,j,k variables are almost certainly held in registers already, assuming you are compiling with optimizations on (which you should do - add "-O2" to your icc invocation). You can use an asm block, but an easier method considering you're already using ICC ...
2,739,236
2,739,283
C++ from SpeakHere in iPhone app
I've made a template app where I've grabbed the recording part of the SpeakHere example and removed the file handling part, but I'm struggeling to get the C++ part of the app working right. As soon as it enters the C++ class, it gets syntax errors. If I don't import the header files from C++ (and then of course don't u...
You are indirectly including the C++ headers into plain Objective-C code (.m) - that won't work, you have to use Objective-C++ (.mm) all the way or encapsulate the C++ classes in Objective-C classes using opaque pointers. One problematic chain: Classes/MainViewController.m, plain Objective-C, includes RecorderLink.h, ...
2,739,251
2,739,264
Reversing a for loop... want to print numbers in reverse
How would I change this loop to print prime number in reverse... starting from the biggest one first int main(){ bool prime; for( int i=3; i<=10000; i++){ prime = true; for(int n=2; n<=i-1; n++){ if( i%n == 0){ prime = false; } } if(prime)...
You can reverse the for loop as follows: for( int i=10000; i>=3; i--) { That being said - you can also simplify this. You only need to check until you reach the square root of the number. Also make sure that, when you find that a number isn't prime, you break out immediately: int main() { bool prime; for( i...
2,739,354
2,743,627
segfault on vector<struct>
I created a struct to hold some data and then declared a vector to hold that struct. But when I do a push_back I get damn segfault and I have no idea why! My struct is defines as: typedef struct Group { int codigo; string name; int deleted; int printers; int subpage; /*included this when it sta...
Well... valgrind to the rescue! What called out to me in the valgrind log was this piece. Invalid write of size 4 ==4639== at 0x805BDC0: ChangeGroups() (articles.cpp:405) ==4639== by 0x80AC008: GeneralConfigChange() (config.cpp:4474) ==4639== by 0x80EE28C: teste() (main.cpp:2259) ==4639== by 0x80EEBB3: main...
2,739,464
2,739,472
Segmentation fault C++ in recursive function
Why do I get a segmentation fault in my recursive function. It happens every time i call it when a value greater than 4 as a parameter #include <iostream> #include <limits> using namespace std; int printSeries(int n){ if(n==1){ return 1; } else if( n==2){ return 2; } ...
return printSeries(n-3) + printSeries( (n-2) + printSeries(n-1) ); // ^^^^^^^^^^^^^^^^^^^^^^^^ Incorrect nesting of parenthesis causes infinite recursion, which leads to stack overflow (segfault). Consider when n = 4, f(4) = 1 + f(2 + f(3)) = 1 + f(2 + 3) = 1 + f(5) =...
2,739,572
2,739,820
C++ UTF-8 output with ICU
I'm struggling to get started with the C++ ICU library. I have tried to get the simplest example to work, but even that has failed. I would just like to output a UTF-8 string and then go from there. Here is what I have: #include <unicode/unistr.h> #include <unicode/ustream.h> #include <iostream> int main() { Unic...
Your program will work if you just change the initializer to: UnicodeString s("привет"); The macro you were using is only for strings that contain "invariant characters", i.e., only latin letters, digits, and some punctuation. As was said before, input/output codepages are tricky. You said: My terminal and font suppo...
2,739,773
2,739,789
error LNK2001: unresolved external symbol _D3DX10CreateTextureFromFileW@24
I am trying to call a direct X funciton but I get the following error error LNK2001: unresolved external symbol _D3DX10CreateTextureFromFileW@24 I understand that possibly there maybe a linker issue. But I am not sure where. I inluded both d3dx10.h and the d3d10.h. I also included the d3d10.lib file. Plus, the intelli...
Is the appropriate DirectX library (or libraries) configured inthe project or makefile (or whatever build system is being used)? For this particular function , it's D3DX10.lib.
2,739,905
2,746,909
Better way to write an object generator for an RAII template class?
I would like to write an object generator for a templated RAII class -- basically a function template to construct an object using type deduction of parameters so the types don't have to be specified explicitly. The problem I foresee is that the helper function that takes care of type deduction for me is going to ret...
It seems pretty easy. The questioner himself proposed a nice solution, but he can just use a usual copy constructor with a const-reference parameter. Here is what i proposed in comments: template<typename T, typename U, typename V> class FooAdder { private: mutable bool dismiss; typedef OtherThing<T, U, V> Thing; ...
2,740,002
2,740,101
How does server management software work?
How does server management software work? I was reading about this software, and I found that they can monitor CPU speed/temperature. How can one do this in C++?
Traditionally, motherboards come with device drivers that provide functionality to query the temp sensors and other motherboard parameters. These drivers can be accessed by other programs. For example, vendors like ASUS have rich GUIs that can present this info (by querying the driver) or background programs that can g...
2,740,020
2,740,178
C++ STL: Array vs Vector: Raw element accessing performance
I'm building an interpreter and as I'm aiming for raw speed this time, every clock cycle matters for me in this (raw) case. Do you have any experience or information what of the both is faster: Vector or Array? All what matters is the speed I can access an element (opcode receiving), I don't care about inserting, alloc...
Element access time in a typical implementation of a std::vector is the same as element access time in an ordinary array available through a pointer object (i.e. a run-time pointer value) std::vector<int> v; int *pa; ... v[i]; pa[i]; // Both have the same access time However, the access time to an element of an array...
2,740,029
2,740,046
Reading data from a socket
I am having issues reading data from a socket. Supposedly, there is a server socket that is waiting for clients to connect. When I write a client to connect() to the server socket/port, it appears that I am connected. But when I try to read() data that the server is supposedly writing on the socket, the read() funct...
Read is blocking until is receives some I/O (or an error).
2,740,164
2,740,236
How to Embed/Link binary data into a Windows module
So I have a Visual Studio 2008 project which has a large amount of binary data that it is currently referencing. I would like to package the binary data much like you can do with C# by adding it as a "resource" and compiling it as a DLL. Lets say all my data has an extension of ".data" and is currently being read from...
Right click the resource script (.rc file) Choose Import http://msdn.microsoft.com/en-us/library/saced6x2.aspx You can embed any "custom" file you want, as well as things like .bmps and stuff VisualStudio "knows" how to edit. Then you can access them with your framework's resource functions like FindResource LoadRes...
2,740,431
2,740,970
How can I store an inventory-like list of numbers?
I've got a list of number that I need to keep track of. The numbers are loosely related, but represent distinctly different items. I'd like to keep a list of the numbers but be able to refer to them by name so that I can call them and use them where needed easily. Kind of like an inventory listing, where the numbers al...
Let me try to rephrase what you're trying to do here. You want developers who use your code to be able to refer to a pre-defined set of numeric values: using intuitive names that will be validated at compile time and that the IDE will recognize for the sake of code completion. If the values will not change at run-ti...
2,740,573
2,740,976
How to share classes between DLLs
I have an unmanaged Win32 C++ application that uses multiple C++ DLLs. The DLLs each need to use class Foo - definition and implementation. Where do Foo.h and Foo.cpp live so that the DLLs link and don't end up duplicating code in memory? Is this a reasonable thing to do? [Edit] There is a lot of good info in all the a...
Providing functionality in the form of classes via a DLL is itself fine. You need to be careful that you seperate the interrface from the implementation, however. How careful depends on how your DLL will be used. For toy projects or utilities that remain internal, you may not need to even think about it. For DLLs t...
2,740,712
2,740,728
How safe and reliable are C++ String Literals?
So, I'm wanting to get a better grasp on how string literals in C++ work. I'm mostly concerned with situations where you're assigning the address of a string literal to a pointer, and passing it around. For example: char* advice = "Don't stick your hands in the toaster."; Now lets say I just pass this string around b...
String-literals have the type const char[N] (where N is the length + 1) and are statically allocated. You need not worry about memory issues; if a string is used in your program it is all handled for you, and resides somewhere in program memory (usually read-only). That is, these are "the same": static const char str[]...
2,740,715
2,740,721
what is the reason for the difference between setprecision (12) and setprecision (012) for example,in c++?
In c++ when you write setprecision (12) for example, 12 is in the base of 10 but when you write it like setprecision (012) it is an octal number,why?
Because constants with leading zeros (other than leading 0x) are always octal: An octal integer literal (base eight) begins with the digit 0 and consists of a sequence of octal digits. C++ draft standard (n1905) §2.13.1 It has nothing at all to do with setprecision.
2,740,822
2,836,393
Is it possible to use boost::bind to effectively concatenate functions?
Assume that I have a boost::function of with an arbitrary signature called type CallbackType. Is it possible to use boost::bind to compose a function that takes the same arguments as the CallbackType but calls the two functors in succession? I'm open to any potential solution, but here's a... ...Hypothetical example...
Boost already provides a way to create a sequence of bound functions. Use Lambda's comma operator. using namespace boost::lambda; MyClass mc; CallbackType object = (bind(&MyClass::alert, mc), bind(doIt, _1, _2, _3)); object(1, 2, 3); That will create a new functor, object. When you invoke that functor with three argum...
2,740,939
2,740,955
Malloc function in C++
I am transitioning to C++ from C. In C++, is there any use for the malloc function? Or can I just declare it with the "new" keyword. For example: class Node { ... } ... Node *node1 = malloc(sizeof(Node)); //malloc Node *node2 = new Node; //new Which one should I use?
Use new. You shouldn't need to use malloc in a C++ program, unless it is interacting with some C code or you have some reason to manage memory in a special way. Your example of node = malloc(sizeof(Node)) is a bad idea, because the constructor of Node (if any exists) would not be called, and a subsequent delete node; ...
2,741,059
2,741,068
Are Bitsets actually Bools?
In C++, are bitsets actually a set of bools? Doesn't this defeat the purpose of using a BitSet because bools are 32 bits (I think...)?
They represent a collection of bool's, but those values are really stored as bits in an unsigned long. The size of a bool is not necessary any number of bits, neither is an unsigned long. (Though the minimum number of bits for any data type is 8, and for an unsigned long it must be at least 32.)
2,741,370
2,741,392
C++ Boost bind value type
I look in documentation and source code but cannot figure out how to get return value type of boost bind functor. I am trying to accomplish following: 35 template<typename T,size_t N, class F> 36 boost::array<typename F::value_type, N> make_array(T (&input)[N], F unary) { 37 boost::array<typename F::value_type, ...
Doh. nevermind, it's result_type rather than value_type. should i delete this question?
2,741,422
2,741,468
How can I avoid explicitly declaring directory paths in C or C++ #include directives?
I am making a simulator and have written lots of files and headers. The problem is whenever I include a file I give the relative path of the particular file. For example a typical code in my application would begin like #ifndef AI_H #define AI_H #include <cstdlib> #include "../world/world.h" #include "pathPlan.h" #i...
Really it all depends on your include path, different compilers might call it different things but in gcc -Idir Append directory dir to the list of directories searched for include files. So in your example you would specify ../world etc... in the list of directories in -I
2,741,522
2,741,541
How do you mentally handle going from writing managed to non-managed code?
~80% of the code I write is in C#. The other ~20% is in C++. Whenever I have to switch from C# to C++, it takes me quite a while to mentally "shift gears" to thinking in C++. I make simple mistakes using pointers and memory allocation that I would not have made when I was in university. After the adjustment period, I a...
I have the same problem. I use completely different color schemes for Visual Studio (dark-on-light for C++; light-on-dark for C# and VB). Seems to help my brain ease the switch.
2,741,744
2,743,535
qt drop event get widget
I'm trying to, inside a dropevent method, find out which widget was just dropped. I tried looking at the docs, but they only have commands for images and text. How do I access both the item just dropped and which widget it was dropped on?(this is drag and drop inside of a QTreeWidget)
By default, Qt is limited to darg & drop text and images but this behaviour can be extended by adding new MIME Type. You can find an interesting example of drag & drop using alternate data type at http://doc.trolltech.com/4.6/draganddrop-fridgemagnets.html. This example can be extended to support drag & drop of widgets...
2,741,787
2,741,810
Warning: cast increases required alignment
I'm recently working on this platform for which a legacy codebase issues a large number of "cast increases required alignment to N" warnings, where N is the size of the target of the cast. struct Message { int32_t id; int32_t type; int8_t data[16]; }; int32_t GetMessageInt(const Message& m) { return *rein...
One possible alternative might be: int32_t GetMessageInt(const Message& m) { int32_t value; memcpy(&value, &(data[0]), sizeof(int32_t)); return value; } For x86 architecture, the alignment isn't going to matter that much, it's more a performance issue that isn't really relevant for the code you have provided....
2,741,790
2,741,853
C++ and preprocessor macro gotcha
Can you figure out what is wrong with the statement below? GCC error states: 'type name' declared as function returning array #define MACRO(a) (a)[1] class index { public: typedef int index_type[2]; const index_type& operator[](int i) const; }; int k = 0; int i = MACRO(index()[k]); btw: I know what is wr...
In the expanded line: int i = (index()[k])[1]; (index()[k]) is interpreted as a cast expression, declaring a function that returns an array of length k of index. At least, that's what it looks like is happening. How gcc is manages to validly interpret the [1] as an expression, I'm not sure.
2,741,840
2,741,867
Dev-C++ Run Program in Background without GUI
I recently began learning C++ in order to reach people w/o .net. I need to run my program in the background(without any visual indication to the user so no window or cmd). I know there a various methods to do this In C#, but I don't know how to do this in C++ (specifically Dev-C++). Any help is greatly appreciated.
First of all, you shouldn't be using Dev-C++. If you really don't want to use Visual Studio (why not? it's free!) then Code::Blocks or Eclipse or something is a better choice. Dev-C++ hasn't been updated in like 5 years... The ways of creating background processes in C++ is basically the same as in C#, you just don't g...
2,741,846
2,741,852
How to sort an array or ArrayList<Point> ASC first by x and then by y?
I just want to use Collections.sort or Arrays.sort to sort a list of points (class Point) by x first and then by y. I have a class Ponto that implements Comparable like this: public int compareTo(Ponto obj) { Ponto tmp = obj; if (this.x < tmp.x) { return -1; } else if (this.x > tmp.x...
Replace return 0 by the same comparison algo on this.y and obj.y. By the way, reassigning to tmp is unnecessary here. The optimized picture can look like: public int compareTo(Ponto other) { if (this.x == other.x) { return (this.y < other.y) ? -1 : ((this.y == other.y) ? 0 : 1); } else { return ...
2,741,986
2,742,159
Indentation control while developing a small python like language
I'm developing a small python like language using flex, byacc (for lexical and parsing) and C++, but i have a few questions regarding scope control. just as python it uses white spaces (or tabs) for indentation, not only that but i want to implement index breaking like for instance if you type "break 2" inside a while ...
I am currently implementing a programming language rather similar to this (including the multilevel break oddly enough). My solution was to have the tokenizer emit indent and dedent tokens based on indentation. Eg: while 1: # colons help :) print('foo') break 1 becomes: ["while", "1", ":", indent, "p...
2,742,084
2,742,091
const CFoo &bar() const
I have a property of a class, for example, const CFoo &bar() const, what does it mean?
The method bar returns a reference to a const CFoo (that's the const CFoo & part before bar), and calling this method does not modify any variables that are not marked as mutable (that's the const after the parentheses). See also the C++ FAQ Lite entries What does "Fred const& X" mean? and What is a "const member funct...
2,742,295
2,742,306
issue with OOP Class Definitions
I work for my homework in C++ and i have some problems with multiply definitions. My graph class ; class Graph{ private: string name; //Graph name fstream* graphFile; //Graph's file protected: string opBuf; //Operations...
No you don't need the definition of the classes. You just need to give the hint to the compiler that Graph and Traversal are classes. So use forward declartion like class BreadthFirst; in the definition of Graph (i..e just above class Graph{....}). Similarly use class Graph; before the definition of Traversal class.
2,742,299
2,742,339
How to get all n sets of three consecutives elements in an array or arraylist with a for statement?
I'm trying to do a convex hull approach and the little problem is that I need to get all sets of three consecutive vertices, like this: private void isConvexHull(Ponto[] points) { Arrays.sort(points); for (int i = 0; i <points.length; i++) { isClockWise(points[i],points[i+1],points[i+2]); ...
The remainder "trick" You can use the % "trick" (% is the remainder operator JLS 15.17.3) for circular indexing. Here I will illustrate the general idea using a String instead. String s = "ABCDE"; final int L = s.length(); for (int i = 0; i < L; i++) { System.out.format("%c%c%c ", s.char...
2,742,371
2,748,434
Visual Studio 2010 - Export (Project) Template menu option grayed out
In Visual Studio, I want to make a simple C++ project and export it out as a template, so I can use the template to start new projects to save me time. But the Export Template menu option is always grayed out. I've not once been able to click it. Anyone know why? Anyone know how to accomplish what I need (besides the ...
You can use the Visual C++ wizard architecture, which is designed for easy extensibility and customization. You can create a wizard using the Visual C++ Custom Wizard. After you create your wizard, you can configure it to generate the starter files you need for your projects. For more information how to do this please ...
2,742,381
2,742,413
Getting a seg fault, having trouble with classes and variables
Ok, so I'm still learning the ropes of C++ here so I apologize if this is a simple mistake. I have this class: class RunFrame : public wxFrame { public: RunFrame(); void OnKey(wxKeyEvent& keyEvent); private: // Configuration variables. const wxString *title; const wxPoint *origin; const wxSize...
You are catching the event in an object other than the RunFrame object. Probably it's being caught in the base-object of type wxFrame. Use the runtime command wxEvtHandler::Bind<>() to bind the event, rather than an event table, and it should become clear what's happening. To verify that this is the problem, compare ...
2,742,447
2,742,477
Split string "A10" into char 'A' and int 10
Given a string consisting of a single character followed by a number (one or two digits), I would like to split it into a character and an integer. What is the easiest way to accomplish this? My thoughts so far: I can easily grab the character like so: string mystring = "A10"; char mychar = mystring[0]; The hard part ...
You can make use of the operator[], substr, c_str and atoi as: string s = "A10"; char c = s[0]; // c is now 'A' int n = atoi((s.substr(1,2)).c_str()); // n is now 10 EDIT: The above will also work if s="A1". This is because if the 2nd argument to substr makes the substring to span past the end of the string content, ...