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,318,691
5,318,901
How to get Qt Creator to work with CDB?
I'm using Qt Creator 2.01 32-bit with Qt 4.7.1 on Windows 7 64-bit. I compiled my Qt library using Microsoft Visual C++ 2010. Now I want to use CDB with Qt Creator (or GDB if that works, or whatever is the best option). What exactly do I need to do to be able to debug with CDB (so I can set break points and see symb...
Since your Qt is compiled with MSVC the best option is indeed CDB (for GDB you would need, for example, a MinGW compiled version). Debugging should be out of the box. One first point I could think is whether for some reason Qt Creator doesn't see your debugging tools for Windows. Have you made sure that the path (and t...
5,318,802
5,319,790
Switching Endian of encrypted char array
I am working on a project at school, where we set up a simple key distribution center on our network, encrypted with blowfish. I have successfully coded it and have it working on same-endian machines. The issue arises when I have to send it to a machine of a different endian. The key is encrypted as a character array, ...
It depends on the algorithm implementation. Looking at the implementation your are using (look at the BytesToBlock and BlockToBytes functions), it is casting the blocks of bytes to unsigned ints. This transformation is endian dependant and so the the algorithm will have to be adjusted based on the endianness of the ma...
5,318,842
5,318,861
How to wrap C library callbacks in C++/CLI
Given the following C library with a callback event that ask to set a buffer, how to write a proper C++/CLI wrapper in a type safe manner? // The callback signature typedef void (__cdecl *BUFFERALLOCATOR)(void *opaque, void **buffer); // A struct that contains the context of the library struct lib_context_base_s { ...
I will insist on type-safe principles: I know there's already Marshal.GetFunctionPointerForDelegate but that requires function pointer type cast in C++/CLI and hides how marshalling unmanaged->managed works (debugging is much harder and I don't like not understanding what's happening behing the scene). Just noticed the...
5,318,868
5,319,067
General function question (C++ / Java / C#)
This question is probably language-agnostic, but I'll focus on the specified languages. While working with some legacy code, I often saw examples of the functions, which (to my mind, obviously) are doing too much work inside them. I'm talking not about 5000 LoC monsters, but about functions, which implement prerequisit...
Every function/method/code block should have a precondition, which are the precise circumstances under which it is designed to work, and a postcondition, the state of the world when the function returns. These help your fellow programmers understand your intentions. By definition, the code is not expected to work if ...
5,319,179
5,319,427
QWidgetAction : how to make the menu disappear after the user completes his input
In my QMenuBar, I have several menus. One of those menus has a QWidgetAction in it. It shows up fine, but the problem is that once the user completes his input, I want the menu to disappear (as is the normal behavior for a classical QAction). However, I am not sure on how to do that. In my QWidgetAction, there is a but...
QMenu inherits QWidget, so calling yourMenu->hide() should do the work. Hope this helps.
5,319,282
5,319,376
Game engines: What are scene graphs?
I've started reading into the material on Wikipedia, but I still feel like I don't really understand how a scene graph works and how it can provide benefits for a game. What is a scene graph in the game engine development context? Why would I want to implement one for my 2D game engine? Does the usage of a scene graph...
What is a scene graph? A Scene graph contains all of the geometry of a particular scene. They are useful for representing translations, rotations and scales (along with other affine transformations) of objects relative to each other. For instance, consider a tank (the type with tracks and a gun). Your scene may have ...
5,319,516
5,319,682
Does the concept of "magic number" change from language to language?
Take the following code in C/C++, for example: int foo[] = {0, 0, 0, 0}; No magic numbers, right? Now, the Python "equivalent" of that would be: foo = [0, 0, 0, 0] Still no magic numbers. However, in Python, that same thing can be written like this: foo = [0] * 4 And now we DO have a magic number. Or do we? I'm gues...
Not every number is a magic constant. The reason 4 and the four 0 are magic numbers (in any language) is that it's entirely unclear why that number is 4 and not any other number. For example in the context of a game that is played with the well known six-sided die def roll_die(): return random.randint(1,6) this c...
5,319,556
5,319,584
STL basic_string length with null characters
Why is it that you can insert a '\0' char in a std::basic_string and the .length() method is unaffected but if you call char_traits<char>::length(str.c_str()) you get the length of the string up until the first '\0' character? e.g. string str("abcdefgh"); cout << str.length(); // 8 str[4] = '\0'; cout << str.length(); ...
Great question! The reason is that a C-style string is defined as a sequence of bytes that ends with a null byte. When you use .c_str() to get a C-style string out of a C++ std::string, then you're getting back the sequence the C++ string stores with a null byte after it. When you pass this into strlen, it will scan ...
5,319,798
5,319,857
Visual Studio confusing exception
For a robotics class I'm taking, we have to download the code from http://www.cs.okstate.edu/~katchou/vboost.cpp and place it into a project of the same name. When I debugged the program (by navigating to Debug>StartDebugging in Release mode) I got an error saying : First-chance exception at 0x6eedfb59 (msvcr100.dll) ...
The application requires 5 commandline parameters, and can take 2 optional - it'll crash if you don't pass the first 5. See lines 364-431 in the cpp file. // Name of the classifier group (i.e., new.clas) // Number of positive images. // Initialize the negative image counter. // Number of classifier levels in the casca...
5,319,851
5,319,891
Allowing the user to interface with std::strings while implementing a linked list internally?
I'm creating a textbox for my game. Most of the string related functions in the engine I'm using use std::string* or std::string& . Here is some of the constraints: The rest of my Gui API returns std::string& for the getText() function, so I need to be able to return a std::string& for the text. I implemented the textb...
Unfortunately, you really can't; the std::string class is required to have contiguous storage so that the data member function can work correctly. If you want to use a faster representation of a string for an editor buffer, such as a rope, you're going to have to have the function return something of a different type....
5,319,906
5,319,927
error: expected class-name before ‘{’ token
I know there are a couple of similar questions(circular include) out stackoverflow and other websites. But I still can't figure it out and no solutions pop out. So I would like to post my specific one. I have a Event class who has 2 and actually more subclass, which are Arrival and Landing. The compiler(g++) complains:...
Replace #include "Landing.h" with class Landing; If you still get errors, also post Item.h, Flight.h and common.h EDIT: In response to comment. You will need to e.g. #include "Landing.h" from Event.cpp in order to actually use the class. You just cannot include it from Event.h
5,320,057
5,320,088
Help with optimizing this index to row column and vice versa algorithm
Here is my issue. I have made a TextBox for my Gui in my game. What it does is, every time I resize it, because it word wraps, I have to figure out which index the caret is at in the text string, then I need to convert that into the proper row column after the reize. The slowest part according to my profiler is when I...
You're extracting a substring with: curChar = getText().substr(bytesSkipped,curCharLen); But then you only use the first element. You can avoid string construction/copying by simply extracting the char you need. On general algorithmic optimization - I'd spend the resources needed to build a deque of character objects...
5,320,105
5,320,311
Array offset and bit #
I was wondering what an array offset and what an array bit # is? for example an array offset in like a hash function. Suppose you are given x as a parameter to the hash function. The array offset could be x>>5 (x/32). The bit number could be x&0x1F (x%32). What I don't get is what constitutes an offset and what c...
It sounds like the code you are talking about is accessing bits in an array of 32-bit ints. So, say, bit #0 overall would be bit #0 of int #0, bit #31 overall would be bit #31 of int #0, bit #32 overall would be bit #0 of int #1 (since you ran out of bits in int #0), etc. So the int# to look at is the your overall bit#...
5,320,365
5,320,512
Is there any c++ tcp server on linux?
I want to develop one no-blocking tcp server with c++, is there any open source project like Twisted ?
Boost.Asio is discussed quite frequently in the boost-asio tag on SO. Copying from the tag wiki that I wrote: Most programs interact with the outside world in some way, whether it be via a file, a network, a serial cable, or the console. Sometimes, as is the case with networking, individual I/O operations ca...
5,320,374
5,320,380
c++ derived class question
suppose I have this code: class D : public Base1, Base2 {} My question is. Obviously class D is public derived from Base1, but what about Base2? Is is private derived? Or also public derived? I checked some websites but I did no find article about this. thank you!
It's private derived, inheritance method should be declared for each base class individually, if not, then it's private by default.
5,320,415
5,320,552
Whats the most basic way to go online in c++?
What is the most basic way to go to a webpage and download its contents? the webpage i wish to get only has text, most of which is in tables. is there a std library that does it (like urllib in python)?
A large number of tasks that are not covered by the C++ standard library can be done using boost, the collection of peer-reviewed portable libraries, which are used by pretty much every C++ project today. For networking, we use boost.asio. Their tutorials include HTTP clients: http://www.boost.org/doc/libs/1_46_1/doc/h...
5,320,545
5,320,556
c++ is this copy constructor?
class A {}; class B { public: B (A a) {} }; A a; B b=a; I read this from http://www.cplusplus.com/doc/tutorial/typecasting/ . It says this is a implicit type conversion. From class A to class B. I want to ask, is this also an example of copy constructor? Thanks.
No, it's not a copy constructor. A copy constructor copies one object of one type into another of the same type: B::B(const B& b) { // ... } As a side note, if you need a copy constructor then you also need a destructor and an assignment operator, and probably a swap function. What B::B(A) is is a conversion funct...
5,320,566
5,320,585
Block access to a file
i want to make a program which block any file(like autorun.inf),so that no other program can read from it(just like a way,antivirus do) with c++ in windows. please help me. thanks.
You can open a file with a dwShareMode of 0, which will Prevents other processes from opening a file or device if they request delete, read, or write access. So once your process opens the file, no other process will be able to open it, delete it, etc. MSDN Reference
5,320,636
5,320,743
Problem in Next Line in Edit Box in Win32C++
I'm having a problem where in displaying my output. Whenever I display the output instead of having multiple lines of output i only got single line output. Here is my Current code: int TextLength = GetWindowTextLength(GetEditControl) + 1; TCHAR Text[100000]; GetWindowText(GetEditControl, Text, TextLength); if(TextLengt...
Try specifying "\r\n" to separate the strings instead of just "\n".
5,320,675
5,320,744
member copying of class
While learning the concept of "copying members", the book gives the following statement. In addition, a default assignment cannot be generated if a nonstatic member is a reference, a const,or a user-defined type without a copy assignment. I do not quite understand what does this statement really want to deliver? Or w...
This statement has to do with the compiler automatically generating the default assignment operator function for a class you write (i.e. user-defined type). The default assignment works by copying all the members over to a new instance. This statement covers three cases where a default assignment would not be able to b...
5,320,878
5,321,084
Simple c++ cout statment, one line with a formatting issue, what it is?
Here is my code: #include <iomanip> #include <fstream> #include <iostream> using namespace std; int main () { ifstream fin; fin.open("Celsius.txt"); if (!fin.good()) throw "I/O error"; double myC; fin >> myC; fin.close(); ofstream fout; fout.open("Fahrenheit.txt"); if (!fo...
You must include fixed in the output stream, like so: cout << myC << " Celsius equals " << fixed << setprecision(3) << myAnswer << " Fahrenheit" << endl; setprecision will specify the number of decimal places after the decimal. So 3 will yeild a number like 72.000, or 1 in your case will set it to 72.0
5,320,894
5,320,907
Using kernel32 in .Net
Question for the SO community. I have a C++ library with full source code and I am able to compile it in 32- and 64-bit mode. However, to call the code from .NET, I must choose either 32- or 64-bit, therefore forcing my application to be either 32- or 64-bit. I decided that I may have to live with that problem... bu...
It's a feature of Windows on Windows 64 (WOW64): the File System Redirector You can't really use it for your own libraries, because it's only for the System32 folder. (Do NOT even think about putting your DLLs in System32.) Using SetDllDirectory might help, but I'm not sure.
5,320,958
5,321,011
C++ Error 1 error C2227: left of '->keyPress' must point to class/struct/union/generic type
Hi I am having trouble with my code. I got error C2227. My code: Game.h #ifndef GAME_H #define GAME_H #include "drawEngine.h" #include "Sprite.h" class Runner { public: bool run(); Runner(){}; protected: bool getInput(char *c); void timerUpdate(); private: int *gamer; double frameCount; ...
Change int *gamer; to Character* gamer; and gamer; new Character(&drawArea, 0); to gamer = new Character(&drawArea, 0);
5,321,133
5,321,315
Pointer scope in C++
Although this is a very general question, here's my specific example so you can understand what I'm asking. I have a copy constructor for a quad-tree class. So I write a recursive helper method called copy so I can call it in my copy constructor. The helper takes one parameter, a node. The root node is given as the fir...
You will end up with a new root node which is linked to the same child nodes as the original tree. So any changes made to any children will affect both trees, and you may have a double-free problem later. This is because, although you're calling copy recursively, you're discarding the return value. Furthermore, you sa...
5,321,152
5,321,165
Is it safe to cast between two unrelated types if their structures are similar?
This is piece of code from our team's small project (acdemic) class B{ public: DWORD GetLen(){return i;} DWORD i ; }; class A { public: DWORD GetLen(){return j;} public: int j ; }; B b; b.i = 2; A * pA = (A *)&b; int j = pA->GetLen(); "j" will be 2. Is this code safe? Or, what should I modify it? By using re...
Is this code safe? No. What should I do to correct it? Remove the cast and only call member functions of A on instances of A. As for what you should do instead, well, that depends entirely on what you're actually trying to do.
5,321,330
14,096,928
How do you use CheckMultisampleQualityLevels and enable multisampling
I'm learning directx 11 and trying to set up multisampling. For some reason every tutorial on the internet disables multisampling and never goes over how to enable it. First: I've searched around and can't find any examples of how to use CheckMultisampleQualityLevels. It seems like you need to create a device, call...
1.Call ID3D11Device::CheckMultisampleQualityLevels, which gives you the quality level supported by the adapter. 2.While filling out the DXGI_SWAP_CHAIN_DESC, set the SampleDesc.Count and SampleDesc.Quality. 3.If multi-sample antialiasing is being used, all bound render targets and depth buffers must have the same sampl...
5,321,551
5,327,413
How can I write a sentence converse algorithm using higher level C++ code?
run this code. you can reverse "live long and prosper" to "prosper and long live" . #include <stdio.h> #include <string.h> void rev(char *l, char *r); int main(int argc, char *argv[]) { char buf[] = "live long and prosper"; char *end, *x, *y; // Reverse the whole sentence first.. for(end=buf; *end; end++); rev(buf,...
Here's one way to do it in C++: #include <iostream> #include <string> #include <vector> #include <sstream> #include <iterator> int main() { std::istringstream converter("live long and prosper"); std::vector<std::string> words( (std::istream_iterator<std::string>(converter)), std::istream_iter...
5,321,664
5,321,710
Checking whether a cross-cast could possibly work?
I know that it's legal to use dynamic_cast to do a "cross-cast" across a class hierarchy. For example, if I have classes that look like this: A B \ / C If I have an A* pointer that's pointing at an object of type C, then I can use A* aPtr = /* ... something that produces a C* ... */ B* bPtr = dynamic_cast<...
It's not possible to detect this at compile-time. The class C that introduces the relationship could be found in a dynamically loadable library that hasn't even been written yet, and the compiler can't prove otherwise. There may be a few exceptions though. If A has only private constructors (or a private destructor) ...
5,321,979
5,322,139
CppCheck: Variable 'bla' is not assigned a value
running CppCheck over my codebase produces some style warnings. E.g. in void foo(int& x) { x = 0; } void bar() { int y; foo(y); } it gives me Variable 'y' is not assigned a value It's the same with code like char buffer[160]; i+=sprintf(buffer,"%2.2ld.",ymd.monthday); Is this a problem with my code or is ...
It's a bug in CppCheck and the good news is that it has already been fixed! You can either grab the latest code and build your own version or wait for v1.48 to be released. Version 1.48 is planned to be released on April 9th according to the wiki.
5,322,216
5,322,236
How to print a string in C++
I tried this, but it didn't work. #include <string> string someString("This is a string."); printf("%s\n", someString);
#include <iostream> std::cout << someString << "\n"; or printf("%s\n",someString.c_str());
5,322,312
5,322,366
abc interface inheritance and re-exposing methods in base class
I am curious if there is a neat way to expose methods in the base class of a derived interface. So in code: - class cbase { public: void MyMethodA() { } }; class cderived : public cbase { public: void MyMethodB() { } } class ibase { public: virtual void MyMethodA() = 0; }; class iderived : public ibase { publ...
If I understand correctly you want to make ibase a virtual base class of iderived and cbase. This was there is only one instance of each of your interface classes in the class hierarchy and when you join cbase and iderived together at the cderived level the non-virtual override of MyMethodA in cbase is used because it ...
5,322,470
5,322,488
What does the destructor do silently?
Considering the following code which looks like that the destructor doesn't do any real job, valgrind showed me clearly that it has memory leak without using the destructor. Any body can explain me what does the destructor do in this case? #include <iostream> ...
The insert() method creates new A on the heap and links it to the next element with the follower pointer. So without the destructor on A, the object pointed to by follower never gets deleted.
5,322,477
5,322,500
Unsafe, super-fast cross-process memory buffer?
Cross-process memory buffers always have some overhead, and my understanding is this is quite high. But what if you're implementing a cross-process render-buffer, this isn't critically important in the same way as other data, so are there techniques we can use to get 'raw' access to a chunk of memory from multiple proc...
Memory mapped files are the way to go here. Windows: CreateFileMapping() (example of CreateFileMapping() & MapViewOfFile()) POSIX: mmap()
5,322,581
5,322,931
cuda and c++ problem
hi i have a cuda program which run successfully here is code for cuda program #include <stdio.h> #include <cuda.h> __global__ void square_array(float *a, int N) { int idx = blockIdx.x * blockDim.x + threadIdx.x; if (idx<N) a[idx] = a[idx] * a[idx]; } int main(void) { flo...
Code which has CUDA C extensions has to be in *.cu file, rest can be in c++ file. So here your kernel code can be moved to separate *.cu file. To have main function implementation in c++ file you need to wrap invocation of kernel (code with square_array<<<...>>>(...);) with c++ function which implementation needs to ...
5,322,610
5,322,672
Why is this simple program giving a segmentation fault?
I have written a simple C++ program. The idea is, once it sees a non-alphabetic character, then till the time it see a new word (a blank) or the string ends, it keeps on incrementing the iterator. This generates Segmentation fault, no idea why :( Please help. #include <iostream> using namespace std; int main() { str...
while((*it!=' ')||(it!=str.end())) *it is evaluated before checking if it itself is ok to use. Change to: while((it!=str.end())&&(*it!=' '))
5,322,726
5,322,785
Is there a default implementation of graph data structure in Qt?
Is there a implementation of graph data structure in Qt with default operations for nodes and edges built-in?
I don't know of any Qt graph classes, but there is a nice Boost Graph Library: More here: http://www.boost.org/doc/libs/1_46_1/libs/graph/doc/index.html
5,322,956
5,323,292
Few questions about C++ compilers : GCC, MSVC, Clang, Comeau etc
I've few questions about C++ compilers Are C++ compilers required to be one-pass compiler? Does the Standard talk about it anywhere? In particular, is GCC one-pass compiler? If it is, then why does it generate the following error twice in this example (though the template argument is different in each error message)? ...
The standard sets no requirements what so ever with regards to how a compiler is implemented. But what do you mean by "one-pass"? Most compilers today do only read the input file once. They create an in memory representation (often in the form of some sort of parse tree), and may make multiple passes over that. And...
5,323,163
5,323,950
How to convert colour to greyscale image in openCV?
Hi I have read the openCV reference from this site and using the following code: VideoCapture mCap; Mat mcolImage, mbwImage; mCap >> mcolImage; // New frames from the camera cvtColor( mcolImage, mcolImage, CV_BGR2RGB); cvtColor( mcolImage, mbwImage, CV_RGB2GRAY); QImage colI...
You need to explicitly set a gray color table for bwImagetmp: QVector<QRgb> colorTable; for (int i = 0; i < 256; i++) colorTable.push_back(qRgb(i, i, i)); bwImagetmp.setColorTable(colorTable);
5,323,362
5,323,497
Return Arabic from JNI call
I have been trying to return an ARABIC string from a JNI call. The java method is as follows private native String ataTrans_CheckWord(String lpszWord, String lpszDest, int m_flag, int lpszReserved); lpszWord : Input English lpszDest : Ignore m_flag : Ignore lpszReserved :Ignore Now when I use javah to generate the h...
Java strings are internally UTF-16, an encoding which uses 2 or 4 bytes per character. Your translation system seems to return strings encoded in a MBCS (Multi-Byte Character Set) - 1-N bytes per character. The JNI NewString function expects data encoded as UTF-16, and you're passing it something else - so in java you...
5,323,580
5,323,726
Printing contents of a linked list with Visual Studio's debugger
I have a crash dump. This crash dump contains a doubly-linked list with 15000 nodes whose head pointer is null, but still has a valid tail. In order to figure out whether the head pointer was wiped out by a logic error or heap corruption, I need to walk backwards from the tail, up to the first valid node. If I can reac...
There is this article showing how to write custom visualizers for Visual Studio: http://www.virtualdub.org/blog/pivot/entry.php?id=120, including lists. There is a comment asking about visualizers for doubly-linked lists, and apparently this should work: typedef struct _Stream ( struct _Stream *p_next, struct _Stream *...
5,323,644
5,323,887
uniform sampling of a 3D model
I seek for a method/algorithm for uniform sampling of the surface of 3D models in C++. I have found methods for uniform sampling of unit sphere such as this and this but I need something that would work also for more complex 3D models that may also be concave. thanks in advance
What I do: My model consists of many different primitives (triangles, quads, disks, cylinder...). For each primitive I can implement a random picking method (e.g. http://mathworld.wolfram.com/TrianglePointPicking.html). Each primitve can compute its surface Area. The higher the area of the primitive the higher its prob...
5,324,057
5,324,157
Post-condition for a function/method
Did anyone of you ever documented a function or method with pre and post conditions? (I'm asking because my teacher says that's the official/correct way to do it): Legend: (for I couldn't type special chars) 3 - read it as "there exists" '&exist' E - is a member of (as in set) A - for all --> - implies Suppose t...
Yup. I've come across it, though it is not normal practice in industry. In certain context, it would definitely count as best practice to formally specify the preconditions, postconditions and invariants. For example: when using formal methods; e.g. for formally proving that programs are correct, or when using a pro...
5,324,060
5,324,085
how to design const member function, preventing it from modifying the object
This a const member function, which allow me to get the minimum node of the tree: BinarySearthTree* BinarySearchTree::min() const { // Return the minimum node (left-most node) value of the t...
Make next const: const BinarySearthTree* BinarySearchTree::min() const { // Return the minimum node (left-most node) value of the tree const BinarySearchTree *next;...
5,324,081
5,324,133
Problem in implementing Stack using Vector
In a class say: class X { int _top; vector<int> _stack; public: X() { } // SOME CONSTRUCTOR }; Why does a constructor of this form works: X( int capacity ) : _stack( capacity ), _top( 0 ) { } But these do not work: 1. X( int capacity ) { _stack( capacity ); _top=0; } 2. X( int capacity ) {_...
The first one works, because you're initializing _stack in initialization list, while the second form doesn't use initialization list. Read the comments in this code to understand what is initialization list! struct sample { int a,b,c; vector<int> _stack; sample(int capacity) : _stack(capacity), a(1), b(10...
5,324,139
5,324,228
fastest data structure for retrieval info c++
I am Developping Client Application which is a simulator for TCP client may have to simulate 1000 client. each client status info can be of the size 50 byte.The state info is required by the server and client simulator need to store some where. Server can request any client about status info.So for this scenario I want...
It depends on what you need to do with it. If it's just a simple lookup then use a stl::map (in STL this is typically implemented as a tree so you have O(lg N) lookup). If there are only 1000 and you have some control over the identifier, why not use an array? This will (obviously) give you O(1) access to any elemen...
5,324,256
5,325,052
Is const_cast<const Type*> ever useful?
Recently I found a piece of C++ code that effectively does the following: char* pointer = ...; const char* constPointer = const_cast<const char*>( pointer ); Obviously the author thought that const_cast means "add const", but in fact const can be just as well added implicitly: const char* constPointer = pointer; Is t...
const_cast, despite its name, is not specific to const; it works with cv-qualifiers which effectively comprises both const and volatile. While adding such a qualifier is allowed transparently, removing any requires a const_cast. Therefore, in the example you give: char* p = /**/; char const* q = const_cast<char const*>...
5,324,404
5,324,452
Side effects of assigning a pointer value to a variable in C++
I'm running into some strange problems when assigning the reference of a pointer to a variable: the local code works correctly, but it causes memory access errors elsewhere: //This works fine Gridcell* g = model.gc; cout << g->LC_updated << " " << g << endl; //When I include this, the program crashes elsewhere //But o...
You need to make sure that Gridcell has a proper copy constructor. This is only required if Gridcell manually manages resources, which almost never should be the case. If it the the case for you, you will need The Big Three. If you need more specific help, post the class definition of Gridcell, along with constructors ...
5,324,903
5,325,234
Refactoring c++ template class based on template type
Given class Foo template <typename T> class Foo { public: ...other methods.. void bar() { ... m_impl.doSomething(); ... } void fun() { ... m_impl.doSomethingElse(); ... } void fubar() { ... } private: T m_impl; }; I wanted to cater for situations where T is a boos...
Sylvain wrote a DRY solution, but I don't like abusing inheritance. Using a wrapper class to uniformize the interface is easy, especially since pointer semantics work so well! namespace details { template <typename T> struct FooDeducer { typedef boost::optional<T> type; }; template <typename T> struct Fo...
5,325,122
5,326,725
Rework for loop over STL container to use functional techniques
I have a std::vector of pointers Person objects, which have a member function std::string getName() const. Using STL algorithms I want to count all the Person objects in the vector where getName() returns "Chad". The behaviour simply iterating over the loop would be: int num_chads = 0; for(std::vector<Person *>::const_...
Since nobody posted the actual boost code yet, C++98 with boost: ptrdiff_t num_chads = std::count_if(vec.begin(), vec.end(), boost::bind(&Person::getName, _1) == "Chad"); test run https://ideone.com/PaVJe As for pure C++, I don't think it's possible without the compose1 adaptor, present in STL bu...
5,325,202
5,327,137
boost::unit_test case fails because a child process exits with nonzero
I have the following code: bool f() { command = "mkdir -p /\/\/"; result = aSystemCall(command); if (result == ... } BOOST_AUTO_TEST_CASE(BadDir) { BOOST_CHECK_EQUAL(false, f()); } If I execute command in command line, I get a permission denied error. I'm aware of this. That's exactly what I want to test. aSy...
This is resolved in later version of Boost.Test
5,325,302
5,466,578
C/C++ Code Examples with HTK (Hidden Markov Toolkit)
I am trying to get started with HTK, I grabbed a copy, compiled it, grabbed the book, and all went more or less fine, little troubles here and there but nothing serious. Now after reading the book and googling quite a while, I do not see any documentation for the essential part for me: HTKLib. Everything is described i...
Maybe ATK is more suitable for you. Here is the explantation from the ATK site: "ATK is an API designed to facilitate building experimental applications for HTK. It consists of a C++ layer sitting on top of the standard HTK libraries." In addition Microsoft Research has another research tool here for training acoustic...
5,326,118
5,326,145
Compiling problems dealing map.find and initialization
I've written a class in c++ named 'Sync'. Then, i've created a map holding Sync objects, associated with syncID num, as follows: map<int, Sync*> _syncList; In one of my methods, I'm trying to search for an existing Sync object in my map, according to a given syncID number, as follows: Sync* currS = *(_syncList.find(sy...
Two things: Get rid of the asterisk: Sync* currS = _syncList.find(sync_id)->second; Be sure that find() actually finds an element (or else you need to check the return value of find() for map<...>::end).
5,326,251
5,326,283
How to convert void (__thiscall MyClass::* )(void *) to void (__cdecl *)(void *) pointer
I want to build a "IThread" class which can hide the thread creation. Subclass implements the "ThreadMain" method and make it called automatically which seems like this: class IThread { public: void BeginThread(); virtual void ThreadMain(void *) PURE; }; void IThread::BeginThread() { //Error : cannot conver...
You can't. You should use a static function instead (not a static member function, but a free function). // IThread.h class IThread { public: void BeginThread(); virtual void ThreadMain() = 0; }; // IThread.cpp extern "C" { static void __cdecl IThreadBeginThreadHelper(void* userdata) { IThread*...
5,326,332
5,326,349
How robust are windows messages?
If i queue a message with PostMessage (and it return true) can i be certain that eventually the window will process the message unless some catastrophic event happen?(something which will crash the program anyway)
Once posted messages don't disappear from the queue. One of our products is a Windows service that uses Windows messages to communicate between threads and it relies on them heavily. So far the only problem we've seen is that if you post them too fast the queue just fills and doesn't accept more messages until someone ...
5,326,525
5,343,244
Class Interfaces: Basic or Complex?
I'm writing a container class for fun and education. Previously when writing container classes I had limited myself to just a few very basic methods: GetValue, SetValue, GetSize and Resize. I did this to avoid "code spaghetti" so my class would be easier to debug. However, it occurred to me that users of the class mi...
Classes should only provide a basic/minimal interface of member-functions (and preferably no data!). You can then add convenience methods as non-friend non-member functions. According to the interface-principle however, these functions are still part of your classes interface. You already named the prime reason for th...
5,326,562
6,220,185
Convert C++ AlphaVSS DLL from framework 2.0 to 4.0
I'm trying to convert AlphaVSS to Framework 4.0, but when I try to compile I receive error c1010070: Failed to load and parse the manifest. Impossibile trovare il file specificato. <mypath>\AlphaVSS-1.0-Beta\Source\Obj\WinXP\x64\AlphaVSS.Platform.vcproj.dll.intermediate.manifest AlphaVSS.Platform.vcproj. What can I d...
AlphaVSS 1.2 beta1 is now released which targets the .NET 4 framework if you prefer not to use the App.config approach.
5,326,564
5,329,413
C++ Boost.ASIO: passing accepted TCP connection from one opened socket to another using Windows APIs ( while works with Linux APIs)?
I was trying to learn how to re assign accepted connection using Boost.ASIO and Windows API's. found this code sample added to it includes and use of namespaces so now it is compilable - just copy and paste and here you go... "The parameter is incorrect" exception at the same place code poster had it=( So here is code:...
Try using the code snippet attached to the WSASocket documentation: socketDup = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, &pi, 0, WSA_FLAG_OVERLAPPED); Ok, I traced through the Boost code, and it fails trying to associate the socket with the I/O completion port. That's because the socke...
5,326,708
5,326,803
What is the best way to binarize data
I have some data files that are written as tag = value, where tag is string and value may be numeric, string, array, etc. I use this format because is readable and can be edited easy. Now every class that is instantiated using this format has a load method and it reads the tags that it needs and use the values found wi...
I have a serialization base class for this, with To/From functions with a small header where version handling can be embedded. I think its a good system for simpler data that needs to be stored locally and in most cases is "read only". Something like this: class SeralizeMe { public: virtual bool To(Archive &file)=0;...
5,327,130
5,327,909
Returning a reference to data held by boost::any
I've got a map of any pointers, called gmap, defined like so: std::map<std::string, boost::any*>& gmap = getSingleton().globalValues; This map is indeed a reference to globalValues, I've checked the addresses in gdb. I've also got control of the any pointers (which is why they are pointers, I'd rather do references, b...
This is odd, but I figured it out. Ignoring the fact that it says if T is a reference, it'll return one; I passed it a pointer and got the correct pointer. But for whatever reason, I can't just dereference the return value and return. First I had to store that pointer in an explicit local (as opposed to implicit), de...
5,327,237
5,328,145
Private member vector of vector dynamic memory allocation
I'm new to C++ (I learned programming with Fortran), and I would like to allocate dynamically the memory for a multidimensional table. This table is a private member variable : class theclass{ public: void setdim(void); private: std::vector < std::vector <int> > thetable; } I would like to set the dimension of th...
Thank you everybody for your comments. I was on the way to do a small source code with only the problematic part, and as I tried to run it, it worked... I was very confused so I tried to find the differences between the instructions. Finally, I figured out that I forgot a #include <vector> in one of the source file (...
5,327,340
5,329,748
Ruby vs Lua as scripting language for C++
I am currently building a game server (not an engine), and I want it to be extendable, like a plugin system. The solution I found is to use a scripting language. So far, so good. I'm not sure if I should use Ruby or Lua. Lua is easier to embed, but Ruby has a larger library, and better syntax (in my opinion). The pro...
I've used Lua extensively in the past. Luabind is really easy to use, there is no need for an external generator like SWIG, the doc is great. Compile times remain decent. Biggest problem I've seen : lua is mostly ... write-only. You don't really have classes, but only associative arrays with a bit of syntaxic sugar ( o...
5,327,408
5,327,467
std string vs char performance, best technique to delete parts from the beginning
well i have to process a large chunk of text, analysing it linear from begin to end. And i wonder what is the better approach for this: using char* or std::string. while using char* i can alter the pointer to a position further in the string eg. //EDIT later: mallocing some space for text char str[] = "text to analyse"...
With std::string, you would probably use std::string::iterator. Your code would be: std::string str = "text to analyse"; std::string::iterator iter = str.begin(); // process iter += processed_chars;
5,327,638
5,329,686
Fast/Efficent Pixel Access in Magick++
As an educational excercise for myself I'm writing an application that can average a bunch of images. This is often used in Astrophotography to reduce noise. The library I'm using is Magick++ and I've succeeded in actually writing the application. But, unfortunately, its slow. This is the code I'm using: for(row=0;row<...
Why use vectors/arrays at all? Why not double red=0.0, blue=0.0, green=0.0; for(i=1;i<10;i++) { ColorRGB rgb(image[i].pixelColor(column,row)); red+=rgb.red(); blue+=rgb.blue(); green+=rgb.green(); } red/=10; blue/=10; green/=10; This avoids 36 function calls on vector objects per pixel. And you may get eve...
5,327,666
5,327,713
Syntax for class within a class in C++
If I have the following class A { public: int stuff; void helper(B temp, int d); //what about here? I'm getting a 'B' has not been declared error here. private: class B { public: int stuffer; private: int x; }; }: What...
First of all, class name cannot start with integer. So renaming them: class A { public: int stuff; private: class B { public: int stuffer; private: int x; }; }; Second, since the nested class B is in the private section, so you cannot...
5,327,894
5,411,966
Cannot convert 'vector<unsigned long>' to Python object
I am trying to wrap a c++ function with signature vector < unsigned long > Optimized_Eratosthenes_sieve(unsigned long max) using Cython. I have a file sieve.h containing the function, a static library sieve.a and my setup.py is as follows: from distutils.core import setup from distutils.extension import Extension fr...
If you only need to call you function for C++, declare it with cdef instead of def. On the other hand, if you need to call it from Python, your function has to return a Python object. In this case, you'll probably make it return a Python list of integers.
5,328,070
5,328,184
How to convert string to IP address and vice versa
how can I convert a string ipAddress (struct in_addr) and vice versa? and how do I turn in unsigned long ipAddress? thanks
Use inet_ntop() and inet_pton() if you need it other way around. Do not use inet_ntoa(), inet_aton() and similar as they are deprecated and don't support ipv6. Here is a nice guide with quite a few examples. // IPv4 demo of inet_ntop() and inet_pton() struct sockaddr_in sa; char str[INET_ADDRSTRLEN]; // store this IP...
5,328,075
5,328,862
Security issues with online-judge
I am involved in making an online-programming-judge supporting C/C++ like SPOJ,UVA etc on Linux machine(Ubuntu). The code itself is in C++ . I have to prevent the server from malicious code. I plan to implement security in 2 steps. 1. By jailing (sandboxing) the executing code with chroot system call in a folder with r...
The single biggest security risk of running something like this is the possibility of making outgoing network connections on port 25. Someone will find your service, make thousands of dollars spamming, and you'll get banned by your host. Plus you'll make everyone else on your hosting provider/isp hate you for getting t...
5,328,102
5,328,147
Sharing runtime variables between files
I have a project with a few files that all include the header global.hpp. Those files want to share and update information that is relevant for the whole program during runtime (that data is gathered progressively during the program runs but the fields of data are known at compile-time). Now my idea was to use a struct...
It is a possible solution, but not a very clean one. Creating a single session_struct in main and passing that around as an argument (by reference), or storing references/copies/shared pointers in all classes that needs access to the session data, is much cleaner. What happens when multithreading comes into play is tha...
5,328,150
5,328,303
How to avoid conflict in two header file c++
I am using two lib jsoncpp and imap (lib c-client). json cpp have write function . but in imap lib they have some macro #define write safe_write which is overriding some macro from jsoncpp . I am not able to use both library at same time. how can I avoid this conflict ?
Assuming you don't use write macro from imap: #include "imap.h" #undef write #include "jsoncpp.h"
5,328,411
5,328,910
Effective use of C++ iomanip library
I created a Vector class in C++ and it works great for my problems. I am now cleaning it up, and I ran into the following piece of code: std::ostream& operator<<(std::ostream &output, const Vector &v){ output<<"[" <<std::setiosflags(std::ios::right | std::ios::scientific) <<std::setw(23) <<std::setprecisi...
Only std::setw() is temporary. The other two calls, setiosflags, and setprecision have a permanent effect. So, you could change your code to : std::ostream& operator<<(std::ostream &output, const Vector &v){ output<<"[" <<std::setiosflags(std::ios::right | std::ios::scientific) <<std::setw(23) <<std::setp...
5,328,414
5,328,454
Overloaded functions in C++
Are this functions overlaoded functions ? void f(int a, int b) {} void f(int& a, int& b) {} void f(int* a, int* b) {} void f(const int a, const int b) {} Or overloading functions occurs only when the number or type of arguments differ ?
Number 1, 2, 3 are. Number 4 redeclared number 1. You see, top-level const-qualifiers don't affect the function declaration. They alter the way in which you use them inside a function definition, but it's still the same function void f(int); void f(const int); //redeclares void f(const int x) //same as above { x = 4...
5,328,447
5,328,531
object initialization
In the book of "The C++ Language", the author claimed Sometimes, when you design a library, it is necessary, or simply convenient, to invent a type with a constructor and a destructor with the sole purpose of initialization and cleanup. Such a type would be used once only: to allocate a static object so that the const...
The C++ standard does not specify the order in which the static objects are created. Therefore, if you need some hierarchy in static objects, you need them to depend one on another (e.g., one should be the member of the other). The construct from the book guarantees this behaviour. For example, a hypothetical game engi...
5,328,511
5,328,583
Whats the Difference between a . and -> in calling a Method in C++
Can you tell me the difference between a . and -> call to a method in C++. This code works fine, using both calling methods. #include <iostream> using namespace std; class myclass { public: string doSomething(); }; string myclass::doSomething() { return "done something\n"; } int main (int argc, con...
The arrow operator is meant for calling a method from a pointer to an instance of an object. The dot operator is meant for calling a method from a reference to an instance of an object, or on a locally defined object. Your code would not compile if you reversed the operators on the two examples.
5,328,544
5,328,581
Returning char array as std:string
Is the following safe as is, without an explicit cast or call to std::string constructor? If not safe, why not? std:string myfunc() { char buf[128] = ""; // put something into buf or not base on logic. return buf; }
Yes. That is perfectly fine. The caller will get a copy of the local buffer, because std::string would make a deep-copy out of this local buffer! EDIT: I'm assuming the buf is null-terminated string!
5,328,594
5,329,356
Delphi alternatives to some File I/O C++ lib functions?
fopen_s <--> OpenFile fclose <--> CloseFile Is my assumption correct? I wonder what is better to use, OpenFile or CreateFile. The latter gives more freedom, but is it faster?
I would use neither in Delphi – I would use streams. Low level file handling is messy and error-prone, it's much better to use higher level routines if you can. You ask which is faster, OpenFile or CreateFile. They are basically the same, but any method of opening a file is going to map onto the system call anyway so t...
5,328,815
5,328,946
What happens when I subtract an unsigned integer from a signed integer in C++?
What happens if I do something like this: unsigned int u; int s; ... s -= u; What's the expected behavior of this: 1) Assuming that the unsigned integer isn't too big to fit in the signed integer? 2) Assuming that the unsigned integer would overflow the signed integer? Thanks.
In general, consult 5/9 in the standard. In your example, the signed value is converted to unsigned (by taking it mod UINT_MAX+1), then the subtraction is done modulo UINT_MAX+1 to give an unsigned result. Storing this result back as a signed value to s involves a standard integral conversion - this is in 4.7/3. If the...
5,328,873
5,329,095
C++ Streams vs. C-style IO?
I was coding some C++ for a small hobby project when I noticed that I'm using C-style operations to access IO (printf, fopen, etc.). Is it considered "bad practice" to involve C functions in C++ projects? What are the advantages of using streams over C-style IO access?
This is an heated topic. Some people prefer to use the C++ IO since they are type-safe (you can't have divergence between the type of the object and the type specified in the format string), and flow more naturally with the rest of the C++ way of coding. However, there is also arguments for C IO functions (my personal ...
5,328,952
5,329,056
class exporting error (error C2470: looks like a function definition)
I can't export a class: #ifndef SDBIDI #define SDBIDI #ifndef SDBIDI_FLAG #define SDBIDI_ORIENT __declspec(dllimport) #else #define SDBIDI_ORIENT __declspec(dllexport) #endif #include "TCInfoSuVars.h" //class is here! SDBIDI_ORIENT int myFoo(FILE *file); // exporting function #endif class definition in TCInfoSuVars...
Somewhere you're including TCInfoSuVars.h before SDBIDI_ORIENT is defined - Make sure you include the header file that defines SDBIDI_ORIENT first.
5,328,976
5,329,109
static array variables would need to be locked?
so let's say that I have a static variable, which is an array of size 5. And let's say I have two threads, T1 and T2, they both are trying to change the element at index 0 of that array. And then use the element at index 0. In this case, I should lock the array until T1 is finished using the element right? Another ques...
Synchronization in java is (technically) not about refusing other threads access to an object, it about ensuring unique usage of it (at one time) between threads using synchronization locks. So T2 can access the object while T1 has synchronization lock, but will be unable to obtain the synchronization lock until T1 rel...
5,329,033
5,329,234
C++ Template meta-magic, template call-site qualification deduction mechanism
I apologise for the verbosity of this example, I contrived it out of a project. The commented, Item 1 and item two, are important in the following code. #include <boost/intrusive/set.hpp> struct x : public boost::intrusive::set_base_hook<> { int y; }; struct finder { bool operator()(const int & i, const x & _...
Wouldn't the find() member function of boost::intrusive::set simply have a const and non-const overload? I mean, that's how I would do it: template <typename T /*...*/ > class set { //... public: template <bool isConst> class iterator { //.... }; iterator<true> find(/*..*/) const; //notice th...
5,329,066
5,330,469
Integrating Flex/Bison with external program
I'm working on an intelligent agent model that requires, as input, a list of events. The events come from the output of another model and are in a (large) text file. The text file is a list of all events (including unnecessary events that I don't care about), so I've written a scanner using flex that can find the use...
If your grammar is that simple then using a parser seems overkill. Just process each line and scan the tokens into a collection. Why do you think you need a parser?
5,329,100
5,329,124
what happens if malloc (STL allocator, etc)requested to allocate 0 bytes
Possible Duplicate: what does malloc(0) return ? Does it return zero pointer? Is the behavior standardized? How about STL allocator? I googled it, but couldn't pinpoint the answer I was looking for. EDIT: The linked question doesn't explain STL allocator. I have another relevant question. What happens if one tries ...
malloc(0) may either return 0 or it may return a unique address (which shall not be accessed) -- the C89 and C99 Standards allow either behavior but do not mandate either one. (Bad design for a standard and I objected when I was on X3J11 but that's how it is.) BTW, this is a duplicate question: what does malloc(0) retu...
5,329,107
5,329,380
Passing a pointer representing a 2D array to a function in C++
http://www.neilstuff.com/guide_to_cpp/notes/Multi%20Dimension%20Arrays%20and%20Pointer%20Pointers.htm According to this site, I should be able to use the following code: double stuff[3][3]; double **p_stuff; p_stuff = stuff; But I get a complaint that the conversion is not allowed by assignment. Am I doing something w...
Regarding the edit: to pass this double stuff[3][3] to a C function, you could 1) pass a pointer to the whole 2D array: void dostuff(double (*a)[3][3]) { // access them as (*a)[0][0] .. (*a)[2][2] } int main() { double stuff[3][3]; double (*p_stuff)[3][3] = &stuff; dostuff(p_stuff); } 2) pass a pointer to ...
5,329,312
5,331,521
Free implementation of "bounded priority queue" in C++
I'm looking for a free software implementation of the bounded priority queue abstraction in C++. Basically, I need a data structure that will behave just like std::priority_queue but will at all times hold the "best" n elements at most. Example: std::vector<int> items; // many many input items bounded_priority_queue<in...
I think that the algorithm discussed in this thread is probably what you are looking for. If you want to get a head start, you might want to consider building upon Boost's implementation d_ary_heap_indirect which is part of Boost.Graph (in d_ary_heap.hpp). If you do a good job with it, you might submit it to Boost. It ...
5,329,391
5,330,517
ResolveVCProjectOutput failure
We just recently started getting warnings on our build system which are eventually causing the build to fail. The build works fine if I build in the VS2005 IDE. The error seems to boil down to the following error: Task "ResolveVCProjectOutput" skipped, due to false condition; ( ('$(Configuration)' == 'Debug') and ('$(P...
I had a mysteriously similar problem when building VC++ projects prior to VS 2010. What happens is that vcbuild.exe (which is eventually used when building .vcproj files even from msbuild) parses the project file and freezes the value of $(Configuration) on the first one that is found. The evaluation of any other str...
5,329,573
5,338,033
What is the defacto standard for sharing variables between programs in different languages?
I've never had formal training in this area so I'm wondering what do they teach in school (if they do). Say you have two programs in written in two different languages: C++ and Python or some other combination and you want to share a constantly updated variable on the same machine, what would you use and why? The infor...
When asking particular questions, you should aim at providing as much information as possible. You have added a use case, but the use case is incomplete. Your particular use case seems like a very small amount of data that has to be available at a high frequency 10kHz. I would first try to determine whether I can actua...
5,329,638
5,329,671
/usr/bin/ld: cannot find
I created a .so file and put it in the location /opt/lib and added this path to LD_LIBRARY_PATH now after this when I try to compile my main program with the following command: g++ -Wall -I/home/alwin/Development/Calculator/ main.cpp -lcalc -o calculator I get the following error: /usr/bin/ld: cannot find -lcalc colle...
Add -L/opt/lib to your compiler parameters, this makes the compiler and linker search that path for libcalc.so in that folder.
5,329,848
5,339,234
gauss-legendre in c++
i am trying to create gauss-legendre code according to the following algorithm: for n points That is,it is created a 2n equation system (if we demand to be accurate for polynominals of order 2n-1 , ti are roots of the legendre polynominals of order n.The legendre poynominals are given : and wi : My code is : #inc...
I do not know the algorithm but your code is wrong. First : while(n<10) { L[0]=1; L[1]=x; //legendre coef for (int i=1;i<=10;i++){ L[i+1]=((2.0*i+1.0)*x*L[i] - i*L[i-1])/(i+1.0); } You must change the value of n (increment, decrement, etc.) otherwise th...
5,329,902
5,329,958
what does "layout-compatible with C" mean?
It is said that stl vector is "layout-compatible with C". Where can I find the definition of "layout-compatible with C"?
This means that, as long as the vector is not empty, &vector.front() will give you a pointer to a contiguous array of objects, which could be passed to a C API that expects such an array.
5,329,913
5,329,950
programming tests/questions
Does anybody know a good reference I can use to prepare for interview questions/tests about c++ programming? From basic questions about OO programming to advanced ones. Thank you,
Check out C++ -FAQ lite by Marshall Cline. It covers almost everything that might be asked in a C++ technical interview
5,329,963
5,330,108
what to link with v8 under windows
I've been trying to get to get a basic v8 program working under visual studio 2010. I've been able to build v8.lib and v8.dll with no problems. I placed the .v8.dll in my debug folder, and added the v8.lib to VC lib folder. I added v8.lib to my list of additional dependencies, but when I try and build anything using v...
You are missing the kernel32.lib dependency. Getting it from a file named MSVCRTD.lib is very fishy, that's the import library for the CRT. Do make sure that whatever 'framework' you are using isn't trying to replace it. And make very sure that you haven't been copying .lib files to try to solve another linker probl...
5,330,020
5,330,064
Initiating a derived class with specific variable values
For the below code snippet, how do I initialize instances of class Enemy with variables (such as x, y, type)? I have it working correctly, it triggers the instances no matter how many of them I insert... I just need to know the best way of creating an enemy with certain variables that will differ for each of my instanc...
Include the arguments in the enemy constructor and Base constructors. You can then use those to initialize the member variables. class BaseObject { public: BaseObject(int x, int y) : x(x), y(y){ } virtual void Render() = 0; int x; int y; }; and class Enemy : public BaseObject { public: Enemy(int ...
5,330,196
5,330,259
Overriding methods by changing typedef in ancestor - possible?
I am trying to base my application on callbacks. The issue that bothers me the most is that I have to specify what arguments does the lambda function take. My base class that all others extend does specify two basic types. It looks like this: class Callback { typedef function<void()> Function; typedef vector< p...
Types are not virtual; you cannot "override" them in a derived class. From my somewhat limited understanding of what you're trying to do, I think you should make Callback a template. Something like this: template<typename ArgType> class Callback { typedef function<void(ArgType)> Function; typedef vector< pair<s...
5,330,203
5,330,269
Remove duplicate items without rounding, C++
I am trying to remove duplicate items from vector using the following comparator bool operator() ( const Point * p1, const Point * p2 ) const { return ( p1->X() < p2->X() ) || ( ( p1->X() == p2->X() ) && ( p1->Y() < p2-Y() ) ); } and overloaded opeartor == bool P...
Operator == does not bring any effect, near points are not sorted next to each other... If the type of x and y is float or double, then equality cannot be done reliably. Consider using numeric_limits<double>::epsilon() or numeric_limits<float>::epsilon() when comparison! Is DIFF in your implementation equal to numer...
5,330,287
5,330,408
What is an Anonymous Object?
What is an Anonymous Object exactly? Does C++ support/have Anonymous Objects?
The C++ standard does not define the term "anonymous object", but it stands to reason that one might sanely use the term to describe any object that has no name: Temporaries: f(T()); Unnamed function parameters: void func(int, int, int); What I wouldn't count is dynamically-allocated objects: Technically speaking, an...
5,330,333
5,330,357
Problem with my method in C++
I have a class like so: class Qtree { public: Qtree(); Qtree(BMP img, int d); private: class QtreeNode { public: QtreeNode* nwChild; // pointer to northwest child QtreeNode* neChild; // pointer to northeast child QtreeNode* swChild; // pointer to southwest child QtreeNode* se...
try: static QuadtreeNode copy(QuadtreeNode & n); or better create copy constructor. copy is instance method, it means that it can be run only with object provided. It's internal signature as a function is: QuadtreeNode copy(QtreeNode* this, QuadtreeNode & n); So you have to pass to parameters. Notation obj->copy(..) ...
5,330,459
5,330,758
Ownership/delete'ing the facet in a locale (std::locale)
I wrote the following function to get a date/time string using boost.date_time. namespace bpt = boost::posix_time; string get_date_time_string(bpt::ptime time) { bpt::time_facet * facet(new bpt::time_facet); facet->format("%Y%m%d%H%M%S"); stringstream return_value; return_value.imbue(std::locale(std::locale:...
According to Stroustrup, a 0 argument passed to the constructor tells the facet that the locale will handle destruction, and the both constructors of bpt::time_facet default to 0 when it isn't supplied. A non-zero value, though, implies that the programmer must explicitly handle the destruction of the facet.
5,330,672
5,330,707
Initializing the first element in a struct
I do a lot of Win32 programming in C++ and many Win32 structures have a 'size' (often called cbSize or length) member as the first element which needs to be set before the relevant API call can be made. For example: WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); GetWindowPlacement(hWnd, &wp); Now, I think i...
Yes, they're automatically initialized to zero. 8.5.1/7: If there are fewer initializers in the list than there are members in the aggregate, then each member not explicitly initialized shall be value-initialized (8.5). [Example: struct S { int a; char* b; int c; }; S ss = { 1, "asdf" }; initializes ss.a wi...
5,330,717
5,330,763
Counting Flops for a code!
This is really taking my time. I could not find a simple way to estimate FLOPS for a following code (the loop), How much FLOPS are for a single iteration of the loop: float func(float * atominfo, float energygridItem, int xindex, int yindex) { ... for (atomid=0; atomid<numatoms*4; atomid+=4) { float dy...
I see (in order of increasing complexity): 8 additions (inc. subtractions) 3 multiplications 1 reciprocal-square-root How these relate to each other depends strongly on the CPU family.
5,330,756
5,331,535
is Qt a conforming C++ implementation?
Does the C++ standard implicitly or explicitly allow such language extensions (or use whatever other term you like) as MOC is? That is, can we technically call Qt (including MOC) a conforming C++ implementation?
MOC is a code generator, not a language extension. All code moc generates you could also write by hand (it would be time-consuming, mind-numbing and error-prone though). Qt uses a few macros such as Q_OBJECT, Q_SIGNALS, Q_SLOTS etc. for the declarations and to give hints to moc. This is perfectly "legal" usage of the p...