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
4,063,396
4,063,494
How does stringstream work internally?
I'm asking in context of performance. Is stringstream simply a string/vector, so writing to it may result in its whole content being copied to a bigger chunk of memory, or is it done in a more tricky way (say, a list of strings or whatever)?
It's up to the standard library vendor how to implement stringstream (or any library feature for that matter). You can look at the sstream header shipped with your compiler to see how it's implemented there. That much on the theoretical side... As far as practical experience and measurements show, ostringstream is ofte...
4,063,400
4,066,238
Logging Guard to limit semi-constant log messages
I'm using boost log in my application for logging. However, in some sections of my code I have some log statements that could occur very often if something goes wrong. I'd want some kind of guard that can limit log messages when it detects that the same log message appears constantly. e.g. (This is a simplified example...
How about something simple, you could encapsulate it if you wanted to: int tooMany = 10; int count = 0; while(!framebuffer.try_pop(frame)) { if(count < tooMany) { BOOST_LOG(trace) << "Buffer underrun."; } count++; } if(count >= tooMany) { BOOST_LOG(trace) << "Message repeated: " << count << " ti...
4,063,405
4,063,419
c++ crashes on writing public variable
I wrote a simple test program in c++ but why does this crash on: s[i] = s[i] - 'a' + 'A'; with the exception: Access violation writing location 0x01327808 #include "stdafx.h" #include <iostream> using namespace std; class String { public: char *s; int len(); void upper(); String(char*); }; String::String(...
It's because of: String s("test"); What this does is to pass the const char * "test" to your constructor which then simply stores the address of that string. Later, when you try to modify the memory that the pointer points to, that's undefined behaviour. Typically, string literals will be stored in read-only memory to...
4,063,630
4,063,658
When a RAII object fails to construct
Suppose I construct a RAII object, and that object may fail to construct. How do I handle this? try { std::vector<int> v(LOTS); // try scope ends here because that's what the catch is for } catch( const std::bad_alloc& ) { // ... } // v? what v? Granted, the default constructor of std::vector won't throw a...
Depends what you mean by "proceed". Whatever operation requires the resource will fail: that's what "requires" means. So when you want to continue after an error, you might end up writing code like this: void something_using_RAII(thingummy &t) { vector<int> v(t.size_required); // do something using v } ... fo...
4,063,766
4,063,901
Windows Explorer Context Menu
I want to add a context menu entry with C++. I've been searching but all I can find is some jackass trying to sell me some BS program that does it for me which is not what I am looking for. I'm not looking for anything that uses .NET or Visual C++ either. I want the straight C++ way of doing this.
A decent tutorial, ignore the jackass title, is available here. This kind of shell programming requires COM, no escaping that. Trying to write COM code without MSVC support classes is character-building. But possible, as long as you know COM really well.
4,063,961
4,063,994
Fast controlled copy from istream to ostream
I have to copy several bytes from a istream to a ostream, there are 2 ways that I know to perform this copy. myostream << myistream.rdbuf(); and copy( istreambuf_iterator<char>(myistream), istreambuf_iterator<char>(), ostreambuf_iterator<char>(myostream) ); I've found that rdbuf version is at least twic...
Can you use 0x? If so, then you can use copy_n: copy_n( istreambuf_iterator<char>(myistream), 100, ostreambuf_iterator<char>(myostream) ); EDIT 1: I know you're probably looking for a library solution, and you could probably have figured this out on your own. But in case you haven't thought of someth...
4,063,989
4,065,078
Converting UTF-8 with C++ standard libraries (no /clr)
I have a string like this: "These are Pi (\u03a0) and Sigma (\u03a3).". How can i convert this to contain and print effective characters, using C++ standard libraries? This solution http://msdn.microsoft.com/en-us/library/system.text.encoding.utf8(VS.80).aspx, use .NET framework (/clr compiling), that i want to avoid p...
I am not quite sure what you mean by "standard", but I guess you meant "unmanaged". If that's what you want, please try ICU. It is not very easy to master, but it is definitely capable of such conversions. BTW. If you simply want to convert UTF-16 encoded wstring to UTF-8 encoded string, you can do it with WideCharToMu...
4,064,010
4,064,023
What is the difference between the standard library and the standard template library?
I keep seeing reference to both the C++ standard Library and the C++ Standard Template Library (STL). What is the difference between them? Wikipedia mentions that they share some headers but that's about it.
The Standard Template Library (STL) is a library of containers, iterators, algorithms, and function objects, that was created by Alexander Stepanov; the SGI website has the canonical implementation and documentation. The standard library is the library that is part of C++; it includes most of the Standard Template Li...
4,064,088
4,064,158
no match for ‘operator<<’ in ‘os << "Test Failed ["’ when os is an ostream &
Edit: I incorrectly used #include <stdio.h> when I needed to include <iostream>. This happened mostly because I was integrating some C style code with a larger C++ program. EndEdit I'm using a simple test framework for my college class, but whenever I use the provided preprocessor macro I get these two errors. I've ex...
stdio.h is for C functions like printf and scanf. If you want to use C++ style I/O (streams) you need to include iostream.
4,064,134
4,064,161
ARRAYSIZE C++ macro: how does it work?
OK, I'm not entirely a newbie, but I cannot say I understand the following macro. The most confusing part is the division with value cast to size_t: what on earth does that accomplish? Especially, since I see a negation operator, which, as far as I know, might result in a zero value. Does not this mean that it can lead...
The first part (sizeof(a) / sizeof(*(a))) is fairly straightforward; it's dividing the size of the entire array (assuming you pass the macro an object of array type, and not a pointer), by the size of the first element. This gives the number of elements in the array. The second part is not so straightforward. I think...
4,064,228
4,064,268
One single class for const and non-const iterators. Is it possible?
I'm implementing a custom container with an STL-like interface for a 3D grid control for my scientific software. This is my second question regarding the iterator class for this container. Thanks for helping me with the first! My question is just like "How do you avoid code duplication when implementing const and non-c...
If you want to go kind of hacky, you may be able to abuse "const_cast" to create a const iterator out of a non-const one.
4,064,286
4,064,315
C++ "const" keyword explanation
When reading tutorials and code written in C++, I often stumble over the const keyword. I see that it is used like the following: const int x = 5; I know that this means that x is a constant variable and probably stored in read-only memory. But what are void myfunc( const char x ); and int myfunc( ) const; ?
void myfunc(const char x); This means that the parameter x is a char whose value cannot be changed inside the function. For example: void myfunc(const char x) { char y = x; // OK x = y; // failure - x is `const` } For the last one: int myfunc() const; This is illegal unless it's inside a class declaratio...
4,064,412
4,064,839
Can I use c++ to traverse DOM from C# BHO?
I'm writing a Browser Helper Object (BHO) for Internet Explorer in C#! I want to look for text nodes in the DOM, which requires me to traverse the whole DOM tree if I want to differentiate between text nodes and other types of nodes. This is supposedly time consuming in C#, but should be almost instantanious in C++ (?)...
Where did you get the "supposedly" from? Most of the time will be spent in the code that implements the DOM. Which was written in C++ by Microsoft. Marshal.GetIUnknownForObject() gets you a raw interface pointer that you can pass to native code. It needs to QI that pointer for IHtmlDocument2 and take it from there.
4,064,601
4,064,640
Copy data from fstream to stringstream with no buffer?
Is there anyway I can transfer data from an fstream (a file) to a stringstream (a stream in the memory)? Currently, I'm using a buffer, but this requires double the memory, because you need to copy the data to a buffer, then copy the buffer to the stringstream, and until you delete the buffer, the data is duplicated in...
// need to include <algorithm> and <iterator>, and of course <fstream> and <sstream> ifstream fin("input.txt"); ostringstream sout; copy(istreambuf_iterator<char>(fin), istreambuf_iterator<char>(), ostreambuf_iterator<char>(sout));
4,064,763
4,065,018
Increase in memory footprint. False alarm or a memory leak?
I have a graphics program where I am creating and destroying the same objects over and over again. All in all, there are 140 objects. They get deleted and newed such that the number never increases 140. This is a requirement as it is a stress test, that is I cannot have a memory pool or dummy objects. Now I am fairly c...
It does seem possible that this behavior could come from a situation in which there is no leak. Is there any chance that your heap is getting fragmented? Say you make lots of allocations of size n. You free them all, which makes your C library insert those buffers into a free list. Some other code path then makes all...
4,064,813
4,097,721
I want to make my own source code editor, what are the good choices to make?
I've had it of those dozens of editors which never provides simple things like: distinguish type keywords and instruction keywords so I can put different colors on them. being cross platform using a standard GUI lib like qt gtk etc (notepad++, yes, I almost hate you). enough keyboard shortcut like duplicate line, comm...
Like everyone else is saying, it's probably more trouble than it's worth, but if you really want to do it, Qt's a good choice since it's cross platform. Use QSyntaxHighlighter to do your keyword/type highlighting, and take full advantage Qt's support for keyboard shortcuts.
4,064,841
4,064,862
Strange error, set<int>::begin() always returning const iterator
Why is set.begin() always returning a const iterator and not a standard one? 35 int test(){ 36 std::set<int> myset; 37 myset.insert(2); 38 myset.insert(3); 39 int &res = *myset.begin(); 40 return res; 41 } test.cpp:39: error: invalid initialization of reference of type ‘int&’ from expression of ty...
It's not returning a const_iterator, rather the key_type of std::set<int> is const int. Remember that keys in a std::set are constant. You can't change a key after it's inserted into the set. So when you dereference the iterator, it necessarily returns a constant reference. So you need to say: const int &res = *myse...
4,064,910
4,065,003
Understanding the '&' operator
As of what I know about '&' operator, it returns the base address of the operand in memory. Let us imagine the following scenario (as on my machine): sizeof(int) = 4 bytes sizeof(float) = 4 bytes sizeof(char) = 1 byte Now, if I write something like this: void main() { int i = 5411; int *ip = &i; char *c = &i; pr...
You seems to have trouble understanding how integers are stored in memory. Take 5411 as example. 5411 = 1010100100011 this number 13 binary digits has however, since an int is 32-bit, it must be pad to 32 digits 5411 = 00000000 00000000 00010101 00100011 On a little endian machine (x86, ARM by default), the least sig...
4,064,984
4,065,059
Sort char * With Special (german) Characters?
The problem I'm having is that I need to sort a whole bunch of char pointers, but they have special characters. I managed to get a sorting procedure like so: std::sort(dict_.begin(), dict_.end(), comp); bool comp(NumPair& a, NumPair& b) { return boost::lexicographic_compare(a.pFirst, b.pFirst); } This worked grea...
You might want to show more of your code, like exactly what strings you're using that are causing this problem. I'm easily able to sort a set of German words, and any words beginning with non-ASCII special German characters are ordered at the end. This happens even without any special German locale settings, since in...
4,065,016
4,065,520
itk filereader causes access violation exception
I have a problem with an Access Violation Exception. I am using itk and read a File with it's file reader. ThreeDImageFloatType* MyClass::loadImage(std::string filename){ const char* cfilename = filename.c_str(); fileReader = ImageFileReaderType::New(); fileReader->SetFileName(cfilename); try{ fileReader->Update...
I just found the answer myself. The Solution to the Problem lies within this line: fileReader = ImageFileReaderType::New(); It's a smart pointer. So when the function returns, it gets unregistered. So the pointer received from that function to an internal buffer (the read file), can't be used any more. While the point...
4,065,113
4,065,126
Confused with Overriding in C++
I'm trying to make a class inherits from other and override some methods. Classes 'header' is: class Objeto { public: virtual bool interseca(const Rayo &rayo, float magnitud); virtual bool breakNormal(const Punto &punto); virtual Vector normal(const Punto &punto); int idMaterial; }; class ...
You can only get polymorphic behavior if you access the class via a pointer or reference. In addition to that, you are slicing the object when you are copying the derived type to a non-pointer/non-reference base type. Slicing: http://en.wikipedia.org/wiki/Object_slicing Given these definitions: #include<iostream> cla...
4,065,315
4,065,443
Doubles as template type?
I am trying to create a generic class that handles ints, doubles, and strings. However, when trying to instantiate the template class with I get the following error message: error: 'double' is not a valid type for a template constant parameter The instantiation works completely fine with int types, as does the inter...
template<NODETYPE> friend Forest<NODETYPE>& operator+(Forest<NODETYPE>& f1, Forest<NODETYPE>& f2); template<NODETYPE> friend ostream& operator<<(ostream& output, const Forest<NODETYPE>& f1); template<NODETYPE> friend void outputHelper(ostream& output, const ForestNode<NODETYPE>& currentNode, int depth); Thes...
4,065,378
4,067,169
Qt get children from layout
I try to hide all widgets in layout. But looks like findChildren doesn't work for layout. Here's my sample code: QLayout * layout = widget -> findChild<QLayout *> (layoutName); QList<QWidget *> list = layout -> findChildren<QWidget *> (); cout << list.size() << endl; size is 0, but inside this layout I have a few wi...
The layout does not "inject" itself in the parent-child tree, so the widgets stay (direct) children of their parent widget. You could use QLayout::count() and QLayout::itemAt() instead.
4,065,458
4,065,464
C++ -- Question about typedef
Given the following code: typedef struct IntElement { struct IntElement *next; // use struct IntElement int data; } IntElement; typedef struct IntElement { IntElement *next; // Use IntElement int data; } IntElement; // why I can re-use IntElement here? I use above data structure to def...
Neither is C++. The first declaration is old C syntax. The second is someone who realized that you don't need that in C++ and then forgot it one line later. C++ does it like this: struct IntElement { IntElement* next; int data; };
4,065,607
4,065,708
C++ - Stack Pop() Function with Singly Linked list
For starters this is apart of my current homework assignment for my Data Structures class. I am not asking for answers, I am asking for help. I have a stack class that is implementing a Linked List instead of an array. I am currently trying to write my pop() function. I have a node for my theBack part of the stack. I a...
A stack is actually reasonably simple to implement as a singly linked list, due to its restricted push and pop operations. It's actually a lot easier if you insert pushed elements at the head of the list. Since it's homework, I'll provide pseudo-code. To initialise a stack, it's simply creating: top -> null with this ...
4,065,622
4,065,630
What type of class do I need for this?
I want to create a class that is usable without being instanced, but that can also be instanced. Similar to a math class I suppose. Thanks
If you add static methods to the class, you can call them like this ClassName::staticMethod(); You are not stopped from also creating instances of this class.
4,065,847
4,065,859
How do I insert queue elements into a vector?
I have typedef std::queue<MyObject*> InputQueue; std::vector<InputQueue> inp_queue; Now what I want to do is define at runtime say 5 queues and place data on those queues like inp_queue[1].push(new MyObject()); etc. I got it to compile, but it core dumps right away. I guess I need to actually add the queues to the ...
You have not allocated any of the 5 queues. Try: typedef std::queue<MyObject*> InputQueue; std::vector<InputQueue> inp_queue(5); inp_queue[1].push(new MyObject()); Also not that std::vector uses indices starting from 0, so to insert into the first queue: inp_queue[0].push(new MyObject()); Follow-up to your edit: The ...
4,065,919
4,065,958
vector of char stars in c++
If I declare a vector as such: vector<char *> charStarVec(4); and then add values to it like so: charStarVec.at(0) = (char *) "one"; charStarVec.at(1) = (char *) "two"; charStarVec.at(2) = (char *) "three"; charStarVec.at(3) = (char *) "four"; Then no problems result. (I can print out all the vector elements just fine...
Here are two reasonable routes. Use the std::string class instead of char pointers, or use strdup(...) to copy the array to a newly allocated char* pointer once you've loaded and null terminated it: charStarVec.at(4) = strdup(carr); You'll have to free(...) each pointer when you're done, or you'll leak memory.
4,065,996
4,066,006
C++ - Linked List Stack Operator Overloading Function
I am currently working on a stack that implements linked list. I am having a problem when it comes to overloading the "=" operator. I am very clueless as to what to do. If anyone could point me in a good direction that would be awesome. //operator overload template <class S> const Stack<S>::operator=( const Stack& s ) ...
You need to empty the current stack, before pushing data on it. You should add a removeAll function, and call it at the top of the assignment (after a check for self assignment, which is also a good idea). Otherwise, it looks correct. So, the end result would be: //operator overload template <class S> const Stack<S>:...
4,066,023
4,066,091
Adding list of check boxes in a single widget in Qt
I'm using Qt Creator 2.0.1 (Qt 4.7). I need a widget which can hold multiple check boxes vertically. The check boxes will be added to the widget dynamically upon user interaction with other UI element. The widget will have fixed width and height so if there are too many check boxes, a vertical scroll bar should appear....
Well you could indeed use a QListWidget with checkable items (see void QListWidgetItem::setFlags, or use a QScrollArea containing a QWidget where you would dynamically add QCheckBoxes. The choice is up to you!
4,066,129
4,066,138
C++ Struct pointer question
This is probably simple, but im trying to try and understand pointers better. Lets say I have a struct struct Person{ char Name[20]; char ID[15]; char Address[50]; char Number[15]; }; and lets say I have a bunch of these stored in memory like one after the other. so now i declare a new pointer to the struct. ...
It will point to the second struct. The pointer will be advanced by sizeof(Person).
4,066,140
4,066,211
C++ - Unresolved External Error
I am currently writing a stack class that uses linked lists. I feel like i am done but I keep getting an Unresolved external error. Here it is: Error: Unresolved external 'Stack<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::Node::Node(std::basic_string<char, std::char_traits<char>, std::allo...
That's complaining that a function Stack<...>::Node::Node(std::string) does not seem to have an implementation. Most likely it's that you've added the declaration for that constructor and used it somewhere, but your implementation is missing or misnamed.
4,066,233
4,066,281
Pointer to base class
If I have the following classes: class A { ... } class B { ... } class C : public A, public B { ... } and somewhere I detect that the pointer of class B that I have actually points to a class C, but a function requires a pointer to class A, what can I do to get that pointer to class A?
If you know for certain that you have a B* that points to a C object, you can use a pair of static_casts: B* bp = new C(); C* cp = static_cast<C*>(bp); A* ap = static_cast<A*>(cp); The only way to cast across the inheritance hierarchy is to use dynamic_cast, which requires that the type is polymorphic (that is, your ...
4,066,304
4,066,310
set comparator type expected error
Sorry guys, if this is a stupid question. I have a set of integers which I want be sorted using a function object. But when I try to compile the following code, I get the error "invalid template argument for '_Pr', type expected". class MySortedUser{ vector < user* > & users; public: MySortedUser(vector <...
MySortedUser(_users) is an expression (it creates a MySortedUser object). The object is constructed at run time. Templates need to be instantiated at compile time. You need to give std::set the type as a template argument and the constructed comparator as a constructor argument: std::set<int, MySortedUser> MySet(MySo...
4,066,411
4,066,441
How do I add a copy constructor and assignment operator to this class?
I'm having trouble adding a copy constructor to this class: http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html I need to add it so that I can add the concurrent_queue in an stl vector container. Tried the below, and it almost compiles. In fact, if I remove ...
Both boost::mutex and boost::condition_variable only have default constructors. Aside from that, you don't want their (potentially locked) state to be copied - just use the default constructors. Also you shouldn't copy the_queue directly as this is not thread-safe.
4,066,576
4,066,591
Passing a parameter to a comparison function?
When using the STL sort algorithm on a vector, I want to pass in my own comparison function which also takes a parameter. For example, ideally I want to do a local function declaration like: int main() { vector<int> v(100); // initialize v with some random values int paramA = 4; bool comp(int i, int j...
You cannot access the local variables of a function from within a locally defined function -- C++ in its current form does not allow closures. The next version of the language, C++0x, will support this, but the language standard has not been finalized and there is little support for the current draft standard at the m...
4,066,666
4,066,676
>> and << operator overloading
I just did a quiz for my programming class and got this question wrong: The return type of the function to overload the operator << must be a reference to an ostream object. This does not seem right at all to me. Surely C++ is a bit more open ended than this. But I thought I'd ask here anyway. How is this right (...
It is not required by C++ that the return type be a reference to an ostream object. However, if you are trying to do something like: cout << instance_of_custom_type << 3 << "hi" << endl; Then you will need: ostream &operator << (ostream &os, custom_type &t); However, if you were doing something like writing a large i...
4,066,741
4,070,202
need help in pointers
SPI_SPI (char* p1, char* p2) { return ( *(point*)p1 == *(point*)p2 ) ? '0' : 'F'; // epsilon } is this show that p1 caste to point class pointer and give pointer to this pointer point class.. am i right? i am not getting pointer in every case plz refer me a usefull link related to it... or explain me this .
That function compares two points using comparison specified for point object by casting point structures referenced through char* pointers. That code equals to: // casting char* to point* point* ptPointer1 = (point*)p1; point* ptPointer2 = (point*)p2; // extracting values point pt1 = *ptPointer1; point pt2 = *ptPoint...
4,066,763
4,066,772
Semantics of pointer dereference operator `->`
I am looking for some help regarding the pointer dereference operator -> . Let me describe what I am trying to do. I am implementing a unidirectional iterator for a special container. The container is special in the sense that it does not physically allocate any space for the contained values but generates them at run...
Here is the answer to answer your questions, though I do not think they are so useful as you might hope: Yes, it is a unary operator No, it does not care what member is. If member isn't a field/member of the class/struct pointed to be the return of operator -> then the compiler will complain. member could indeed be e...
4,066,928
4,069,323
Getting page number from a Word document
I want to create an index page for which I need the page number from the Word document. I am working with C++ managed code and Word interop.
See here for info on this. This is for C#, but the classes are all available in C++/CLI. There is page number info info here for including page numbers in a footer, and also on handling Table of Contents.
4,066,930
4,066,973
Reading a line of numbers and stopping after the end of the line
Example of input: I 67 85 49 R 4 D 4 G 65 97 /end input.txt So I'm sure this is a elementary programming question but i've been playing with code and tried looking it up in books. But I need a way to keep reading in numbers after the I because theoretically the numbers could be endless. Now the D,G,R I can just code it...
case 'I': { std::string str; std::getline(inFile, str); std::istringstream iss(str); iss >> value; while(iss) { outFile << value; MainInsert(value); iss >> value; } break; }
4,067,017
4,067,051
Is there a way to output text to a file in different colors on Linux?
I am outputting data to a txt file on Linux using C++. Is there a way to output a portion of a line of text in a different color? For example, I'd like to be able to write 0.000 Watts in red. Total Power Usage of this model: 0.000 Watts
Plain text files (*.txt) don't support color in any way. You will have to use a different format, such as RTF or HTML.
4,067,045
4,067,383
problem with qt for symiban none-english project name
how can i create a qt project with none-english name.or how can i deploy the application on to device with a none-english application name,like chinese or japanese.
The toolchain supports e.g. UTF-8 encoding. Just save your non-ASCII files as UTF-8 and you should be all right.
4,067,135
4,067,145
C++ Generating a 4 digit random number
I need to generate a 4 digit random number in C++ I used the following code #include<time.h> int number; number=rand()%1000; srand ( time(NULL) ); but its doesn't gives a total random number
number = rand() % 9000 + 1000; There are 9000 four-digit numbers, right? Starting from 1000 till 9999. rand() will return a random number from 0 to RAND_MAX. rand() % 9000 will be from 0 to 8999 and rand() % 9000 + 1000; will be from 1000 to 9999 . In general when you want a random number from a to b inclusive the for...
4,067,206
4,067,260
how to implement timer in C/C++
I want to call a function of the business class after every 2 hours. I m not getting any way to implement same in C/C++ without using a while loop. My problem is that i cannot use while(1) as this does not retun back the control for further execution. Any pointer in this regards wud be helpful....:) thnaks
In plain C, I would've considered using the alarm(2) or setitimer(2) functions. Alternatively, spawn a thread and do the waiting from there. If you decide on the alarm or setitimer routes, bear in mind that you'll need to write signal handlers and may need a dispatch loop to note that it is time to do the periodic main...
4,067,246
4,067,316
How to set predefined macros in Code::Blocks
Is there a way to set some predefined Macros for my local installation of Code::Blocks. To elaborate on that, basically I would like to have certain blocks compiled only at pc and not anyplace I send the code to. One way to achieve this is as follows: #define MYPC #ifdef MYPC //do something #else // do something else...
Project - Properties - Project's build options - Compiler Settings - #defines. Edit. Example of #defines edit box: CONSTANT1 CONSTANT2="0" Gives the following command line: g++ -DCONSTANT1 -DCONSTANT2="0" ...
4,067,256
4,067,262
How do I stop program from skipping over getline?
This is my main program, int main () { string command; cin>>command; if(command == "keyword") { string str, str2, str3, str4; cout << "Enter first name: "; getline (cin,str); cout << "Enter last name: "; getline (cin,str2); cout << "Enter age: "; ...
string command; cin>>command; after this just eat the end of the line string restOfLine; getline(cin, restOfLine); Otherwise the '\n' in the line where you input command is not consumed and the next readline reads just it. HTH
4,067,302
4,067,329
g++ compile using custom header file
I want to use a header file, its included as #include <custom.h> how can I compile it by using the custom.h header file ? I tried -I /path/to/custom.h , but its giving me error that its not a directory..
-I /path/to This will enable all headers in that directory to be found. In man gcc, search (using / in your pager) for "-I dir": -I dir Add the directory dir to the list of directories to be searched for header files. Directories named by -I are searched before the standard system include directories. If the direct...
4,067,395
4,067,413
GNU STL string: is copy-on-write involved here?
(Disclaimer: I don't know what the C++ standard might say about this..I know, I'm horrible) while operating on very large strings I noticed that std::string is using copy-on-write. I managed to write the smallest loop that would reproduce the observed behaviour and the following one, for instance, runs suspiciously fas...
C++ doesn't distinguish between the operator[] for reading and writing, but only the operator[] for const object and mutable (non-const) object. Since a_copy is mutable, the mutable operator[] will be chosen, which forces the copying because that operator returns a (mutable) reference. If efficiency is a concern, you c...
4,068,041
4,068,517
Calling base class move ctor [C++0x]
Which is the right way to call base class move ctor? this (works in MSVC2010, but not in CBuilder2010): struct Foo { Foo(Foo&& other) { } }; struct Bar : public Foo { Bar(Bar&& other) : Foo((Foo&&)other) { } }; or (works in CBuilder2010, but not in MSVC2010): struct Foo { Foo(Foo&& other) { } }; struct B...
The first option looks logical although I would spell it std::forward<Bar>(other). I have no idea what causes CBuilder to think that the type of &other is Bar&& and not Bar*. Basically what's happening here is that once an rvalue reference is named it is no longer an rvalue reference, that's what std::forward is for, i...
4,068,046
4,068,065
Getting to know size of a reserved memory on the heap
Is there a way to get the size of previously allocated memory on a heap? For example: //pseudo-code void* p = operator new (sizeof(int) * 3); unsigned size = getSomeHow(p);
You can't do it at all times, since operator new() can be overloaded in any reasonable way and maybe even without using the runtime heap. In case operator new() is implemented with malloc() in Visual C++ you can use _msize().
4,068,114
4,068,146
conditional breakpoints with c++ in Visual Studio
Is it possible to have conditional breakpoints (without changing anything about the sourcecode) in Vistual Studio 2008 with C++ language? thanks!
Yes, you can specify a condition on a breakpoint in any language. Note that this can slow execution down quite a bit, depending on the condition and how often the check has to be made.
4,068,141
4,068,184
How do I check if one vector is a subset of another?
Currently, I think my best option is to use std::set_intersection, and then check if the size of the smaller input is the same as the number of elements filled by set_intersection. Is there a better solution?
Try this: if (std::includes(set_one.begin(), set_one.end(), set_two.begin(), set_two.end())) { // ... } About includes(). The includes() algorithm compares two sorted sequences and returns true if every element in the range [start2, finish2) is contained in the range [start1, finish1). It re...
4,068,165
4,068,227
qt gui transported from windows to linux
i wrote an application in qt creator and designed it on windows. when i'm running the application on Linux the size of the controls is too small. all the controls are in layout. which property should i change?
minimumSize should do the trick. It ensures your controls have at least this size, but they can still grow if needed (for example because of bigger fonts depending on the platform, and, for instance dpi settings). But this setting would also affect your windows version. Another way would be to override the pixelMetric(...
4,068,286
4,068,330
Boost enable_if problem
This is more or less copy pasted from boost docs and I keep getting an error (actually alot of errors) I'm trying to make sure that a template class is only used with numbers using boost. This is an exercise in boost, rather than making a template class that only uses numbers. #include <boost/utility/enable_if.hpp> #in...
You never actually created a class template called A. You just created a specialization. You need to first create the A class template with a dummy parameter for the enabler to work. using namespace boost; template <class T, class Enable = void> class A { }; template <class T> class A<T, typename enable_if<is_arith...
4,068,511
4,068,652
Change the Type of a Template Class
As an example in Ruby (1.8) i = 4 i.class => fixnum i += 1.3 i.class => float Can this be achieved in C++? for instance template<class T> struct Number {}; Number<int> foo; foo.changeTypeToFloat(); // <-- Possible? // foo now Float?
C++ is a statically-typed language. A variable has a fixed type. The best you can do at the language level is a conversion to a new variable, e.g.: int i = 5; float f = static_cast<float>(i); Alternatively, you could write a variant class, and have the conversion handled internally. But this would really be syntact...
4,068,718
4,069,013
Containers of generic Future/Promises
We are trying to produce a library component which will perform asynchronous calls. For various reasons this needs to have a C like interface, so we are providing a large set of static functions as the interface to the library. We also need the user to have control over the memory. So most functions look something lik...
Either you will use C++ to do polymorphism or you will reimplement polymorphism with void*. The easiest way to solve your problem is to give Future<T> a base class that doesn't depend on T. Usually I do it like this: class Future {}; template<class T> class FutureOf : public Future {}; Then, you can create containe...
4,069,686
4,069,979
Explain a line of two's complement math counting free virtual memory
I have a Visual Studio 2008 C++ application for Windows Mobile 6.x where I'm counting the amount of free virtual memory available for a given process. (I realize it is not taking fragmentation in to account.) My code looks basically like this: MEMORY_BASIC_INFORMATION mbi = { 0 }; /// total free memory available to th...
Allocation granularity for VirtualAlloc is normally 64KB. He tries to do something meaningful if the AllocationBase is not a multiple of 64KB. I don't think it is meaningful at all, his bitmasks still assume a granularity of 64KB and he doesn't use SYSTEM_INFO.dwAllocationGranularity. Which has this comment: This v...
4,069,968
4,070,328
Linked-list assignment operator
I'm trying to figure out if i have the general idea behind the assignment operator for Doubly Linked Lists using a current node (no front or back). This is my pseudo code. I need to get this concept down. If anyone can help, that would be sweet. Loop to start temp = temp->back loop to count if 0 receive...
struct Node { Node *prev, *next; int entry; explicit Node(int entry) : prev (0), next (0), entry (entry) {} }; Node* copy_list(Node *node) { assert(node); // require a non-null pointer // copy "current" node Node *new_list = new Node(node->entry); // copy backward from node to beginning Node *dest ...
4,070,304
4,070,330
How can I find an element in a set which contains pointers to the elements?
Edit: I fixed my mistake: I'm using a set and not a vector. Please consider the following example code: set<Foo *> set_of_foos; set_of_foos.insert(new Foo(new Bar("x"))); set_of_foos.insert(new Foo(new Bar("y"))); [...] // The way a "foo" is found is not important for the example. bool find_foo(Foo *foo) { return s...
find_foo(new Foo(new Bar("x"))); does not sound like a good idea - it will most likely (in any scenario) lead to memory leak with that search function. You could use find_if with a functor: struct comparator { Foo* local; comparator(Foo* local_): local(local_) {} ~comparator() { /* do delete if needed */ } ...
4,070,349
4,070,415
SQLite Character transformation
I've written a program that converts a SQL Server table into a SQLite table. This is a C++ program using ADO (COM) to retrieve the data from SQL Server and the C SQLite interface (wrapped by my own C++ class). In SQL Server, I have a record with a field having the contents: HÄAGEN-DAZS (That first A has two dots over i...
0xC4 is not utf-8 for Ä. It is isolatin-1 (also known as 8859-1) for Ä, which means it is also (sort of) the utf-16: u00C4. The utf-8 encoding is 0xC3 0x84, two bytes.
4,070,360
4,072,252
VS2010: Setting Up File Details on Application Build
After I right-click on a file in Windows (ex: Windows 7 64bit), a pop-up menu appears with "Properties" on its bottom. Going to: Mouse-Right-Click on a File -> Properties -> Details I get a tab with file description containing: File Description Type File Version Product Version Copyright Size Date modified Language ...
In Visual C++ project add a resource file with version information. See MSDN help: http://msdn.microsoft.com/en-us/library/aa381058(v=VS.85).aspx
4,070,424
4,070,532
'Unloading' a Python module and 'unbinding' associated APIs
I have a program which embeds Python (via Boost.Python), and provides an 'extension' framework. I wish to unify these two parts by allowing extensions to load a set of Python bindings for their API, however I'm confused as to how I would I 'unregister' these APIs when the plugin is unloaded. Is this even possible with...
There is a related discussion about unloading/reloading python modules. Check out the 3rd answer (here), the one that starts off with: To cover my shame, here is a Python list thread that discusses how to delete a module. The summary: it can be especially difficult if the module is not pure python.
4,070,543
4,070,791
Simple and efficient container in C++ with characteristics of map and list containers
I'm looking for a C++ container that will enjoy both map container and list container benefits. map container advantages I would like to maintain: O(log(n)) access operator[] ease of use sparse nature list container advantages I would like to maintain: having an order between the items being able to traverse the lis...
std::map is already a sorted container where you can iterate over the contained items in order. It only provides O(log(n)) access, though. std::tr1::unordered_map (or std::unordered_map in C++0x) has O(1) access but is unsorted. Do you really need O(1) access? You have to use large datasets and do many lookups for O(lo...
4,070,558
4,070,603
Why doesn't my performance counter code work?
I am trying to use the Windows performance counters to get the virtual bytes usage of a specific process. It seemed simpler to read the % CPU usage, so I thought I would try to get that to work first. At the top of the file, I have this: #include <pdh.h> #include <pdhmsg.h> Then in a function, I have this: PDH_STATUS...
I think you need to remove the ampersand (don't take the address of counter): status = PdhGetRawCounterValue(counter, NULL, &rawValue); And it looks like the call to PdhCloseQuery also should probably not be passing the address of the parameter. status = PdhCloseQuery(query);
4,070,836
4,071,051
Boost::Asio Threaded Server Asynchroun Problem. Nothing happen
I´m making a Server with the BoostLib, and so i am using the asio lib. I made an Server class. Server::Server(unsigned short port) : m_IOService(), m_Socket(m_IOService), m_Endpoint(boost::asio::ip::tcp::v4(), port), m_Acceptor(m_IOService) { m_Port = port; m_Acceptor.open(m_Endpoint.protocol()); m_Accept...
Perhaps this code is not the full version but it's not clear why you waiting for all your threads to exit (using join) before opening up the socket. I would think you need to move this: // Wait for all threads in the pool to exit. for (std::size_t i = 0; i < threads.size(); ++i) threads[i]->join(); to be the ...
4,070,849
4,070,868
A variable not detected as not used
I am using g++ 4.3.0 to compile this example : #include <vector> int main() { std::vector< int > a; int b; } If I compile the example with maximum warning level, I get a warning that the variable b is not used : [vladimir@juniper data_create]$ g++ m.cpp -Wall -Wextra -ansi -pedantic m.cpp: In function ‘int main()...
In theory, the default constructor for std::vector<int> could have arbitrary side effects, so the compiler cannot figure out whether removing the definition of a would change the semantics of the program. You only get those warning for built-in types. A better example is a lock: { lock a; // ... // do criti...
4,070,915
4,070,938
Classes and namespaces sharing the same name in C++
Let's say I have a class called 'foo' in namespace "abc"... namespace abc { class foo { int a; int b; }; } ...and then say I have another class called "abc" in a different namespace #include "foo.h" namespace foo { class abc { abc::a = 10; }; } abc::a would not be a define...
You can use ::abc::xx, that is, identify the variable or type as its absolute namespace path. If you don't specify an absolute name, relative names start going upwards in the including namespaces/classes.
4,071,068
4,071,093
Correct C pointer notation
Which one is the best way to write: string* str Or: string *str Is there any drawback of side effect to one of them ? Thanks
A reason to prefer the second one is when you declare multiple variables at once: string *str, *foo; string* str, foo; Those two lines are different, the first one declares to pointers, whereas the second one declares one pointer to string and one string. [Comment by FredOverflow] This problem can be solved by some te...
4,071,145
4,073,911
Boost wave context concept_check issue
I'm debugging with concept check in boost and gcc. The code finds are error like this /home/hoffman34/boostlibsinstall64/include/boost/wave/util/ cpp_iterator.hpp:2495:1: instantiated from 'boost::wave::pp_iterator<boost::wave::context<__gnu_cxx::__normal_iterator<char*, std::basic_string<char> >, boost::wave::cpp...
That's a known issue (see Boost ticket #1079), but not in Wave but in Spirit's (V1.x) parse tree generation code. The concept checking complains about an incomplete type. This error only pops up when compiling Wave using gcc and with --enable-concept-checks or #define _GLIBCXX_CONCEPT_CHECKS 1.
4,071,313
4,071,326
C++: reading from a file with null characters
I have to read data from a file for an assignment unfortunately instead of spaces separating the various fields there are null characters. When taking integers from the file they are extracted fine however with the strings i just get a blanks space and garbage from my uninitialized character array. Any ideas as how to ...
Use getline and pass \0 (null character) as the delimiter.
4,071,356
4,071,410
stack data between languages
Lets say for example, I push a large amount of data onto the stack using some assembly code. My question is, is it possible to manipulate this data in a language such as c++ by passing the address of the stack pointer to the c++ program(or some other way)? If so, how would c++ handle this data? Meaning, how would I det...
Yes, you can do it, provided of course that you use the calling convention properly, so that the data is well clear of any regions of the stack that the C++ code is using as stack. Stack memory is just memory, and as far as the code receiving this pointer is concerned, there's no difference between pushing some values ...
4,071,495
4,074,625
OpenGL on Android using C++ only
I'm developing an Android application for Android 2.1. I'm trying to code OpenGL's stuff with C++ only. Do you know a tutorial or an article showing an example about how to do that? UPDATE: Sorry, I've forget to say that I will use a Java home application to launch main activity. I'm trying to say if I have to code on ...
In the Android NDK there is a san-angeles demo under the samples directory which shows off using OpenGL ES 1.x in C code and a Java wrapper. As for changes to already existing C++ code be aware that there is no official STL implementation for the NDK r4 (although I believe there are some ports available) [edit: as of N...
4,071,522
4,071,560
Struct Not Accepting wchar_t
That's the only thing I can think of. The thing is sentient. I have a struct as follows: struct NumPair { wchar_t *pFirst, *pSecond; int count; with ctor, copy assignment and construction as NumPair( wchar_t *pfirst, wchar_t *psecond, int count = 0) NumPair( const NumPair& np ) NumPair& operator=( const NumPai...
Strings have to begin with an L to be wide-character string literals, e.g. L"abcdefghijk", which is of type const wchar_t*. Without the L it's a narrow-character string, of type const char*, so the error is correct; attempting to cast a const char* to wchar_t* won't work, because you're just changing the type of the po...
4,071,579
4,071,615
c++ scoping weirdness - Why do inner-type parameters of member functions do not need scoping?
Let's say we're given this class with an inner struct. class Some { public: struct Crap{}; Crap Process(Crap& c); } Some::Crap Some::Process(Crap& crap) { Crap moreCrap = .. } It makes sense to me that the return type (Some::Crap) in "Process" is scoped. It makes sense to me that no scoping is needed i...
In fact, the parameter type does need to be qualified (unless your example is incorrect and you intend for Process to be a member function of Some).
4,071,673
4,071,908
"thread-local storage not supported for this target", suitable #ifdef?
Since every compiler has its own version of thread local storage, I ended up creating a macro for it. The only problem now is GCC (with pthreads turned off), which gives me: "thread-local storage not supported for this target" Fair enough, given that pthreads are actually turned off in this case. The question is, is th...
Your compile command line either has -lpthread or not: You could include a -DHAVE_PTHREADS there as well. If you really want GCC/ELF specific runtime dectection, you could resort to weak refs: #include <pthread.h> extern void *pthread_getspecific(pthread_key_t key) __attribute__ ((weak)); int main() { if (pthrea...
4,071,675
4,071,879
Visual C++ Error: "Identifier "IMSNMessenger" is undefined" - after adding tlb file
I am learning to work with the MSN Messenger API. After adding the tlb file, and copy/pasting some example code, I noticed that in the Visual c++ IDE it's telling me about an undefined identifier. Though once I compile the code, everything works fine. I see the problem: The problem is that the IDE (the intellisense, mo...
Well, it should not recognize MSNMessenger::, you used the no_namespace attribute on the #import directive. Taking a wild guess, maybe you started this first without that attribute and the IntelliSense parser isn't smart enough to recognize that you changed it. Close your solution and delete the .ncb file in the proje...
4,072,016
4,072,141
QApplication in unicode
QApplication's constructor takes an (int argc, char**argv) to handle any Qt specific commandline arguments. What if my app is in unicode? And I have a wchar_t** argv? It seems a bit silly to create a char* copy of all the commandline args to pass to a library that is itself unicode.
Yes, it would be. If it wasn't for this note: Warning: On Unix, this list is built from the argc and argv parameters passed to the constructor in the main() function. The string-data in argv is interpreted using QString::fromLocal8Bit(); hence it is not possible to pass, for example, Japanese command line arguments o...
4,072,066
4,130,319
how to access c++ memory mapped files in java
I have a windows c++ application that creates a memory mapped file for a bitmap that is updated frequently. I would like to access to this memory mapped file to display the live image in a java application. How can I do that? I know that FileChannel can be mapped to memory but I cannot see how to access a memory mapped...
I have finaly used jna and the platform library that they provide. The Kernel32 package offers access to the CreateFileMapping and MapViewOfFile functions.
4,072,292
4,078,086
stepping through program with debugger takes a long time
When I debug my program by stepping through it, it sometimes takes a long time for the step to finish. This was not happening in the beginning of the project so most likely it is due to something I have added. Could you give me pointers as to how to remedy this. I did notice one of the problems was due to the main...
With gdb just set scheduler-locking mode to desired behaviour. In this case: "The step mode optimizes for single-stepping. It stops other threads from "seizing the prompt" by preempting the current thread while you are stepping. Other threads will only rarely (or never) get a chance to run when you step."
4,072,353
4,077,567
How to determine if a CD is in CD-ROM drive
I was wondering if there is a Windows API that can tell me if there is a empty CD is inside a CD-ROM/DVD-Rom drive. I've already looked at GetVolumeInformation(), but that only brings back information on the actual CD-ROM drive, not the media that is inside it, if there's even a CD in it or not. All I'm trying to d...
Call GetFileAttributes() on the root directory. GetFileAttributes() is quite optimized as it's commonly used as a check whether a file or directory exists. Another method is to call GetDiskFreeSpace, which (despite its name) also returns the total disk size. The Shell also has some useful functions. SHGetDriveMedia wi...
4,072,363
4,072,393
How to extract digit(s) from the end of string
Given strings like the following: sdfsd34 sdfdsf1 I would like to extract: 34, 1 using c++ (STL but no boost), c. thanks
You’re searching for the function string.find_last_not_of: string str = "sdfsd34"; size_t last_index = str.find_last_not_of("0123456789"); string result = str.substr(last_index + 1);
4,072,392
4,072,419
SDL/C++ include problems
I started doing game for my school project in C++ with SDL library. But I cannot find what am I doing wrong in code below. I am using VC++ 2008, here is the compilator output: 1>Compiling... 1>initGame.cpp 1>.\dec.h(4) : error C2065: 'SDL_HWSURFACE' : undeclared identifier 1>.\dec.h(4) : error C2065: 'SDL_DOUBLEBUF' :...
Move #include <SDL.h> to dec.h. When compiling initGame.cpp, you never told the compiler to look at SDL.h, so it couldn't figure out what any of those SDL_ things were and got very confused. Also, don't #include one *.cpp file from another. Take the #include "initGame.cpp" out of main.cpp.
4,072,437
4,109,091
Strange effect with sizeof
The following code works as intended: template <typename T> inline char* Utils::PushData(char* destination, T data) { memcpy(destination, &data, sizeof(data)); destination += sizeof(T); return destination; } However, when I use this: template <typename T> inline char* Utils::PushData(char* destination, T d...
Surely sizeof(T) and sizeof(data) should be the same, right? Or have I misunderstood what sizeof actually gets the size of? That's not necessarily the case. Consider this one: template<typename T> void f(T data); int main() { f<char[1]>(0); } This will yield sizeof(char[1]) when applied to T, and sizeof(char*) when ...
4,072,534
4,078,166
How to tell if user clicked Cancel when calling MSI functions?
My installer bootstrap app makes a bunch of MSI calls at the start in order to get information from the MSI (what version(s) are installed, what features are installed, property values, paths, etc.). While these MSI calls are being made, Windows installer throws up a window with a Cancel button on it. My code has traps...
If I understand correctly, it sounds like you're getting small "Preparing you install" style dialogs. If that's the case, what you want to do is preface your calls with MsiSetInternalUI to hide all (or most) UI. Note that if you then call MsiInstallProduct or similar to kick off the install, you may need to restore a n...
4,072,578
4,072,604
Inside a while loop, is the last comma separated statement guaranteed to run last?
Consider the following (trivial) code segment: while (i++, i <= 10) { // some more code } In the general case, C++ allows comma separated statements to be evaluated in any order. In the case of a while loop, are we at least guaranteed (by the specification) that the last statement (which is used as the condition for...
In the general case, C++ allows comma separated statements to be evaluated in any order. If you're referring to the commas between function arguments, that's just a separator. In your case, you're using the comma operator, and that introduces a sequence point that guarantees that all side-effects from the comma's lef...
4,072,676
4,072,797
Books/resources on learning Xlib ("the Linux Petzold"?)
I have stubbornly decided to learn Xlib programming for Linux GUIs, just for fun & the gained experience. I'm young and have lots of time to read useless stuff. Nobody seems to want people to learn this, though, as everywhere I look, askers are being bombarded with suggestions of using a toolset instead - usually Qt or...
There used to be a whole series of books on X programming (they actually worked their way up to Xlib!) but the one you probably want is Xlib Programming Manual Over a year later I ran across a "retro UNIX" imgur album which has a picture of it! Keeping good company with the Red Book (the Postscript Language Reference ...
4,072,713
4,072,756
Creating a test project
I have a solution consisting of several library project and one application project. I want to create a separate application test project. However, my problem is how I can write test for the application project since I can't link to it? I've added the application project as a reference in "Common Properties", but I get...
I can think of three solutions to this - none 100% as clean as I'd prefer. Compile test code into a test library that is conditionally linked to the application program, and is driven by test input to the program. So in effect you use your own app as the test driver Make you application a shell only and put all unit ...
4,072,725
4,072,755
Private DLL Functions are Publicly Accessible
I have generated a Win32 DLL using C++ in Visual Studio 2008. All of my functions are defined within the only class native to the new DLL. Some functions are declared as private, and others are public. I'm using Dependency Walker to objectively verify the accessibility of the functions in my DLL. My class is declar...
Yes, the compiler depends on the integrity of the .h file with the class definition to enforce the privacy of class members. If someone modifies the class definition, the loader will be more than happy to link those private functions.
4,072,868
4,073,878
Suggestion for C IDE?
I used to use gcc compiler on my unix machine. I am now forced to work on a windows machine. Is there any cool IDE or a simple editor for C with a unix terminal like feel (Black Screen and colored syntax on it :)) What other editors/IDE are as robust as gcc for windows? Also what is your personal favorite. I would lik...
If you are used to a Unix-y feel and are looking for a text editor, I'd honestly avoid installing Visual Studio. It's a nice IDE, but it is very heavyweight and perhaps much more than you are asking for. That said, you might of course find that you like it, but be aware that you are potentially looking at a several-hun...
4,072,939
4,073,000
directx 9 SetTime is not member c++
ok i found a tutorial on animated mesh. when im trying t use their code i get an error on this line m_pAnimController->SetTime(..).. it says that SetTime is not member. i thought it was mistake the author made but i found another tutorial used the same format like var->SetTime(..).. so im not sure what is wrong im usin...
You are certainly using a newer version of DirectX 9 than the guy who wrote the sample you are using. The function SetTime() has been changed for AdvanceTime().
4,073,119
4,073,219
Topological Sort with Grouping
Ok, so in topological sorting depending on the input data, there's usually multiple correct solutions for which order the graph can be "processed" so that all dependencies come before nodes that are "dependent" on them. However, I'm looking for a slightly different answer: Suppose the following data: a -> b and c -> d...
Label all root nodes with a level value 0. Label all children with level value parent+1. If, a node is being revisited i.e it already has a level value assigned, check if the previously assigned value is lower than the new one. If so, update it with the higher value and propagate them to the descendents. now, you have ...
4,073,210
4,073,226
Calling an overridden function from a base class?
My question will probably be best explained by an example. For example, I have 2 classes: A base class and a derived class: class baseClass { public: baseClass() { foo(); } virtual bool foo() { printf("baseClass"); return false;} }; class derivedClass : public baseClass { public: bool foo(...
You should not call a virtual method from a constructor because the object has not yet been fully constructed. Essentially, the derived class doesn't exist yet, so its methods cannot be called.
4,073,276
4,073,316
Use templates to get an array's size and end address
You can use templates to find the length of an array. template<typename T, size_t N> size_t arraylen( T(&)[N] ) { return N; } I'd like to take this idea one step further. struct Foo { template< typename T, size_t N > Foo( /* ??? */ ) : ptr(?), size(?) { } char* ptr; size_t size; }; int main() { Foo fo...
struct Foo { template< typename T, size_t N > Foo(T(&array)[N]) : ptr(array), size(N) { } const char* ptr; size_t size; }; array is a reference to an array of N T's. The same is true of the original code, but the parameter isn't given a name. But this really isn't calculating the address at compile time....
4,073,289
4,073,313
Compiling simple Hello World program on OS X via command line
I've got a simple hello world example that I'm trying to compile on OS X, named hw.cpp: #include <iostream> #include <string> using namespace std; int main() { cout << "Hello world!" << endl; return 0; } I'd like to compile it using gcc, but I've had no success. I'd also like to hear the other options, like using ...
Try g++ hw.cpp ./a.out g++ is the C++ compiler frontend to GCC. gcc is the C compiler frontend to GCC. Yes, Xcode is definitely an option. It is a GUI IDE that is built on-top of GCC. Though I prefer a slightly more verbose approach: #include <iostream> int main() { std::cout << "Hello world!" << std::endl; }
4,073,292
4,073,529
C++ Shader matrix question
While examining shader examples I recently found that it's pretty often to pass the world inverse transpose matrix with the world and world-view-projection matrices. float4x4 worldMatrix; float4x4 worldViewProjectionMatrix; float4x4 worldInverseTransposeMatrix; Unfortunately, I couldn't understand the purpose of that ...
The world inverse transpose matrix is often used for transforming normals into viewspace.
4,073,298
4,073,362
C++ - Operator Overload Error C4430: missing type specifier - int assumed
I compiled my code using Borland 5.5 and there was no errors that popped up. But it ll didn't run correctly so I decided to use Visual Studio 2010 to debug my program. Visual studio is giving me this error : Error 1 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\user...
There is no return type defined for your operator. const Stack<S>::operator=( const Stack& s ) should be changed to : const Stack<S>& Stack<S>::operator=( const Stack& s )
4,073,428
4,073,491
strtod and underflow
I would like to detect underflow when converting string to double in C++ (Visual C++ 2010) using strtod function. The code below doesn't work as I expect although I did it according to strtod's documentation: char numStr[] = "123456.122111111123123123123132123123123123123124434345345"; char* pEnd; double d = strtod(...
I think you're confusing "loss of precision" with "underflow". You would get underflow with input like 1.0e-1000. strtod doesn't directly report a loss of precision, but you could try changing the last digit and reparsing, or something like that.
4,073,616
4,073,626
Assigning max value of smaller integer to a larger integer
Consider the following code: uint32_t x = ~uint8_t(0); std::cout << x << std::endl; Now, I fully expected this to output 255, but instead it output 4294967295. I'm aware of integer promotion in C++, but I can't understand why this would happen. The way I understand it, the expression ~uint8_t(0) should evaluate to ...
The integral promotions are performed on the operand of the unary ~, so the uint8_t(0) is promoted to int and then the ~ is evaluated. It's equivalent to ~(int)(uint8_t)0 You can get the maximum value representable by a type using std::numeric_limits<T>::max(); if the type is unsigned, you can also cast -1 to that ty...
4,073,706
4,073,739
c++ having trouble with abstract class
I have this class that will help me with animated meshes. class CAllocateHierarchy: public ID3DXAllocateHierarchy { public: STDMETHOD(CreateFrame)(THIS_ LPCTSTR Name, LPD3DXFRAME *ppNewFrame); STDMETHOD(CreateMeshContainer)(THIS_ LPCTSTR Name, LPD3DXMESHDATA pMeshData, LPD3DXMATERI...
The error message indicates that you didn't override all the abstract methods from the interface ID3DXAllocateHierarchy. Looking through the arguments, I see that you forgot the "const" for several arguments to the CreateMeshContainer() method. As a result, the C++ compiler thinks this is a different method, and compla...