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
7,416,445
7,416,473
What is use of c_str function?
I understand is c_str convert a string that may or may not be null-terminated to a null-terminated string. Is this true? Can you give some examples?
c_str returns a const char* that points to a null-terminated string (i.e. a C-style string). It is useful when you want to pass the "contents"¹ of an std::string to a function that expects to work with a C-style string. For example, consider this code: std::string string("Hello world!"); std::size_t pos1 = string.find_...
7,416,539
7,416,580
Is the: "std::string can hold '\0' character" by design?
The fact that std::string can actually hold '\0' characters comes up all the time. This is of course inconsistent with C-style strings. So I'm wondering, is this by design, or is it an omission, or is it just the fact that standard doesn't forbid it and compilers allow this to happen?
I'm wondering what your quarrel is. '\0' is just another character. There is no efficient way to forbid it in a general purpose 'char' string. That the same character has a special meaning in C is unfortunate but has to be dealt with as every restriction that is imposed by legacy code as soon as you interoperate with i...
7,416,574
7,416,637
Algorithm for finding internally connected cluster of nodes within a graph from which no edge points outwards
I am representing my graph as a adjacency list. I want to know how can I find a cluster of nodes which are internally connected but no edge points outwards from them. Is there any well known algorithm out there which I can use? for e.g.This is my graph. 1---->2 2---->1 2---->3 3---->1 3---->4 4---->5 5---->4 Here node...
You could detect strongly connected components using Kosaraju, Tarjan or Cheriyan-Mehldorn/Gabow algorithm. After finding these components, you compress each strongly connected components into one single node (i.e. you represent a whole component by a single node). In the resulting graph, you look for nodes with no ou...
7,416,872
7,416,889
Why boost::thread could be deleted double times?
I noticed something strange. I expect a segfault to be produced running the following code, but it isn't. void DeadlineTimeOut(const boost::system::error_code& pErrorCode, boost::thread* pThread) { std::cout << "Error code: #" << pErrorCode.value() << " Message: " << pErrorCode.message() << std::endl; s...
Deleting a pointer twice is undefined behaviour. There's no guarantee of a segfault. You might get one if you're lucky; you might not. The code might pass all your testing and then blow up in your customer's face at the worst possible moment. See the C++ FAQ. The same goes for dereferencing a pointer that's been delete...
7,416,931
7,417,036
what is Derived Classes with Depth in C++?
I am reading some C++ text at the address https://cs.senecac.on.ca/~chris.szalwinski/archives/btp200.082/content/dclas.html. At the beginning, the author wrote: "A derived class with depth is a derived class that accesses resources through one or more of the derived class' instance variables." I really dont get this de...
I suppose it refers to a chain of derived classes: struct Base { int i; }; struct D0: Base {}; struct D1: D0 {}; int main() { D1 d; d.i; // access i through D0 through Base }
7,416,958
7,420,083
Finding an installed application on Mac/Linux
If you have an application which relies on another app being installed, you ideally want your installer to find that dependency path automatically. On Windows you can use the registry but what about Mac/Linux? In this particular case it's a C++ application, if that makes a difference.
Generally, on UNIX systems you can expect all programs to reside in $PATH instead of being distributed in a hodge-podge collection of stupidly named and partially localized directories. So, essentially you don't need to find any dependency path - you just call the other "app" (program) via execvp, and the libc takes ca...
7,417,189
7,417,247
c++ multiple inheritance casting
I have a class: class Base; Also I have an interface class Interface; Next i'm creating a class class Derived : public Base, public Interface; If I have Base *object = new Derived; How can i cast object to Interface ? (of course if i know than object is actually a derived class) EDIT: I've tried dynamic_cast and sta...
If Base has virtual function (even be it virtual destructor), then: Derived *pDerived = dynamic_cast<Derived *>(object); Else, use Derived *pDerived = static_cast<Derived *>(object); Note that if Base doesn't have virtual function, then dynamic_cast will NOT compile. In dynamic_cast, only the source has to be a poly...
7,417,359
7,417,633
C++ class design question
this is a question about which class does a free on shared pointers. So I have a class hierarchy, base and derivedA and derivedB and derivedC all from base. Base has some virtual functions. I have a class, Holder, it has a collection that holds instances of derivedA, derivedB and derivedC. So an instance of Holder is ...
The simpler way ? Change your vector to become aware of ownership. boost::ptr_vector<Base> is such a vector, especially suited for polymorphic data: deep-copy through clone methods (just implement virtual Base* clone() const;) automatic memory management sugar coating on dereferencing iterator (yields a Base& instead...
7,417,374
7,418,273
C++ array output problem in VS2008 with OpenCV
I'm making a texture classifier in OpenCV and VS2008 and I want to insert 3 double variables into a double array so I can calculate nearest neighbours of the arrays. I tried : double a[5]={x,y,z}; and the output is 0012FF04 the same output happens when I just declare an array with a couple of numbers in it like doubl...
C++ doesn't define an operator<<(double*) that displays the contents of an array; C++ arrays aren't self-describing and I don't believe defining such an operator in a generally-useful way would be possible. You have to write an explicit loop: for (int i=0; i<3; ++i) std::cout << brick_v[i] << " "; std::cout << std...
7,417,556
7,431,769
Array as array[n] and as pointer array*
What is the difference when array is declared as array[n] or as pointer array* according to example below? I guess that for example both 'a' and 'c' point at the first element of array, but they behave different. #include <iostream> int main() { int a[3] = {1}; int b[5]; std::cout << *a << std::endl; //pr...
Long story short - they are essentially the same, but ever so slightly different. From what I've gathered from http://c-faq.com/aryptr/aryptr2.html , whilst they can both act as a pointer to the front of an array, when you declare an array as int a[3]; you are essentially binding the size of '3' to your variable a, a...
7,417,670
7,418,011
Creating a Win32 application for both XP and Vista/Windows 7
I've written an application in C++ using the pure win32 api (no MFC or WPF). I want the same .exe to run under both Window's XP and Windows Vista / Windows 7. I was using a manifest to add Visual Styles to the controls in my application. However, when I tested the app on an XP Machine, Buttons do not show up. Only Edit...
Make sure you call InitCommonControlsEx
7,417,724
7,417,782
Why is this conversion happening?
#include<iostream> using namespace std; class test { int a, b; public: test() { a=4; b=5; } test(int i,int j=0) { a=i; b=j; } test operator +(test c) { test temp; temp.a=a+c.a; temp.b=b+c.b; return temp; } void print() { cout << a << b; } }; int main() { test t...
The compiler sees you are invoking operator+(test) and attempts to implicitly convert the 2 to a test successfully using your test(int i,int j=0) constructor. If you want to make the conversion explicit, you must change the constructor to explicit test(int i, int j=0). In this case, your code would generate a compiler ...
7,417,736
7,418,043
Double dispatching fails for an InputMap in C++ - codes reduced to simplicity
Hello in one of my current projects I want to implement an InputMap. So I have an abstract input //Input.h namespace INPUT { class InputMap; class Input { public: Input(); virtual ~Input(); virtual void Dispatch( InputMap * pMap ) = 0; }; } and an InputMap //InputMap.h namespace INPUT { class InputMap { pu...
You should read about the Visitor pattern. Basically, the issue is that virtual function are statically bound (ironic), so the solution is to declare all HandleInput (for every single type of Input) in InputMap. class InputMap { public: InputMap(); virtual void HandleInput(StringInput&) = 0; virtual void Ha...
7,418,093
7,418,151
Use one socket in two threads
Possible Duplicate: Are parallel calls to send/recv on the same socket valid? I'm going to use one thread to receive data from socket(read) and another one to send data throughout socket(write). Is it good idea to use one socket in two different threads?
There should be no problems sharing a socket across threads. If there is any kind of coordination required between the reading and the writing, and there probably will be, you're going to need to synchronize that in some way. This article, File Descriptors And Multithreaded Programs, may be helpful and addresses the co...
7,418,199
7,418,249
Why func("abc" "def"); compiles
just stumbled onto a miss in my code, a function was called like this func("text1" "text2"); instead of func("text1", "text2"); The thing is that it actually compiles and runs (MSVC 2008), the two strings are treated as one (ie a call to an overloaded func gets the input "text1text2"). Is this normal standard behavi...
Yes, this is called string literal concatenation, and is a feature of the C and C++ compiler.
7,418,246
7,418,633
Converting to different data types based on different template arguments
I have two systems that I need to map types between - the source data fields, which can be numerical, chars, or strings, is all stored as string objects; the destination system needs a different data type for the underlying type of each data field, and I need to dynamically do this mapping. So basically, for each data ...
if you can discern the ID statically, template pecialization is probably better that a network of if-s. template<int id> struct multireturn; // not defined template<> struct multireturn<1> { typedef std::string return_type; return_type operator()() { return "string"; } }; template<> struct multireturn<2> { t...
7,418,483
7,418,732
How C++ reference works
After working 15 years in C++ I found that I don't understand references completely. class TestClass { public: TestClass() : m_nData(0) { } TestClass(int n) : m_nData(n) { } ~TestClass() { cout &lt;&lt; "destructor" &lt;&lt; endl; } void Dump() { cout &lt;&...
Your code suffers from multiple problems and ultimately won't make sense. However, let's hack through it. 1) You can only bind a temporary to a const reference, thus extending its lifetime: const TestClass & c = TestClass(); 2) Now we can't use dump, because you didn't declare it const: void Dump() const 3) Saying c ...
7,418,518
7,418,760
Is there a way to tell openmp that shared data is constant?
I am guessing that even reading from shared data in openmp causes some parallel overheads, as depending on processor architecture (if different cores have their own cache...) it may be necessary to refresh the cache to ensure that no other cpu has modified the data before reading. Am I right in thinking this? If so, is...
Sharing read-only data among multiple cores has no overhead. The same copy of the data will be in the cache for all the cores that are using it. The only time you will incur overhead is when one of the cores writes to the shared data. In that situation, you will incur a (potentially large) overhead because the write wi...
7,418,553
7,418,808
private template functions
I have a class: C.h class C { private: template<int i> void Func(); // a lot of other functions }; C.cpp // a lot of other functions template<int i> void C::Func() { // the implementation } // a lot of other functions I know, that it's not the best idea to move template implementation in cpp file (because i...
When a function template is used in a way that triggers its instantiation, a compiler(at some point) needs to see that template's definition. And that is the reason, templates are usually implemented inside a header file using inline finctions. So as long as the above rules gets followed it is still okay to have interf...
7,418,567
7,418,997
How does scoped_lock avoid emitting an "unused variable" warning?
boost::mutex::scoped_lock is a handy RAII wrapper around locking a mutex. I use a similar technique for something else: a RAII wrapper around asking a data interface to detach from/re-attach to a serial device. What I can't figure out, though, is why in the code below only my object mst — whose instantiation and destru...
Note that the question has changed since the other answers were written. Likely the reason g++ doesn't warn in the current form is because mst is a reference, and constructing and destructing a reference has no side effects. It's true that here the reference is extending the lifetime of a temporary, which has effects i...
7,418,822
7,418,919
Modify the top of stack without access to StackType object
I had a certain query regarding a question I was asked earlier. I was given this function prototype void StackPop(NodeType *Top) and was told modify the top of the stack without access to the stack object. StackPop function here is a global function and not a member function of the Stack class. After popping, Top shoul...
Yes, this is a valid simple answer to the question, with three caveats: temp = top should read temp = *top; you might want to gracefully handle the case where *top is NULL (rather than just dereferencing the NULL pointer); this solution is of course incompatible with the prototype you were given [void StackPop(Node *T...
7,419,078
7,419,103
Possible memory leak?
I have the following code: void customHandleException (_EXCEPTION_POINTERS* ExceptionInfo) { char* x = (char*)ExceptionInfo->ExceptionRecord->ExceptionInformation[0]; delete[] x; } void foo() { char* x = new char[ 256 ]; ULONG_PTR* args = new ULONG_PTR[1]; args[0] = (long)x; RaiseException(EX...
You should be using delete[]. Memory allocated with new[] MUST be deallocated with delete[]. Reference: C++03 Standard: § 3.7.4.2-3 If a deallocation function terminates by throwing an exception, the behavior is undefined. The value of the first argument supplied to a deallocation function may be a null pointer valu...
7,419,113
7,419,181
What is floating point speculation and how does it differ from the compiler's floating point model
The Intel C++ compiler provides two options for controlling floating point: -fp-speculation (fast/safe/strict/off) -fp-model (precise/fast/strict and source/double/extended) I think I understand what fp-model does. But what is fp-speculation and how does it relate to fp-model? I have yet to find any intel doc which e...
-fp-model influences how floating-point computations are carried out, and can change the numeric result (by licensing unsafe optimizations or by changing the precision at which intermediate results are evaluated). -fp-speculation does not change the numerical results, but can effect what floating-point flags are raised...
7,419,211
7,419,672
my first Qt application, c++ (little opencv)
I am to make a little demo app to learn some Qt and c++ and if anyone know some guides that might be good for this project i am happy to hear about it. What i wanna do: I want to make an app where i can open a folder location of training data(images). Then i want to show the images one by one and mark ROI (rects, cirle...
Qt has lots of very good official tutorials
7,419,315
7,421,237
How to view the value of a unicode CString in VC6?
I'm using Visual Studio 6 to debug a C++ application. The application is compiled for unicode string support. The CString type is used for manipulating strings. When I am using the debugger, the watch window will display the first character of the string, but will not display the full string. I tried using XDebug, ...
Go to tools->options->Debug, and check the "Display unicode string" check-box. That would probably fix the problem. Two other options: In the watch window, if you have a Unicode string variable named szText, add it to the watch as szText,su. This will tell VS to interpret it as a Unicode string (See Symbols for Watch ...
7,419,472
7,421,378
QtCreator: How do I register "override" and "final" as a keyword?
C++11 (or C++0x) introduces the override and final keywords to C++. Great stuff, and we're gonna use them to make our code better. BUT, while the MS Visual-C++ 2010 compiler handles the keywords perfectly, QtCreator (my IDE of choice) is totally confused by them. override methods are marked as errors, and --- much wors...
I guess you'll need to wait until they release it to support C++11. Recompiling it would not be a good option as you will need to take care of everything (lexical, symbol table) by changing the grammar of the language by introducing two new keywords.
7,419,544
7,419,766
Writing a DLL that loads msvcr80.dll and exposes the free()-function
I have a third-party DLL that depends on MSVCR80 and allocates resources that I need to cleanup. The library does not expose a free-function for doing this. Instead, I need to load the same runtime library and manually call the free function. As a workaround I'm trying to write a "wrapper" DLL that loads the correct r...
Probably there are better solutions, but in case everything else failed you could find somewhere a copy of VC++ 2005 Express Edition (=free, no piracy is needed ;) ), which uses the version 8.0 of the compiler, and thus the same runtime of the defective dll. Then you would build your wrapper dll with it, which would ...
7,419,572
7,419,645
Size of an integer literal in VC++ and GCC targeting 64-bit machines
I'm writing cross-platform x86/x86-64/Itanium code oriented towards high performance and would like to avoid any unnecessary operations, including unneeded type casting. The code I have calls a function like this: int theResult = Function(anUInt, 10); Obviously, the type of 10 value is not specified. And Function is d...
There is no such thing as an "untyped integer" in C++. Although you may not specify the type explicity, it does have a type, and that type can be counted upon. The Standard speaks to this: 2.13.1 Integer Literals 2 The type of an integer literal depends on its form, value, and suffix. If it is decimal and has no s...
7,419,593
7,421,462
Zoom image inside preview
I am writing a GUI application that works on Mac and Win and there is one little problem, which i do not know how to solve. In my application I have a small (250 x 250 px) preview window (let' call it SW) in which placed the image. Image can be much bigger, than SW. Somewhere I have a slider which implements zoom func...
Take a look at the Image Viewer Example, it has some features that you are looking for.
7,419,622
7,436,170
OpenMP overhead calculation
Given n threads, is there a way that I can calculate the amount of overhead (e.g. # of cycles) that is required to implement a specific directive in OpenMP. For example, given the code below #pragma omp parallel { #pragma omp for for( int i=0 ; i < m ; i++ ) a[i] = b[i] + c[i]; } Can I calculate some...
Yes, you can. Please take a look at EPCC benchmark. Although this code is a bit older, it measures the various overhead of OpenMP's constructs, including omp parallel for and omp critical. Basic approach is somewhat very simple and straightforward. You measure a baseline serial time without any OpenMP, and just includ...
7,419,650
7,419,745
Where to place Structs and Enums in C++ class + final constants
I have started reading C++ and I have a question about classes and member variables of type Enum and Struct. Where should I declare Enums/Structs so that I can use them as member variables when I separate header and implementation file? And also, how can I make a final member variable in a C++ class? I am just getting ...
The header file is like a person saying 'I can do this, that and the other' - so put declarations into it - enums, structs, class declarations, constants, ... The implementation file is like a person saying 'I can do this and this is how I can do it' - it produces a recipe - Actual machine code for the CPU to crunch. c...
7,419,702
7,419,920
Assigning to a pointer returned by a function call
I'm trying to implement a simple LinkedList The following code, producing this error: error: lvalue required as left operand of assignment The line is: newNode->getNext() = _head; Where getNext() returns a Node*, and i'm trying to make the new Node point at the current head before updating it. I'm probably thinking i...
Either, dereference: Node* Node::getNext(); *(newNode->getNext()) = _head; (assuming _head has type Node and the assignment operator was implemented with care in Node) or, what is probably better Node& Node::getNext(); newNode->getNext() = _head; But anyway, this is not the way you should be doing this. You may want ...
7,419,883
7,419,916
String literals manipulation - copying characters
I am trying to implement a simple string copy in the following code. However, I got a run-time error in the line "*d = *c;". Could anyone tell me what is wrong with that? void test3() { char *a="123456"; char *b="000000"; char *c=a; char *d=b; while(*c){ *d = *c; cout << *c << en...
Basically, string litterals are constant and can't be changed. In the following line: char *a="123456"; char *a should be replaced with const char * a because a points to a block of constant memory. Further down the function, you attempt to change that block of constant memory and this yields a run-time error. To ge...
7,420,314
7,420,351
C++ ISO Standard interpretation of dereferencing pointer to base
I would like to know standard's view on dereferencing pointer to base, but I'm not making any progress finding it. Take these two classes for example: class Base { public: virtual void do_something() = 0; }; class Derived : public Base { public: virtual void do_something(); }; void foo2(Base *b) { Ba...
Base &b = *static_cast<Base *>(d); // does this work by standard? Yes. But you can simply do this: Base &b = *d; //use b polymorphically! b.do_something(); //calls Derived::do_something() No need to use static_cast. After all, Derived is derived from Base. Reply to your edit: foo2(d); // does this work by standard...
7,420,317
7,420,383
sizeof() of a structure containing an unordered_map as a member
I have a structure of the following type struct Node { int word; int count; unordered_map<Type, Node*> map; }node; Is it safe to assume that sizeof(node) gives you the correct size of that node in C++? I am sure there will be padding in the structure but sti...
yes, since sizeof is usually calculated at compile time. That means that even if the hash size is 1000 or 100 or 10 or 1 or 0 you will get the same sizeof result. don't assume it will be enlarged even if the hash table will be modified. however remember that sizeof in c++ can have awkward results sometimes (padding, pl...
7,420,373
7,420,569
AccessViolation error while using _tcstok in C++
I am trying to run the following code TCHAR* str1 = TEXT("C:\\Program Files\\Internet Explorer;"); const TCHAR* del = TEXT(";"); TCHAR* token = _tcstok(str1, del); When I run this in VS 2010 I get the following Exception : Unhandled exception at 0x10275af4 (msvcr100d.dll) in String_Tchars.exe: 0xC00000...
You can only use strtok() (and its Windows relatives) with modifiable strings. So make your strings local character arrays: TCHAR str1[] = TEXT("C:\\Program Files\\Internet Explorer;"); TCHAR* token = _tcstok(str1, ";"); // etc. The the tokenizer function actually modifies the string by replacing the delimiter by null...
7,420,547
7,420,557
comma operators in c++
int main() { int x = 6; x = x+2, ++x, x-4, ++x, x+5; std::cout << x; } // Output: 10 int main() { int x = 6; x = (x+2, ++x, x-4, ++x, x+5); std::cout << x; } // Output: 13 Please explain.
Because , has lower precedence than =. In fact, , has the lowest precedence of all operators. First case: x=x+2,++x,x-4,++x,x+5; This is equivalent to (x=x+2),(++x),(x-4),(++x),(x+5); So, x becomes 6+2 = 8, then it is incremented and becomes 9. The next expression is a no-op, that is x-4 value is calculated and disc...
7,420,570
7,420,630
error opening binary file for writing: terminate called after throwing an instance of 'std::ios_base::failure'
I am getting the following output from the following block of code: //create file for writing cout << "'" << filename.c_str() << "'" << endl; string outfile = filename.append(".bin"); cout << "'" << outfile.c_str() << "'" << endl; fstream *binfile; binfile->open (outfile.c_str(), ios::out | ios::binary)...
Instead of this: fstream *binfile; You should do this: fstream binfile("filename", fstream::in | fstream::out | fstream::binary); and then call: binfile << "write here to file"; binfile.close(); There is no need for a pointer here.
7,420,621
7,421,286
What's the fastest way to draw a new fullscreen image each frame in OpenGL?
Every frame, my program will receive a new image from a USB video camera. This image will initially be in CPU memory. What's the fastest method in OpenGL to draw this image to the screen so that it fills the entire screen? Currently, I'm uploading the image data to a texture and then rendering a fullscreen quad. Howeve...
Currently, I'm uploading the image data to a texture and then rendering a fullscreen quad. However, this doesn't run very quickly on a different machine that tried. Any ideas? Thanks. glTexImage2D does a full texture initialization (which means, allocation, object setup and the like). If you just want to replace the ...
7,420,780
7,432,351
What is a constant reference? (not a reference to a constant)
Why do constant references not behave the same way as constant pointers, so that I can actually change the object they are pointing to? They really seem like another plain variable declaration. Why would I ever use them? This is a short example that I run which compiles and runs with no errors: int main (){ int i=0...
The clearest answer. Does “X& const x” make any sense? No, it is nonsense To find out what the above declaration means, read it right-to-left: “x is a const reference to a X”. But that is redundant — references are always const, in the sense that you can never reseat a reference to make it refer to a different object....
7,420,835
7,421,391
Casting between shared_ptr of forward declared class hierarchy
I have a class manipulating only shared_ptr to an inheritance hierarchy (quite simple, there are a few classes, say A, B, C etc. inheriting from a single class Base). Since I do not need to manipulate the instances of A, B, C... themselves, they are only forward declared. However, the compiler chokes when I try to pass...
Is there any other way than either static_pointer_castor #includethe header of class A? No. In fact, the #include is the only way to do it properly (static_pointer_cast either wouldn't work or invokes undefined behavior). You can't cast ordinary pointers between incomplete subclass and superclass, either.
7,420,842
7,420,929
Visual C++ debugger visualizer?
How does Visual Studio show the elements of a vector, or the characters of a string, in C++? Is there a way for me to make it show my own classes in a custom way?
http://msdn.microsoft.com/en-us/library/zf0e8s14(v=VS.100).aspx For native code, you can add custom data type expansions to the file autoexp.dat, which is located in the Program Files\Microsoft Visual Studio 10.0\Common7\Packages\Debugger directory. Instructions on how to write autoexp rules are located in the f...
7,420,889
7,421,007
how to output a pointer via MessageBox?
i have this code: extern "C" __declspec(dllexport) void getName(void) { char buf[20]; int slotNumber = 1; DWORD tempdw; DWORD hStorm_LOBBYPTR; hStorm_LOBBYPTR = (DWORD)GetModuleHandleW(L"Storm.dll") + 0x1000 + 0x40000 + 0x8000; __asm { PUSHAD MOV EAX, DWORD PTR DS:[hStorm_...
My guess is that your assembly stomps over something (possibly a register) which means that the sprintf fails and the buffer just contains random stack noise. Check this out by removing the assembly.
7,421,116
7,421,222
Regarding Service Locator Pattern
Service Locator seems like a pretty useful concept and I'd like to implement it in my app. However, I have a few questions about how it should be implemented and how it should be used in conjunction with other programming paradigms. Should the SL manage the service it is storing? That is, when the SL gets destroyed, s...
You would think I wrote this article (I didn't), considering how often I refer to it: Service Locator is an Anti-Pattern Dependency Injection makes your dependencies explicit. Service Location buries them in the implementation, and creates a hard dependency on your locator.
7,421,130
7,421,162
How to deallocate a int*** in c++
How do I deallocate this type of 3D array in c++? I have a class that has a int*** volume as a member and I filled it this way.. volume = new int**[xSize]; for(int i =0; i<xSize; i++) { volume[i] = new int*[ySize]; for(int j =0; j<ySize; j++) { volume[i][j] = new int[zSiz...
You just reverse your actions (other than the filling of the array) for(int i =0; i<xSize; i++) { for(int j =0; j<ySize; j++) { delete[] volume[i][j]; } delete[] volume[i]; } delete[] volume;
7,421,170
7,424,395
constexpr undefined behaviour
I've been experimenting with constexpr. On my test compiler (g++ 4.6) this fails to compile with an error about out of bounds access. Is a compiler required to spot this at compile time? #include <iostream> constexpr const char *str = "hi"; constexpr int fail() { return str[1000]; // Way past the end! } template <...
§5.19/2 (on the second page; it really should be split into many paragraphs) forbids constant expressions containing — an lvalue-to-rvalue conversion (4.1) unless it is applied to — a glvalue of integral or enumeration type that refers to a non-volatile const object with a preceding initialization, initialized with ...
7,421,330
7,425,441
Boost::asio: data get received only after other connection appeared
I'm trying to use code examples in my application. At a connection client sends "hello!" to the server. Server receives it and answers on it somehow (and ends message with "Hi, client! I'm server!") - but that's what i have: server doesn't receive anything until I connect to it by telnet and send something. After that ...
size_t len = socket.read_some(boost::asio::buffer(buf), error); if (buf[len-1] == '/n') you've made some assumptions about tcp::ip::socket::read_some() that are not true. Remarks The read_some operation may not read all of the requested number of bytes. Consider using the read function if you need to ensure that t...
7,421,497
7,421,571
QVector size() returning size zero
These 2 functions are my attempt to serialize a QVector. Unfortunally I can't use QDataStream because my boss requires that the implementation is Qt independent and QDataStream prepends a header. So the problem is the vector returned by the function binToVector returns a size equals to 0, but if the elements are printe...
You're calling QVector::reserve, which allocates memory for the class to use as storage, but doesn't actually change the number of real elements in the container. For that, you need QVector::resize. The standard C++ vector class works the same way. Reserving space in advance ensures that repeated future calls to append...
7,421,587
7,421,912
What is the register cache and what does it have to do with const variables?
From http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.14: Even if the language outlawed const_cast, the only way to avoid flushing the register cache across a const member function call would be to solve the aliasing problem (i.e., to prove that there are no non-const pointers that point to the obje...
I think it is talking about something like this: class A; class B { public: A * m_a; B(A * a) : m_a(a) {} }; Class A { public: int m_num; A(int num=0) : m_num(num) {} void DoSomethingConst(B * someB) const; }; void SomeOtherFunction() { A myA; B myB(&myA); //do something with myA.m_num...
7,421,601
7,421,763
How do I write REG_MULTI_SZ values to the Registry?
I'm trying to write a REG_MULTI_SZ value to the Windows Registry using C++. Where I'm stuck is on converting the c-strings that I have to MULTI_SZ format. Is there a convenient way to do this?
You'll have to do it yourself. Given char ** strings; // array of strings int N; // number of strings you count the length of the multi_sz int len=1; for(int i=0; i<N; i++) len += strlen(strings[i])+1; and fill it char* multi_sz = malloc(len), ptr=multi_sz; memset(multi_sz, 0, len); for(int i=0; i<N; i++) { strcp...
7,421,624
7,421,653
Trouble returning a struct from a function
I want to have a function return a struct. So, in my header file, I defined the struct and the function signature. In my code file, I then have the actual function. I get errors about "unknown type name". Everything appears to be following a very standard format for this. Any ideas why this isn't working? TestCla...
foo isn't in the global namespace, so trashme() can't find it. What you want is this: TestClass::foo TestClass::trashme(int x){ //foo and trashme are inside of TestClass TestClass::foo temp; //foo is inside of TestClass temp.a = x*2; //note: temp, not foo temp.b = x*3; //note: temp, not foo return(te...
7,421,761
7,421,794
Stack implementation to judge expressions
I wrote the following code to judge whether an expression entered by user has correct sequence of brackets or not, e.g. if user enters [a*(b+c)] its ok. But if he enters [a*(b+c)[ its not correct. Stacklist.cpp is a file which contains the linked list implementation of stacks and definitions of functions of push and p...
system is found in the header cstdio, but you did not #include that header. Anyway, it's best not to use "tricks" like system("pause") to keep the console window after your program ends: if your console environment is not hanging around after your program has finished doing its meaningful work, then that's your consol...
7,421,825
7,422,058
C++11 features in Visual Studio 2012
A preview version of Visual Studio 2012 (the next version after VS2010) is now available. Does anyone know what new C++11 features it supports? (I'm not in a position to try it out at the moment).
It's worth noting that Visual Studio 2010 already had quite a bit of early C++11 support. So to summarize what is already linked to in other answers, here is what is new in Visual Studio 11 that was not part of Visual Studio 2010: rvalue references to version 2.1 from 2.0 lambdas to version 1.1 from 1.0. decltype to v...
7,421,886
7,421,967
Passing Void into a class as a pointer then executing its contents
How can I pass a function as an argument and then execute it. I'm trying to do something like this: class Foo{ private: void (*external); public: Foo(void (*function)()){ *external = *function; } ~Foo(){ } bool Execute(){ *external(); // Somehow execute 'external' which does the same thing with...
You were close. class Foo { public: typedef void(*FN)(void); Foo(FN fn) : fn_(fn) {}; bool Execute() { fn_(); return true; } FN fn_; }; void pFunc(){ printf("test"); } int main() { Foo foo(&pFunc); foo.Execute(); }
7,422,054
7,422,237
What is the "proper" way to allocate variable-sized buffers in C++?
This is very similar to this question, but the answers don't really answer this, so I thought I'd ask again: Sometimes I interact with functions that return variable-length structures; for example, FSCTL_GET_RETRIEVAL_POINTERS in Windows returns a variably-sized RETRIEVAL_POINTERS_BUFFER structure. Using malloc/free is...
If you like malloc()/free(), you can use RETRIEVAL_POINTERS_BUFFER* ptr=new char [...appropriate size...]; ... do stuff ... delete[] ptr; Quotation from the standard regarding alignment (expr.new/10): For arrays of char and unsigned char, the difference between the result of the new-expression and the address re...
7,422,081
7,422,653
Does clang++ do threadsafe initialisation of local static variables?
Does clang++ do threadsafe initialisation of local static variables? GCC does, unless you turn it off with the misleadingly named -fno-threadsafe-statics. I'm using Apple clang version 2.0 (tags/Apple/clang-139) (based on LLVM 2.9svn).
Yes, same as with GCC (so can also be turned off with -fno-threadsafe-statics)
7,422,123
7,422,168
What does this C++ declaration mean?
I am creating a class diagram for a class that has many definitions similar to this one inside of its header file. 1 2 3 4 5 const std::pair<Controller<_Tp,_Val>*, _Val>& getHighestBidder(_Tp obj) const; I know what several of them do, 2) says that this...
Firstly, note that it's not returning a std::pair<Controller<_Tp, _Val>*, _Val>, it's returning a std::pair<Controller<_Tp, _Val>*, _Val> &, i.e. a reference to such an object that already exists. (1) denotes that it's a const reference to an object; you cannot modify the object through this reference. (5) denotes that...
7,422,200
7,422,239
What's the opposite of `fixed` in cout?
When using cout, what is the default formatter defined in the <iomanip> header? In other words, once I've set my formatter to fixed using cout << fixed << setPrecision(2), how do I change it back? Or, what am I changing it back to?
The opposite of std::fixed is std::scientific. (You find a nice list of manipulators in this great answer.)
7,422,426
7,422,539
How to show Window and command-line prompt?
Is there a way to show a Window and CMD in combination? I would like to use the cmd as a debugging info logger in my Window application.
There are two approaches. You can continue to link your application as a windowed application, and use AllocConsole to create a console window in which you can output your debugging information. Note that this only opens kernel handles, so you would need to use _open_osfhandle and _fdopen to connect stdout/stderr to y...
7,422,641
7,422,664
C++, using this to call a constructor from itself
I was writing some java last night and I had two constructors that looked basically alike, except my default constructor provided some values to my object, it was something like this: testObject(){ width=5; height=12; depth=7; //other stuff is the same as the next one } testObject(int x, int y, int...
In C++0x, you can do this: TestObject() :TestObject{5, 12, 7} {} See Delegating Constructors for more details. (Curly braces not look familiar to you? They're for preventing narrowing.) If you don't have C++0x available yet, then in your case, you can use default arguments as mentioned in other answers here.
7,422,659
7,422,881
How to detect non-virtual-override at compile or runtime
I want to detect if a function was (statically) overridden in a derived class: template< typename T > struct A{ void func(){ static_cast<T*>(this)->func(); } }; struct B: A<B>{}; struct C: A<C>{ void func(){ std::cout << "class C" << std::endl; }; C c; if(&A<C>::func != &C::func) c.func(); Obviously, I won't call...
Works here. BTW the easiest approach would be to define f() in A as empty: struct A{ void func(){ } };
7,422,751
7,423,025
String Reference from String Literal C++
I'm hoping someone can help answer a question about strings in C++. I've tried to strip out any extraneous code from here, so it wont compile (missing namespace, defines, etc...). This is not a "bug" problem. If working code samples are needed, please specify what code you would like (for which question), I'd be hap...
A) I don't know anything about OllyDbg, but in all cases std::ostream makes it's own copy of text before foo returns, so any changing of the variables after the call will not affect the output. B) Yes, the string constructor will always make it's own copy of a char* during the implicit construction for the parameter. C...
7,422,877
7,424,806
How to show tooltip when mouse pointer moves on an item drawn in QAbstractItemView subclass?
I've implemented QAbstractItemView to show a tabular model (having two columns, one for x axis another for corresponding y axis) in line chart style. To do that I reimplemented QAbstractItemView::paintEvent(). The chart is now shown and each data is drawn by a little circle. When mouse pointer hovers over the circles (...
If you haven't already done it, you should redefine the QAbstractItemView::indexAt function, which returns the QModelIndex at a given position in the view. And in your model, you should set the tooltip text for your indexes as the role Qt::ToolTipRole or make your custom model QAbstractItemModel::data() function return...
7,423,008
7,423,387
virtual inheritance with abstract class constructors
I got the following problem: There is an abstract base class, and two other abstract classes which virtually inherit from the base class, and as a conclusion have to call the Constructor of it, with all the needed arguments. But now, I got a "normal" class which does inherit both second order classes, and therefor has ...
FINALLY found it. § 12.6.2 / 7 [class.base.init] The expression-list or braced-init-list in a mem-initializer is used to initialize the designated subobject (or, in the case of a delegating constructor, the complete class object) according to the initialization rules of 8.5 for direct-initialization. The init...
7,423,175
7,423,283
What's a good way to perform cross-platform inter-thread notifications in C++?
Scenario: - My main (UI) thread (Thread "M") runs, and spins up a worker thread ("W") to control with some hardware. - "W" wants to send progress notifications to "M" every so often. - The notification-invocation can't block "W"... "W" needs to make the call and return immediately; "M" will process the notification asy...
If you are using Boost.Thread then you can use a condition variable.
7,423,213
7,423,288
operator overloading and the usage of const_cast
For the following code snippet, class A{ const int a; public: A(): a(0){} A(int m_a):a(m_a){}; A& operator =(const A &other); }; A & A::operator =(const A &other) { const_cast<int&>(a) = other.a; return *this; } what do the lines of A & A::operator =(const A &other) const_cast<int&>(a) = other.a; mea...
The const_cast removes the const from the const member a, thus allowing the assignment from other.a to succeed (without the const_cast the type of a would be const int, and thus it wouldn't be modifiable). Probably the idea is that a is initialized at class construction and can't be modified "by design" in any other pl...
7,423,376
7,433,127
How can I write a signature on C# for a wrapped C++ method having double indirection on its arguments?
I'm writing a wrapper for a dll. The dll has a method whose signature resembles the following: unsigned long aMethod(char **firstParameter, char **secondParameter)) aMethod returns string pointers to all parameters. I've searching at google for a tutorial to give me insight on how to write the signature on C# so the f...
I got the answer: The signature has to be like this: [DllImport(aDll.dll, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)] static unsafe extern ulong aMethod(ref IntPtr firstParameter, ref IntPtr secondParameter); Parameters should be declared as here: IntPtr firstParameter = new IntPtr(...
7,423,424
7,423,496
Expression must have pointer to object type
I'm writing a matrix program and am currently trying to multiply a point and a matrix. I keep getting an error over my objects(result and P) "Expression must have pointer to object type" in this function: //Point Class functions Point Matrix44::operator*(const Point & P){ Point result; for (int i = 0; i < 4; i+...
In your Point class, you have the element member defined as: double element[4]; This is a one-dimensional array. However, in your function, you're trying to access it as if it were a two-dimensional array: result.element[i][k] P.element[j][k] I think you need to rethink exactly how your matrix multiplication is suppo...
7,423,691
7,423,761
Is gets() officially deprecated?
Based on the most recent draft of C++11, C++ refers to ISO/IEC 9899:1999/Cor.3:2007(E) for the definitions of the C library functions (per §1.2[intro.refs]/1). Based on the most recent draft of C99 TC3, The gets function is obsolescent, and is deprecated. (per §7.26.9/2) Can I safely say that gets() is deprecated in bo...
Does it matter? The only way you can ever use gets is if stdin is known to be attached to a file whose contents you have full control over. This condition is almost impossible to satisfy, especially on multiprocess systems where other processes may modify files asynchronously with respect to your program. Therefore, fo...
7,423,718
7,423,774
Creating a File System "Driver"
I'm looking to create a "driver" I guess for a custom file system on physical disk for Windows. I don't exactly know the best way to explain it, but the device already has proper drivers and everything like that for Windows to communicate with it, but what I want to happen is for the user to be able to plug the device...
The closest thing I know of to what I understand from your description is an installable file system, like the Ext2 installable file system that allows Windows computers to work with Linux originating ext2 (and to a certain degree ext3) filesystems. Maybe that can serve as a starting point for your investigations. As ...
7,423,880
7,423,919
ostream& operator<< segfaults without flush()
I have a custom class for which I've defined a custom cast operator char(), call it A. Now, say I want an array of this class but with added functionality so I define a new class B to achieve this with a member variable array of type std::vector<A>. One of the things I want B to handle is printing its data to screen so...
You have to return something there. Certainly the stream you've been provided, so you should: return out; as the last line of the operator. Note that, maybe by chance, calling out.flush() made some register (say EAX) to hold the value of the stream, thus being returned (as per standard calling convention), and this is...
7,423,900
7,424,269
Is there a c++ function (built-in or otherwise) that gives the integer division and modular division results without repeating the operation?
You could write something like: int i = 3; int k = 2; int division = i / k; int remainder = i % k; It seems as thought this would, on a low level, ask an ALU to perform two vision operations: one returning the quotient, and one returning the remainder. However, I believe an ALU would most likely calculate both in a s...
Actually, the code you wrote won't generate any division instructions since the compiler can figure out the results at compile time. I wrote a little test program and set the compiler (VC++ 10SP1) to generate an assembly code listing. #include <iostream> using namespace std; struct result { long quotient, remaind...
7,423,924
7,429,110
Trying to understand a mem leak
I'm working with VLD (Visual Leak Detector), and it detects some mem leaks. I'm trying to understand why this is a mem leak for VLD. It could be a false positive? The code is very simple: CGlobalLog* CGlobalLog::m_instance=NULL; //static instance CGlobalLog::CGlobalLog() { minimiumLogLevel = LOGLEV...
First of all... How do you imagine to destructor get called? Do you call anywhere something that will destroy your object? Secondly calling delete pointer in destructor will cause call of another destructor of same object. So you have recursive destructor call in here. As it is singleton class your call can be simply r...
7,424,088
7,424,138
Why does typedef affect function overloads?
I have two functions in a class (please comment on the issue and not the coding style): template <typename T> class myStringClass { public: ... typedef T* iterator; void erase(size_t pos, size_t n); // FUNC#1 void erase(iterator first, iterator last); //FUNC#2 }; FUNC#2 is erasing the range while FUNC#1 simp...
The following code compiles fine: #include <stdlib.h> template <typename T> class myStringClass { private: T *m_begin; public: typedef T* iterator; void erase(size_t pos, size_t n); // FUNC#1 void erase(iterator first, iterator last); //FUNC#2 }; template <typename T> void myStringClass<T>::erase(size_t p...
7,424,127
7,426,134
How can the handle of a QScrollBar be styled and made scalable?
I have a styled QScrollBar on my table which uses an image for the handle of the scroll bar. The handle is rounded at the edges (with transparency in the image around the edges, of course). Now the problem is that i can't seem to make it re-size nicely. It's a vertical scroll-bar, so the only way I found to work so far...
Well, as you say, you could inherit from the scrollbar and overload the paintEvent function. Therein you can pretty much to whatever you want, for example compute your new pixmap by repeating that one line and painting it. There are actually a couple of functions in QPixmap that should make this relatively easy.
7,424,175
7,425,921
Alternatives to Boost::Function and Boost::Bind
Does anyone know of any libraries that can be used in place of Boost::Function and Boost::Bind? We are trying to remove our dependency on Boost since it's a pretty large library. We're looking for something more focused. I found this: http://www.codeproject.com/KB/cpp/fastdelegate2.aspx I've never used it though and it...
The implementation that you pointed to is built upon undefined behavior according to the standards. Disabling exceptions should be no problem with Boost.Function, as long as you define your own throw_exception function. And I'm sure disabling RTTI won't be a problem either, since Boost.Function goes through great troub...
7,424,195
7,424,468
How to only set a member if it exists?
Edit: Sorry, this question is a duplicate. Original: SFINAE to check for inherited member functions I have a templated function (in a class used for testing): template <class CHandler> void InitHandler(CHandler &handler) { handler.setId(0); handler.SetCache(m_pCache.get()); handler.m_pScience = m_pScience; ...
Reimagining this answer: How to detect whether there is a specific member variable in class?: template<typename T> struct Hasm_pScience { struct Fallback { int m_pScience; }; // introduce member name "m_pScience" struct Derived : T, Fallback { }; template<typename C, C> struct ChT; template<typenam...
7,424,232
7,424,300
How am I supposed to initialize this?
I have an object in my class that only has one constructor, and this constructor takes a pointer to an interface implemented by my class. So I want to put it on the initializer list: : thatObject(this) But that gives me a warning and I can understand why giving a pointer to an unconstructed class is not a good idea. S...
If thatObject is guaranteed to never dereference the given pointer until after it's constructor is complete, then ignore or suppress the warning. If you don't feel safe guaranteeing that it will never in the future dereference the pointer, than go with the second option. In MSVC the code to supress a warning is: #prag...
7,424,298
7,429,743
Efficient way to test ODBC connection
Our product is a TCP listening transaction processor. Incoming connections are assigned a thread to handle the connection and a DB connection to work with. Rather than costly approach of establishing new DB connection for each incoming client connection, we maintain a pool of database connections. The database connecti...
Well the official way is SQLGetConnectAttr( SQL_ATTR_CONNECTION_DEAD ) which tests if the connection was working when last attempted. Or SQLGetConnectAttr(conn, SQL_COPT_SS_CONNECTION_DEAD, ...) which tests if the connection is working now.
7,424,401
7,424,415
Why does returning a malloc'd pointer here result in "HEAP CORRUPTION" on free?
note: please suppress comments about "C++? Use std::string!". This question is using C strings but is more about memory management than strings in general. I have this function char* strclone( char* src ) { char* dst = (char*)malloc(strlen(src+1)); strcpy(dst,src); return dst; } The function should work ...
I believe that the problem is that you've written (char*)malloc(strlen(src+1)); Notice that in the call to strlen, you have written strlen(src + 1) instead of strlen(src) + 1 This first line says "the length of the string starting one character past src," which is the length of the string minus one (or total garbage...
7,424,613
7,424,682
***glibc detected*** free(): invalid pointer:
I get the error in the title when I try to run my code... here's what I'm running class MyQueue { tile* queue; int size; public: MyQueue(int cap); ~MyQueue(); void enqueue(tile t); tile dequeue(); bool isEmpty(); }; void MyQueue::enqueue(tile t) { queue[size] = t; size++; } tile MyQueue::d...
The problem might be due to the fact that in the constructor you're dynamically allocating an array: queue = new tile[cap]; but in deque you delete it using the non-array delete operator. tile* victim = queue; queue++; delete victim; It just looks like the logic in the code is mismatched. On one hand there is code...
7,424,615
7,424,620
Equation not working correctly in C++
//Samuel LaManna //Program 1 (intrest rate) /*Variables: Principal=P Interest Rate=R Times Compounded=T Answer=A */ #include <iostream> //Input/output using namespace std; int main () { int P, R, T, A; ...
I'll guarantee that, if you're doing interest rate calculations (or anything else requiring floating point accuracy), you should not be using an int data type. In addition ^ is not the power operator, it's the exclusive-or operator. You need to look into the pow standard library function. That should hopefully be enoug...
7,424,647
7,436,323
Can a string literal be subscripted in a constant expression?
This is valid, because a constexpr expression is allowed to take the value of "a glvalue of literal type that refers to a non-volatile object defined with constexpr, or that refers to a sub-object of such an object" (§5.19/2): constexpr char str[] = "hello, world"; constexpr char e = str[1]; However, it would seem tha...
The intent is that this works and the paragraphs that state when an lvalue to rvalue conversion is valid will be amended with a note that states that an lvalue that refers to a subobject of a string literal is a constant integer object initialized with a constant expression (which is described as one of the allowed cas...
7,424,721
7,424,744
Help with POW function in C++
m having trouble with the pow function. The equation is A=P*((1+R)/T)^T were "^" is to the power of. How would i use the pow function, i only see examples that are 4 to the 5th power, nothing like what i have to do
it would simply be A = pow((1+R)/T , T) * P;
7,424,805
7,424,837
How to iterate/count for a multimap<string,string>
My class is like this: class Outgoing { multimap<string,string> outgoing; public: void makeConnection(string key, string value) { outgoing.insert(pair<string,string>(key,value)); } void iterate() { multimap<string, string>::iterator it; multimap<string, string>::ite...
You can use the count function for this, which returns the number of entries in the multimap with the the given key. In your example, writing outgoing.count("str1") would produce the value 2. In C++, there is no way to iterate over just the unique keys in a multimap. If you want to iterate over just those keys, ther...
7,424,859
7,424,877
Mysterious reference to empty constructor
Here's my header file Normal.h: #ifndef NORMAL_H #define NORMAL_H #include "Vector3.h" class Normal { public: Vector3 pos; Vector3 direction; Normal(Vector3, Vector3); }; #endif Here's the cpp file Normal.cpp: #include "Normal.h" #include "Vector3.h" Normal::Normal(Vector3 pos, Vector3 direction) { th...
This is not an uncommon C++ issue. To fix it try Normal::Normal(Vector3 pos, Vector3 direction): pos(pos), direction(direction) { } The reason is that the way you defined your constructor, C++ says: Create a Normal object whose fields are initialized to their default values Then assign the fields. But what are the d...
7,424,879
7,424,923
C++ Float Var rounding
Possible Duplicate: Equation not working correctly in C++ Help with POW function in C++ In This code: //Samuel LaManna //Program 1 (intrest rate) /*Variables: Principal=P Interest Rate=R Times Compounded=T Savings=S Interest=I */ #include <iostream> //Input/output #include <cmath> //Math Functions using...
Let's assume that I know nothing about what cout does. Because I know nothing about cout, I do a search engine query for "c++ cout". I click on one of the links on the first page, such as this MSDN doucmentation. According to that page, I find that cout is an ostream that outputs to the standard output. So let's look u...
7,425,241
7,425,255
How to return NULL object in C++
I know that this might be a duplicate of: Return a "NULL" object if search result not found BUT, there's something different going on with my code because the asterisk doesn't solve my problem, which is this: Normal Sphere::hit(Ray ray) { //stuff is done here if(something happens) { return NULL; } //...
I think you need something like Normal* Sphere::hit(Ray ray) { //stuff is done here if(something happens) { return NULL; } //other stuff return new Normal(something, somethingElse); } to be able to return NULL;
7,425,318
7,425,335
Multiple inputs on one line
I have looked to no avail, and I'm afraid that it might be such a simple question that nobody dares ask it. Can one input multiple things from standard input in one line? I mean this: float a, b; char c; // It is safe to assume a, b, c will be in float, float, char form? cin >> a >> b >> c;
Yes, you can input multiple items from cin, using exactly the syntax you describe. The result is essentially identical to: cin >> a; cin >> b; cin >> c; This is due to a technique called "operator chaining". Each call to operator>>(istream&, T) (where T is some arbitrary type) returns a reference to its first argument...
7,425,749
7,425,767
Trouble with this C++ snippet
I don't understand what this snippet is do, if anyone could explain it would help out a great deal. bool result; for (std::set<_Tp>::const_iterator o = objs.begin(); o != objs.end(); o++) { //confusion here, what does this do result |= accept(c, *o, bid); //accept returns a bool } retur...
|= is a bitwise or, not a logical or. You have removed the logic out of the snippet, but basically what it does is return true as long as any object within the set is 'accepted', whatever the definition of accept is.
7,425,880
7,427,971
assigning chinese as DBCS
In my code I can do: wchar_t *s = L"...some chinese/japanese/etc string.."; and this works okay. but if I do: char *s = "...some chinese/japanese/etc string..." I end up with s assigned to "???????" (not a display problem, there are actual question marks in the value). Given that I'm on a US/1252 Win 7 (VS2010) and...
Yes, you really do need to do that. There are no MBCS string literals in C++. (In theory you could do something like char *s = "...\xa7\f6\d5..." with the right bytes, but that would be difficult to write and read.)
7,425,890
7,426,305
C++ / SDL animation speed
so I am working on a game, following a tutorial online. Currently I have some FPS built into the system, and a simple animation which uses pieces of a sprite like such: if( frameCount > 12 ) frameCount = 0; //hero frames SDL_Rect clip[ 13 ]; clip[ 0 ].x = 0; clip[ 0 ].y = 0; clip[ 0 ].w...
You have separate your refresh rate (60 fps) from your animation rate. The best solution, in my opinion, is to tie your animation rate to the real time clock. In SDL, you can do this with the SDL_Ticks() function, which you can use to measure time in millisecond resolution. As an example, consider this example (not wor...
7,426,049
7,426,075
converting from upper to lower case and vice-versa
I am writing code to enter a string and convert all its uppercase letters to lowercase and vice versa: #include <iostream> #include <string> using namespace std; int main(){ string s; cout<<"enter the string :"<<endl; cin>>s; for (int i=0;i<s.length();i++){ if ('a'<=s[i] && s[i]<='z'){ ...
You're converting all lower case to upper case in the first if-statement. However, the same letters that were changed to uppercase will immediately be changed to lower case again in the second if-statement. What you want is an else if.
7,426,105
7,426,163
abstract methods and overiding function in C++ and Java
In C++ and Java, or their respecting rules, what limits are placed on overiding abstract methods. Must you match the arguments or return type. I usually see abstract functions implemented with only a return type and no arguments, is it up to derived class to specify the rest. How does it work exactly?
Method overriding must have the same method signature of the parent method it's overriding, otherwise it's not called overriding. Java: public abstract class AbstractTest { public abstract void test() throws Exception; } public class ConcreteTest extends AbstractTest { @Override public void test() throws...
7,426,294
7,426,315
C++ setting array values in a class
I am having trouble with what seems like a very simple concept. I have a class like such: class Projectile { public: int count; int projectiles[1][3]; Projectile(); void newProjectile(); }; Projectile::Projectile() { count = 0; } void Projectile::newProjectile() { projectiles[0][0] = { 1, 2,...
projectiles[0][0] = { 1, 2, 3 }; This isn't correct. Initializer lists can only given at the point of declaration. You have to assign values independently to each location of the array elements. std::vector<std::vector> twoDimArray; is what you want. struct foo{ std::vector<std::vector<int> > twoDimArray; vo...
7,426,422
7,426,562
Multiple inheritance casting from base class to different derived class
Let's assume there is such class hierarchy: class A //base class class B //interface class C : public A, public B Then C object is created: A *object = new C(); Is it possible to cast object to B ? Important: I assume I don't know that object is C. I just know that it implements interface B
No. This is not possible (direct casting from A* to B*). Because the address of A and B are at different locations in class C. So the cast will be always unsafe and possibly you might land up in unexpected behavior. Demo. The casting should always go through class C. e.g. A* pa = new C(); B* pb = static_cast<C*>(pa); ...
7,426,575
7,426,604
Is time_t returned by time() zone specific?
I am just new to <time.h> and have a question regarding to time_t and time(). I read the function time() documented as follows: time_t time ( time_t * timer ); Get current time Get the current calendar time as a time_t object. The function returns this value, and if the argument is not a null pointer, the value is a...
No it's not zone specific. It returns a value that's a count of the number of seconds since 1 Jan 1970 in UTC, ignoring leap seconds. So (in principle) if two machines execute the call at the exact same time, the value returned will be the same, even if they work in two separate time zones.
7,426,603
7,426,775
Qt customizing save file dialog
I need to customize default Qt save file dialog: add some options in it. For example, adding some checkboxes with my own values in it between file type and save/close buttons. Have Qt any ways to do it?
You can customize the Qt file dialog as long as you're okay with using the "non-native" Qt file dialog that comes with Qt; the other option Qt provides is to use the OS's native file dialog, but if you do that there is no way (that I'm aware of) to customize the dialog. Here's an example of an enhanced file dialog clas...
7,426,781
7,426,806
C++ Programming tools
My teacher recommended us to use notepad++ and cygwin for our programming needs. Are there any better solutions anyone can recommend out there to program and compile?
Myriad of various IDE's.... Eclipse CDT, Visual Studio Express, Code::Blocks, DevCPP.... And yes, Notepad++ and Cygwin with gcc would be a very viable option if you only need to compile single files for your homework.
7,426,803
7,427,821
retranslateUi() clears QLabel text
My qt4-based application dynamically changes the GUI language by calling retranslateUi() function. It works like a charm, but when it processes the QLabel which text changes by the program, it tries to translate original text - the one, specified in Qt Designer, not the one, set by my program. I understand it happens b...
As I remember, in Designer you can uncheck on QLabel should it be translated. By default it is. Choose label you don't want to be translated, in property editor scroll to "text" property, expand it and uncheck translate checkbox. Then you should generate ui_*.h file again. After that your label shouldn't be in retransl...