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
888,673
888,705
Microsoft objects, the Release() functions return value?
I'm curious because I couldn't find out about this on MSDN. I've found the Release() function is present in various COM objects which I'm obviously supposed to use for deleting pointers. But I'm not sure what does it return exactly? I used to think it would return the number of references which still exist to the objec...
Your theory is true. COM memory management is based on reference counting. The Release method of IUnknown interface will decrement the reference count and return it. That function will not release references. It doesn't know who holds the reference. It just decrements the reference count until it reaches zero and then ...
888,718
889,346
How do you link a .lib file without putting them into the compilers library folder?
Is there a way in my code that I can link to the library files I need so that I do not have to setup each individual compiler I use? I want to be able to use Visual C++.net 2005, G++, etc. I am trying to make a cross platform game engine, but some platforms use a custom compiler and I want to make my engine as versati...
There is a tool called mpc that can create both makefiles and VC projects from the same mpc DSL. If you would use that tool you would specify the link dependencies (libraries) once in the pmc files and it would generate makefiles for g++ and project files for Visual Studio that contain the necessary information on how ...
889,262
889,284
iterator vs reverse_iterator
I'm using std::map to store a lot of elements (pairs of elements) and I have a "little" doubt. What is more efficient to iterate all elements over my std::map, iterator or reverse_iterator?
Does it really matter? these are the types of the micro optimizations you must try to avoid IMHO. Also, even if the iteration time changes for very large number of elements in the map, the fact that you are trying to iterate through all the elements of such a big map means that most probably you have chosen a wrong da...
889,434
889,898
Markdown Implementations for C/C++
What is the best implementation of Markdown for C or C++? I found these via Google, and would appreciate comments about which ones work well and which ones don't (and which ones I may have missed): peg-markdown Discount Cpp-Markdown libsoldout (formerly libupskirt)
peg-markdown depends on GLib and other 3rd part tools. I've tested it, it works quite well. Advantages: Dual-licensed under GPL and MIT. Uses internally formal grammar, so easy to maintain and extend. Disadvantages: Depends on GLib Provides C API. Cpp-Markdown, Most C++ code but it is quite slow and little bit bl...
889,581
889,679
Why C++ compiler (gcc) thinks function is `virtual' field?
I have a the following method definition in my class: virtual Calc* Compile( Evaluator* evaluator, ResolvedFunCall* fun_call, string* error); For some reason, GCC complains that: error: 'Compile' declared as a 'virtual' field Any ideas why it would believe Compile to be a field, instead of a method?
I get that error when the first parameter doesn't make sense to it. Check that Evaluator is known as type: struct A { virtual void* b(nonsense*, string*); }; => error: 'b' declared as a 'virtual' field struct A { virtual void* b(string*, nonsense*); }; => error: 'nonsense' has not been declared To find out ...
889,756
889,768
C++ - How to know if there is no returned value from a map::upper_bound()?
I've got a very simple map : std::map<int, double> distances; distances[20.5] = 1; distances[19] = 2; distances[24] = 3; How do i know if there isn't any returned value, when using a map::upper_bound() in this case for example: std::map<int, double>::iterator iter = distances.upper_bound(24); (24 is the max key so an...
if (iter == distances.end()) // no upper bound
890,081
892,440
PHP/Rails/Django/ASP websites should have been written in C++?
I was looking at a SO member's open source project. It was a web framework written in C++. Now you are all probably ready to respond about how C++ is a horrible language to do websites in, and that in websites, the bottleneck is in the database. But... I read this post: http://art-blog.no-ip.info/cppcms/blog/post/42 an...
The problem with the article you link to is that the author clearly doesn't really know what he's talking about when he asks where the "bottleneck" is; the fact that someone has more web servers than database servers doesn't mean "the database can't be where the problem is". What's generally meant by "the database is t...
890,164
890,229
How can I split a string by a delimiter into an array?
I am new to programming. I have been trying to write a function in C++ that explodes the contents of a string into a string array at a given parameter, example: string str = "___this_ is__ th_e str__ing we__ will use__"; should return string array: cout << stringArray[0]; // 'this' cout << stringArray[1]; // ' is' co...
Here's my first attempt at this using vectors and strings: vector<string> explode(const string& str, const char& ch) { string next; vector<string> result; // For each character in the string for (string::const_iterator it = str.begin(); it != str.end(); it++) { // If we've hit the terminal char...
890,292
890,319
How to Learn C++ When you are stuck in your ways with newer Languages?
Possible Duplicates: What is the best approach for a Java developer to learn C++ How would you go about learning C++ if you were "Stuck in your ways" with newer languages like Java or C#? I've been working as a developer for 3 years, I've got both a Bachellors and a masters in computing science from a Reputable UK U...
By reading Stroustroup's C++ Programming Language. Switched from Common Lisp.
890,371
890,383
How to sort an object std::vector by its float value
I have a C++ std::vector denoted as: std::vector<GameObject*> vectorToSort; Each object in vectorToSort contains a float parameter which is returned by calling "DistanceFromCamera()": vectorToSort.at(position)->DistanceFromCamera(); I wish to sort the vector by this float parameter however std::sort does not appear t...
you want to use a predicate like this: struct VectorSortP { bool operator()(const GameObject *a, const GameObject *b) const { return a->DistanceFromCamera() < b->DistanceFromCamera(); } }; std::sort(vectorToSort.begin(), vectorToSort.end(), VectorSortP());
890,619
890,650
Prompting a user for the filename or directory
I'm prompting the user for a filename, if they enter a valid filename the first time, it works. However, if its invalid the first time, every other check fails. How would I fix this? Also, let's say they just specify a directory, how would I get the names of all the text files and how many there are? int main() { ...
This is because the error bits in the object 'inFile' have been set. You need to reset the error bits before you do anything else. if (!inFile) { cout << "\n**File failed to open**\n\n"; inFile.clear(); } else break;
890,672
890,721
How to overload the indirection operator? (C++)
I'm trying to create an iterator class as a member-class for a list class, and am trying to overload the indirection operator (*) to access the list it's pointing to: template<class T> T list<T>::iterator::operator*(iterator& iter) { return ((iter.lstptr)->current)->data; } where lstptr is a pointer to a list, cur...
You overloaded the multiply operator. Take the parameter out to make it an indirection operator. template<class T> T list<T>::iterator::operator*() { return ((this->lstptr)->current)->data; } You should also have it return a reference if you want code like *IT = 3; to compile. template<class T> T& list<T>::iterat...
890,895
923,468
Using escaped_list_separator with boost split
I am playing around with the boost strings library and have just come across the awesome simplicity of the split method. string delimiters = ","; string str = "string, with, comma, delimited, tokens, \"and delimiters, inside a quote\""; // If we didn't care about delimiter characters within a quoted section we c...
It doesn't seem that there is any simple way to do this using the boost::split method. The shortest piece of code I can find to do this is vector<string> tokens; tokenizer<escaped_list_separator<char> > t(str, escaped_list_separator<char>("\\", ",", "\"")); BOOST_FOREACH(string s, escTokeniser) tokens.push_back(s...
890,933
890,963
boost::shared_ptr use_count
I'm trying to understand what's going on in the following code. When object-a is deleted, does it's shared_ptr member variable object-b remains in memory because object-c holds a shared_ptr to object-b? class B { public: B(int val) { _val = val; } int _val; }; ...
The A-object will be cleaned up as soon as a is deleted at the end of its block. But the shared_ptr it contains was subsequently copied, incrementing its reference count. Thus, the B-object will have a reference count of 2 after c.setRef (referenced by the A-object and by the C-object's shared_ptr). When a is deleted a...
890,958
890,972
Can't push_front() a standard library list with my objects in C++
I have an class and I would like to use the standard library list to store a list of them. I essentially want to push_front() the list. So my code is like this: #include <list> /* ... lots of stuff ...*/ complexNode myObject(); std::list<complexNode> complexList(); myList.push_front(myObject); But the compiler thro...
std::list<complexNode> complexList(); shouldn't this be : std::list<complexNode> complexList; // without the ()
890,961
890,985
In C++, which is the way to access a 2D array sequentially (memory block wise)
Edit: I've removed the faster/more efficient from the question title as it was misleading..my intention was not optimisation but understanding arrays. Sorry for the trouble! int array[10][10], i, j; for(i=0;i<10;i++) { for(j=0;j<10;j++) std::cin>>array[i][j]; } Versus int array[10][10], i, j; for(i=0;i<1...
Aside from the fact that waiting on getting user input will be signifficantly slower than the array access, the first one is faster. Check out this page on 2D array memory layout if you want more background on the subject. With the second one you are checking A[0], A[10] ... A[1], A[11]. The first is going sequentiall...
891,054
891,330
Why do I need an *.obj file when statically linking?
I'm not sure why is this. I'm distributing a static *.lib across multiple projects, but this static lib generates many *.obj files. Seems like I need to distribute also those *.obj files with the *.lib. Otherwise, I get this error: 1>LINK : fatal error LNK1181: cannot open input file 'nsglCore.obj' Why is this? Is the...
I believe that your linker line is incorrect. The library should have a .lib suffix on it. So nsglCore should be nsglCore-Win32-Release.lib or maybe nsglCore-$(TargetPlatform)-$(ConfigurationName).lib or whatever the correct macro expansion is.
891,066
891,076
Why doesn't this return type work? (C++)
When I try to use my iterator class template<class T> class list { public: class iterator; }; template<class T> class list<T>::iterator { //stuff }; as a return type in an operator overloading, template<class T> class list<T>::iterator { public: iterator& operator++(); protected: list* lstptr; }; template<class T> i...
iterator is not yet known at that point. You need to tell it it's in the list<T> class: template<class T> typename list<T>::iterator& list<T>::iterator::operator++() { (this->lstptr)->current = ((this->lstptr)->current)->next; return *this; // *this here, since this is a pointer only } Notice the typename is r...
891,097
891,105
What does the '%lt' mean in C++? (NOT modulus, I know what that does)
I once saw this line of code: std::cout %lt;%lt; "Hello world!" %lt;%lt; std:: endl; And am wondering what %lt;%lt; means.
You must have seen that online. Someone uploaded this line: std::cout << "Hello world!" << std::endl; Which was translated to this for output to html: std::cout &lt;&lt; "Hello world!" &lt;&lt; std::endl; Because, of course, &lt; is the html entity for <. Finally, something somewhere decided to change the ampersands...
891,637
892,062
Calling swprint from a separate lib fails
I am facing a strange problem. I am using sprintf or swprintf according to the build defines with or without unicode. I have wrapped these functions in my own function like this: int mysprintf( MCHAR* str,size_t size, const MCHAR* format, ... ) { #ifdef MYUNICODE return swprintf( str, size, format); #else retur...
The problem indeed lies in that you have your own function with variable number of parameters. You need to get a pointer to the list of arguments and pass that on to the callees. va_start enables you to do just that and it needs the last pointer in the argument list to your function. int mysprintf( MCHAR* str, size_...
891,750
891,852
Partition sort programming problem
I need an algorithm to select the kth largest or smallest value. The values will be ints. My instructor told me to use a modified partition algorithm to find the kth largest or smallest value. Any thoughts?
The following is a description of the quickselect algorithm. I will assume that you want to find the kth smallest value. Take the first element of your array. This will be your pivot. Keep track of its position. Partition the array based on this pivot. Elements smaller than your pivot go before your pivot in the array...
891,913
891,924
C++ std::vector of pointers deletion and segmentation faults
I have a vector of pointers to a class. I need to call their destructors and free their memory. Since they are vector of pointers vector.clear() does not do the job.So I went on to do it manually like so : void Population::clearPool(std::vector<Chromosome*> a,int size) { Chromosome* c; for(int j = 0 ;j < size-1...
void Population::clearPool( std::vector <Chromosome*> & a ) { for ( int i = 0; i < a.size(); i++ ) { delete a[i]; } a.clear(); } Notice that the vector is passed by reference. In your code, a copy of the vector is used, which means that it is unchanged in the calling program. Because you delete the poin...
891,938
891,972
Developer notebook configuration
I want to buy a brand new notebook for out-of-the-office work. I mainly develop using VC++ (vs03) and c# (vs08) on large projects (10 gb builds). At office I've a quad core xeon with 10.000 rpm disk. What hardware, according to your experience, is the best for this kind of work in terms of price / performances / weight...
How often are you going to be on the road ? I have a 17" Dell Laptop for OOO dev work and to be honest, it's a pain in the ass to drag around and extremely unportable. That said it's a 1920 * 1200 res screen, 4Gb Ram, 7200 RPM disk. I've tried using Visual Studio on small res (1280*720) screens and I just loathe the ex...
892,057
892,111
Design Pattern for optional functions?
I have a basic class that derived subclasses inherit from, it carries the basic functions that should be the same across all derived classes: class Basic { public: Run() { int input = something->getsomething(); switch(input) { /* Basic functionality */ case 1: ...
You may find useful to read about Chain of responsibility pattern and rethink your solution in that way. Also you can declare 'doRun' as protected method and call it in the base default case. default: doRun(input); And define doRun in derived classes. This is so called Template Method pattern
892,133
892,303
Should I prefer pointers or references in member data?
This is a simplified example to illustrate the question: class A {}; class B { B(A& a) : a(a) {} A& a; }; class C { C() : b(a) {} A a; B b; }; So B is responsible for updating a part of C. I ran the code through lint and it whinged about the reference member: lint#1725. This talks about taking...
Avoid reference members, because they restrict what the implementation of a class can do (including, as you mention, preventing the implementation of an assignment operator) and provide no benefits to what the class can provide. Example problems: you are forced to initialise the reference in each constructor's initial...
892,458
892,531
cannot convert from 'WCHAR' to 'WCHAR [260]'
I am trying to modify the amcap, an application from Windows SDK's example to capture video from UVC webcam having resolution 1600x1200px. I am trying to hardcode some variables here like filename, default resolution, type of format etc. WCHAR wszCaptureFile[260]; gcap.wszCaptureFile = (WCHAR)"Capture.avi\0" //mod...
Provide a literal wide string and use the secure copy function: wcscpy_s(gcap.wszCaptureFile, L"Capture.avi"); The literal string provides the terminating zero bytes.
892,462
892,475
Character encoding confusion!
Having some issues getting my head around the differences between UTF-8, UTF-16, ASCII and ANSI. After doing some research I have some idea but it would be really useful if someone could explain exactly the difference between them (including the byte representation of a typical character from each). I quess my question...
I've found Joel's article on Unicode to explain this very well. Specifically it covers the history (essential for this subject), encodings (UTF-8/16 etc.) and code pages.
892,849
892,858
c++ win32 popup animation
I am creating an application that uses popups. However, I would like to animate this popup (a win32 window, a HWND), for example having it slowly extend from the bottom of my screen, moving upwards. Should I make a few dozens of calls to the SetWindowPos function with a small pause in between, or is there a better way ...
You could also use the AnimateWindow() Windows API function.
893,305
893,350
How do I extract the angle of rotation from a QTransform?
I have a QTransform object and would like to know the angle in degrees that the object is rotated by, however there is no clear example of how to do this: http://doc.trolltech.com/4.4/qtransform.html#basic-matrix-operations Setting it is easy, getting it back out again is hard.
Assuming, that the transform ONLY contains a rotation it's easy: Just take the acos of the m11 element. It still works if the transform contains a translation, but if it contains shearing or scaling you're out of luck. These can be reconstructed by decomposing the matrix into a shear, scale and rotate matrix, but the r...
893,509
937,531
"Deprecated" notation for Sun's C++ compiler?
Does the Sun compiler have a notation to mark functions as deprecated, like GCC's __attribute__ ((deprecated)) or MSVC's __declspec(deprecated)?
It seems that one solution that would work on any compiler that supports #warning would be: Copy the header in question to a new, promoted header name Remove the deprecated functions from the promoted header file Add to the old header file: #warning "This header is deprecated. Please use {new header name}"
893,670
893,685
How do I construct a std::string from a DWORD?
I have following code: Tools::Logger.Log(string(GetLastError()), Error); GetLastError() returns a DWORD a numeric value, but the constructor of std::string doesn't accept a DWORD. What can I do?
You want to read up on ostringstream: #include <sstream> #include <string> int main() { std::ostringstream stream; int i = 5; stream << i; std::string str = stream.str(); }
893,940
894,085
What standard does this "ISOTIME" structure represent?
In our code, we have a 16-byte packed struct that we call "ISOTIME": typedef struct isotime { struct { uint16_t iso_zone : 12; // corresponding time zone uint16_t iso_type : 4; // type of iso date } iso_fmt; int16_t iso_year; // year uint8_t iso_month; // month uint8_t iso_day; // d...
International standards rarely concern themselves with detailed in-memory representations of data , particularly at the bit level (exceptions of course for floating point standards). This is because such things are inherently unportable. That's not to say that there is no standard for this structure, but I think it unl...
894,124
894,151
Win32 function for scheduled tasks in C++
I have a function in C++ that needs to be called after a period of time and this task is repeated. Do you know any built-in function or sample code in Win32 or pthread? Thanks, Julian
How about SetTimer. Create a wrapper function to use as the callback for set timer. Wrapper function calls your function. After your function finishes, wrapper function calls SetTimer again to re-set the timer.
894,222
894,255
C++ destructors question
With regards to the sample code below, why is the destructor for the base class called twice? class Base { public: Base() { std::cout << "Base::Base()" << std::endl; } ~Base() { std::cout << "Base::~Base()" << std::endl; } }; class Derived : public Base { public: Derived() { ...
What happens is called slicing. You initialize an object of type Base with an object of type Derived. Since any object of type Derived has also an object of type Base contained (called "base-class sub-object"), there will be two Base objects and one Derived object in existance throughout the program. The Derived object...
894,258
894,288
unix domain stream sockets sending more data then it should be
I have two simple programs set up that share data through a unix domain socket. One program reads data out of a Queue and sends it to the other application. Before it is sent each piece of data is front-appended by four bytes with the length, if it is less then four bytes the left over bytes are the '^' symbol. The cl...
Rather than padding your packet length with '^', you'd be far better off just doing: snprintf(sizeofStringBuffer, 5, "%04d", sizeOfString); so that the value is 0 padded - then you don't need to parse out the '^' characters in the receiver code. Please also edit out your debug code - there's only one write() in the cu...
894,389
894,405
Synchronized value between C# and C++?
Is there a function which exists in both C# and (unmanaged) C++ which returns a synchronized number (such as float or int)? For example is there something which brings the exact system time to at least the second which would return the exact same result on both C++ and C# is called in the exact same time? Just wonderin...
Are you talking about managed C++ (C++/CLI) or native C++ here? If you're using managed code throughout, then the obvious solution is to utilise the Environment.TickCount property. In native C++, the equivalent is the Win32 API GetTickCount function.
894,521
894,606
determing access type of member variables of a class
Would following the table below be the best way of determining the access type of member variables of a class that I'm creating (sorry if this table is hard to see; it's the same table shown http://www.cplusplus.com/doc/tutorial/inheritance/)? Access public protected private members of the ...
The table is correct, if that's what you're asking. What it's saying in words is that you can always access member variables of the class your method is in. If the member variable is defined in a parent class then you can only access it if the member variable is protected or public. If you're outside the class then you...
894,652
894,706
Inverse of A*X MOD (2^N)-1
Given a function y = f(A,X): unsigned long F(unsigned long A, unsigned long x) { return ((unsigned long long)A*X)%4294967295; } How would I find the inverse function x = g(A,y) such that x = g(A, f(A,x)) for all values of 'x'? If f() isn't invertible for all values of 'x', what's the closest to an inverse? (F...
You need to compute the inverse of A mod ((2^N) - 1), but you might not always have an inverse given your modulus. See this on Wolfram Alpha. Note that A = 12343 has an inverse (A^-1 = 876879007 mod 4294967295) but 12345 does not have an inverse. Thus, if A is relatively prime with (2^n)-1, then you can easily creat...
894,666
894,688
DevC++ (Mingw) Stack Limit
Is it possible to set the stack limit in DevC++? Basically the same as "ulimit -s" would do on linux.
Try giving this option to ld (the linker): --stack reserve --stack reserve,commit Specify the number of bytes of memory to reserve (and optionally commit) to be used as stack for this program. The default is 2Mb reserved, 4K committed. [This option is specific to the i386 PE targeted port of the linker] http://s...
894,723
894,766
Is it possible to add an item to the right-click context menu of a Mac OS programmatically?
I have a program that works with a variety of files on both the Windows and Mac OS. I would like to give the user the option of adding a new option to their right click/control click context menu to the effect of "Compress with [Name of App]". I know this is quite possible in Windows with modifications to the registry,...
Yes, you can. You need to make a contextual menu plugin. Apple has contextual menu plugin sample code on its developer site.
894,804
894,808
How to differentiate (when overloading) between prefix and postfix forms of operator++? (C++)
Because I've overloaded the operator++ for an iterator class template<typename T> typename list<T>::iterator& list<T>::iterator::operator++() { //stuff } But when I try to do list<int>::iterator IT; IT++; I get a warning about there being no postifx ++, using prefix form. How can I specifically overload the pref...
Write a version of the same operator overload, but give it a parameter of type int. You don't have to do anything with that parameter's value. If you're interested in some history of how this syntax was arrived out, there's a snippet of it here.
895,020
895,027
Why do I get an "Unreferenced Local Variable" warning? (C++)
When I do something like #include<iostream> int main() { int x; return 0; } I get a warning about x being an unreferenced local variable (I assume becuase I created a variable, then did not use it), why does this give me a warning though?
Probably because you're wasting memory for nothing. Besides, the code becomes dirty and harder to understand, not to mention that programmers don't usually define variables they don't need, so it's sort of a "is this really what you meant?" warning.
895,058
895,253
How does <iostream> work? (C++)
Just out of curiosity, how does iostream access the input-output system. (I have a bad habit of constantly reinventing the wheel, and I'm wondering if I can build a custom input-output system to the likes of iostream).
For a detailed guide to IOstreams, see the book Standard C++ IOStreams and Locales. After reading it I suspect you will be content to manage with with the status quo - IOStreams are probably the most complex part of the C++ standard library.
895,077
895,088
Dynamic source code in C++
How to process dynamic source code in C++? Is it possible to use something like eval("foo")? I have some functions that need to be called depending on user's choice: void function1 (); void function2 (); ... void functionN (); int main (int argv, char * argv []) { char * myString...
C++ is a compiled language, and thus, there is no equivalent to "eval()". For the specific example you mention, you could make a function registry that maps inputs (strings) to outputs (function pointers) and then call the resultant function. There are several C++ interpreter libraries that are available, although perf...
895,197
895,325
Uploading a file over HTTP/HTTPS and/or FTP/FTPS on a Mac
I have found numerous examples on uploading a file to a web server via C++ on Windows. However I am struggling after a lot of searching (and I thought I was good with Google!) to find any examples to help me achieve the same on a Mac. Can anyone point me towards some help on how to upload a file to a web server on a Ma...
connection Kit might be what your looking for
895,340
895,360
using accessors in same class
I have heard that in C++, using an accessor ( get...() ) in a member function of the same class where the accessor was defined is good programming practice? Is it true and should it be done? For example, is this preferred: void display() { cout << getData(); } over something like this: void display() { cout <<...
The reason for this is that if you change the implementation of getData(), you won't have to change the rest of the code that directly accesses data. And also, a smart compiler will inline it anyways (it would always know the implementation inside the class), so there is no performance penalty.
895,554
1,204,718
SpiderMonkey vs JavaScriptCore vs?
I have a C++ desktop application (written in wxWidgets) and I want to add support for some scripting language. Scripting would mostly be used for run-time conversions of strings, numbers and dates by user supplied JavaScript code. I'd like to use JavaScript because it is widely used and everyone is familiar with the sy...
There is also Google's V8 JavaScript engine, builds nicely on Linux, embedding API seems quite straightforward too: (Compared to SpiderMonkey's, never looked at the JavaScriptCore API) http://code.google.com/apis/v8/get_started.html
895,827
895,894
What is the difference between _tmain() and main() in C++?
If I run my C++ application with the following main() method everything is OK: int main(int argc, char *argv[]) { cout << "There are " << argc << " arguments:" << endl; // Loop through each argument and print its number and value for (int i=0; i<argc; i++) cout << i << " " << argv[i] << endl; retur...
_tmain does not exist in C++. main does. _tmain is a Microsoft extension. main is, according to the C++ standard, the program's entry point. It has one of these two signatures: int main(); int main(int argc, char* argv[]); Microsoft has added a wmain which replaces the second signature with this: int wmain(int argc, w...
896,103
896,148
Good methods for converting char array buffers to strings?
I am relatively new to C++. Recent assignments have required that I convert a multitude of char buffers (from structures/sockets, etc.) to strings. I have been using variations on the following but they seem awkward. Is there a better way to do this kind of thing? #include <iostream> #include <string> using std::st...
Given your input strings are not null terminated, you shouldn't use str... functions. You also can't use the popularly used std::string constructors. However, you can use this constructor: std::string str(buffer, buflen): it takes a char* and a length. (actually const char* and length) I would avoid the C string vers...
896,155
896,440
tr1::unordered_set union and intersection
How to do intersection and union for sets of the type tr1::unordered_set in c++? I can't find much reference about it. Any reference and code will be highly appreciated. Thank you very much. Update: I just guessed the tr1::unordered_set should provide the function for intersection, union, difference.. Since that's the ...
I see that set_intersection() et al. from the algorithm header won't work as they explicitly require their inputs to be sorted -- guess you ruled them out already. It occurs to me that the "naive" approach of iterating through hash A and looking up every element in hash B should actually give you near-optimal performan...
896,182
896,196
C++ Threading Question
I have an object Foo which has a global variable, Time currentTime Foo has two methods which are called from different threads. update() { currentTime = currentTime + timeDelay; } restart(Time newTime) { currentTime = newTime; } I am seeing behavior on a restart, the time changes correctly and other times whe...
You certainly have a race condition here. The most straitforward solution is to protect the use of the shared variable currentTime by using a lock. I am using the Boost.Threads mutex class here: class Foo { boost::mutex _access; update() { boost::mutex::scoped_lock lock(_access); currentTime = currentTime...
896,290
896,333
Recursively generate ordered substrings from an ordered sequence of chars?
Edited after getting answers Some excellent answers here. I like Josh's because it is so clever and uses C++. However I decided to accept Dave's answer because of it's simplicity and recursion. I tested them both and they both produced identical correct results (although in a different order). So thanks again everyone....
Following is a recursive algorithm to generate all subsequences. /* in C -- I hope it will be intelligible */ #include <stdio.h> static char input[] = "aaabbbccc"; static char output[sizeof input]; /* i is the current index in the input string * j is the current index in the output string */ static void printsubs(...
896,371
1,575,119
Use a "User Macro" in .vcproj RelativePath
Inside .vcproj files There is a list of all source files in your project. How can we use a macro to specify the path to a source file? If we do this: <File RelativePath="$(Lib3rdParty)\Qt\qtwinmigrate-2.5-commercial\src\qmfcapp.cpp"> </File> The compiler cannot find the folder: qmfcapp.cpp c1xx : fatal error C1083:...
Try setting an environment variable for 'Lib3rdParty' to the appropriate relative path snippet.
896,647
897,696
C++ struct member, what type to keep calendar time on iPhone?
I need to keep datetime in a C++ structure for an iPhone app. The time will be saved and restored into sqlite db. What is the best data type and corresponding API for this? My candidates are: time_t and struct tm from <ctime> and <time.h> NSTimeInterval from <NSDate.h> TimeValue from the QuickTime API My instinct is...
NSTimeInterval and its CoreFoundation counterpart CFAbsoluteTime are the best values to use, as they include sub-millisecond accuracy (they're double-precision floating-point values). time_t and struct tm are only really used in certain BSD APIs (and struct timeval or struct timespec are more common there). TimeValue i...
896,786
896,950
Most accurate line intersection ordinate computation with floats?
I'm computing the ordinate y of a point on a line at a given abscissa x. The line is defined by its two end points coordinates (x0,y0)(x1,y1). End points coordinates are floats and the computation must be done in float precision for use in GPU. The maths, and thus the naive implementation, are trivial. Let t = (x - x0...
To a large degree, your underlying problem is fundamental. When (x1-x0) is small, it means there are only a few bits in the mantissa of x1 and x0 which differ. And by extension, there are only a limted number of floats between x0 and x1. E.g. if only the lower 4 bits of the mantissa differ, there are at most 14 values ...
896,968
897,093
Decrease Qt GUI application size
I'm learning to develop apps using Qt Creator. I have built a simple app under Windows, depends on uses mingwm10.dll, QtCore4.dll, QtGui4.dll, QtNetwork4.dll. Out of QtQui4.dll I use only a a couple of widgets, and don't need all of the rest... Is it possible to either shrink the size of QtGui4.dll or do something else...
It's not possible to shrink the QtGui4.dll by removing some functions. Trolltech is having a look at this, but the good solution seems quite distant: Static linking, I think it is very problematic on windows. Each time I tried, it was a nightmare. So, it looks like you are stuck with the regular DLL. The only thing yo...
897,228
897,246
What is the best way to make a simple cross platform GUI in C++?
I want to produce a desktop application with a very simple GUI (a background graphic, a cancel button and a progress bar). My main targets are Mac and Windows. Is this possible using Visual C++ 2008? Can anyone point to any examples using Visual C++? Or is there a better way to create the GUI separately?
Use Qt4. http://qt-project.org/ This is a self containing framework which contains developers tools, GUI builders, String/IO/XML/Thread classes, Audio/Video controls, HTML widgets and many, many more features. It's built to be completely multi-platform, one code for all systems. In contrary to wxWidgets, it feels more ...
897,300
898,012
How to set amcap's default color space to YUY2?
AMcap is a app for capturing video or to preview from webcam. Its source code comes with Microsoft Windows SDK as sample. I want to (bypass the following process of user interaction in amcap code or say want to) set it as default: Ampcap menu Options Video Capture Pin ... Color Space/Compression: YUY2 ...
Hey @Dani van der Meer: Thanks for the Pointer ... I have done it by: In the function BOOL InitCapFilters() after if(hr != NOERROR) { hr = gcap.pBuilder->FindInterface(&PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video, gcap.pVCap, IID_IAMStreamCon...
897,321
897,326
How can I kill all processes of a program?
I wrote a program that forks some processes with fork(). I want to kill all child- and the mother process if there is an error. If I use exit(EXIT_FAILURE) only the child process is killed. I am thinking about a system("killall [program_name]") but there must be a better way... Thank you all! Lennart
Under UNIX, send SIGTERM, or SIGABRT, or SIGPIPE or sth. alike to the mother process. This signal will then be propagated to all clients automatically, if they do not explicitely block or ignore it. Use getppid() to get the PID to send the signal to, and kill() to send the signal. getppid() returns the process ID of ...
897,614
897,825
How do i know if a thread is suspended under Windows CE
Can I get a threads suspend count under Windows CE, using C or Visual C++, without calling resume or suspend functions? The only way I can see of doing it is something like int Count = SuspendThread(ThreadHandle); ResumeThread(ThreadHandle); This has a couple of problems, firstly, I'd rather not suspend the thread,...
I have a combined solution. Use WaitForSingleObject() to determine if the thread is suspended or not. If it's not suspended, the suspend count is obviously 0. If it's suspended, it's safe to call SuspendThread() to get the suspend count. Since it's already suspended you will not stall anything.
897,809
897,877
I can't build a library that needs WOW64 Api
I'm fixing a bug with Windows Vista 64 bits of a 32bit application, when I try to use the function Wow64DisableWow64FsRedirection(...) the compiler says 'undeclared identifier...'. I'm including the Windows.h header file and set _WIN32_WINNT to 0x0501. Any ideas? Thanks. EDIT: We're using MS Visual Studio 2003
Can you see this API in the header file? May be the Visual Studio you are using is not having updated header file, in which case you will need to do a LoadLibrary for Kernel32.dll and then GetProcAddress for the required function.
898,076
898,144
Solve Quadratic Equation in C++
I am trying to write a function in C++ that solves for X using the quadratic equation. This is what I have written initially, which seems to work as long as there are no complex numbers for an answer: float solution1 = (float)(-1.0 * b) + (sqrt((b * b) - (4 * a * c))); solution1 = solution1 / (2*a); cout << "Solution ...
Something like this would work: struct complex { double r,i; } struct pair<T> { T p1, p2; } pair<complex> GetResults(double a, double b, double c) { pair<complex> result={0}; if(a<0.000001) // ==0 { if(b>0.000001) // !=0 result.p1.r=result.p2.r=-c/b; else if(c>0.00001) throw exception("n...
898,273
898,306
Memory leak (sort of) with a static std::vector
I have a static std::vector in a class. When I use Microsoft's memory leak detection tools: _CrtMemState state; _CrtMemCheckpoint( & state); _CrtMemDumpAllObjectsSince( & state ); it reports a leak after I insert stuff into the vector. This makes sense to me because new space is allocated when something is inserted ...
You can swap the vector with an empty one - this will release the memory. See also Q: Shrinking a vector
898,387
898,425
Problem accessing static const variables through class member functions
I am having a problem accessing a static const variable defined in my class private member variable section. Specifically, the code written below can output the variable within the constructor, but when I try to access it through an accessor function, I get an error discussed below. If anyone knows why I would apprec...
Try initializing the variable outside the class definition, here is a working example: #include <iostream> class Foo { static const double _bar; public: Foo(); void Bar(); }; const double Foo::_bar = 20.0; Foo::Foo() { std::cout << Foo::_bar << std::endl; } void Foo::Bar() { std::cout << Foo::...
898,432
898,480
How is static variable initialization implemented by the compiler?
I'm curious about the underlying implementation of static variables within a function. If I declare a static variable of a fundamental type (char, int, double, etc.), and give it an initial value, I imagine that the compiler simply sets the value of that variable at the very beginning of the program before main() is ca...
In the compiler output I have seen, function local static variables are initialized exactly as you imagine. Note that in general this is not done in a thread-safe manner. So if you have functions with static locals like that that might be called from multiple threads, you should take this into account. Calling the func...
898,731
898,749
How can I find prime numbers through bit operations in C++?
How can I find prime numbers through bit operations in C++?
Try implementing a prime sieve using a bitset. The algorithm only needs to store whether a certain number is a prime or not. One bit is sufficient for that.
898,766
911,844
C++ Recursive File/Directory scanning using Cygwin
I'm looking to write a portable filesystem scanner, capable of listing all files on a given directory path recursively. To do this, I'm attempting to use cygwin for my compiler, making use of dirent.h and using the template: #include <dirent.h> #include <stdio.h> int main(void) { DIR *d; struct dirent ...
The culprit seems to be that the fd file links into /proc/ I do not guarantee it to be true, but I am under the impression that this enables the scanner to recursively loop through its own directory structure. My efforts with readlink() to address this issue were promising at first, but I'm finding that with deeper lev...
898,789
898,844
is there any specific case where pass-by-value is preferred over pass-by-const-reference in C++?
I read that they are conceptually equal. In practice, is there any occasion that foo(T t) is preferred over foo(const T& t) ? and why? Thanks for the answers so far, please note I am not asking the difference between by-ref and by-val. Actually I was interested in the difference between by-const-ref and by-val. ...
Built-in types and small objects (such as STL iterators) should normally be passed by value. This is partly to increase the compiler's opportunities for optimisation. It's surprisingly hard for the compiler to know if a reference parameter is aliasing another parameter or global - it may have to reread the state of the...
898,881
898,902
C++ - threads and multiple queues
I need to build a system of workers (represented as threads) and (multiple) queues. Individual jobs are waiting in one of the queues and waits for a worker thread to process them. Each worker can process jobs only from some of the queues. No spin-waiting. C/C++, pthreads, standard POSIX. The problem for me is the "mult...
What you can do is use a condition variable. Have your worker threads wait on a condition variable. When a job gets added to any of the job queues, signal the condition variable. Then, when the worker thread wakes up, it checks the queues it's waiting on. If any of them have a job, it takes that job off the queue. ...
898,967
899,457
Non-blocking connect() with WinSocks
According to MSDN you have to create a non-blocking socket like this: unsigned nonblocking = 1; ioctlsocket(s, FIONBIO, &nonblocking); and use it in the write-fdset for select() after that. To check if the connection was successful, you have to see if the socket is writeable. However, the MSDN-article does not describe...
You check socket error with getsockopt(). Here's a snippet from Stevens (granted it's Unix, but winsock should have something similar): if ( FD_ISSET( sockfd, &rset ) || FD_ISSET( sockfd, &wset )) { len = sizeof(error); if ( getsockopt( sockfd, SOL_SOCKET, SO_ERROR, &error, &len ) < 0 ) return -1; } el...
899,001
899,062
Combine two images with one being transparent
I have two bitmap images. One contains a picture taken with a usb camera. The other will contain a shape, like a rectagle, but it can also be a trapezoid, or lets say, a random shape with only one color in it. The rest of the image is white right now. The two images aren't of the same size but scaling algorithms aren't...
If you are using the full .NET platform, System.Drawing.Imaging has functions for alpha channels and masking: http://www.codeproject.com/KB/GDI-plus/alphafx.aspx
899,244
899,730
Is there an easy way to iterator over a static list of strings in C++
It often happens that I need to iterate over a list of strings in my C++ code. In languages like Perl, this is easy: foreach my $x ("abc", "xyz", "123") {.... } In the past, this is what I've done in C++ const char* strs[] = { "abc", "xyz", "123" }; for (int i=0; i<sizeof(strs)/sizeof(const char*); i++) { const cha...
Here is my attempt at it. Sadly it relies on variadic macros which is a C99/C++1x feature. But works in GCC. #include <boost/foreach.hpp> #include <boost/type_traits.hpp> #include <iostream> #define SEQ_FOR_EACH(D, ...) \ if(bool c = false) ; else ...
899,341
899,377
Print Coloured Text to Console in C++
I would like to write a Console class that can output coloured text to the console. So I can do something like (basically a wrapper for printf): Console::Print( "This is a non-coloured message\n" ); Console::Warning( "This is a YELLOW warning message\n" ); Console::Error( "This is a RED error message\n" ); How would I...
Check out this guide. I would make a custom manipulator so I could do something like: std::cout << "standard text" << setcolour(red) << "red text" << std::endl; Here's a small guide on how to implement your own manipulator. A quick code example: #include <iostream> #include <windows.h> #include <iomanip> using namesp...
899,517
899,525
Set local environment variables in C++
How do I set an environment variable in C++? They do not need to persist past program execution They only need to be visible in the current process Preference for platform independent but for my problem only needs to work on Win32/64 Thanks
NAME putenv - change or add an environment variable SYNOPSIS #include &ltstdlib.h> int putenv(char *string); DESCRIPTION The putenv() function adds or changes the value of environment variables. The argument string is of the form name=value. If name does not already e...
899,861
899,983
A good way to do a fast divide in C++?
Sometimes I see and have used the following variation for a fast divide in C++ with floating point numbers. // orig loop double y = 44100.0; for(int i=0; i<10000; ++i) { double z = x / y; } // alternative double y = 44100; double y_div = 1.0 / y; for(int i=0; i<10000; ++i) { double z = x * y_div; } But someone hinte...
On just about every CPU, a floating point divide is several times as expensive as a floating point multiply, so multiplying by the inverse of your divisor is a good optimization. The downside is that there is a possibility that you will lose a very small portion of accuracy on certain processors - eg, on modern x86 pr...
899,917
899,930
Why do people use enums in C++ as constants while they can use const?
Why do people use enums in C++ as constants when they can use const?
An enumeration implies a set of related constants, so the added information about the relationship must be useful in their model of the problem at hand.
900,123
903,081
COM, COM+, DCOM, where to start?
I am curious about COM+, DCOM. I know that MSFT does not encourage you to use this tools natively (meaning with C/C++, in fact there is not a lot of documentation available) but I want to learn to use these technologies, like embedding Internet Explorer into a C program. I thought that maybe I could find people that wo...
If you are serious about learning COM, Don Box's "Essential COM" is definitely an absolute "must read". COM can be confusing and in my humble opinion Don Box is one of the few people who actually "got it". The example code in "Essential COM" is in C++. You won't find many books that support COM in C. You can write COM ...
900,145
900,181
When learning new languages related readings, Distractions or Aids?
When learning new languages such as C++ from PHP, does reading other language snippets help you understand better by giving one a different prospective, or does doing so confuse a noob like me? Also, any advice on learning C++ would be great.
I find that reading short snippets helps a lot. A good book is really handy too. Once you understand most of the language itself, reading large, full-size programs helps a lot with learning how common problems are solved in that language. Most languages don't have a term for this, but it is like the "Pythonic" way in P...
900,230
900,243
Difference between long and int data types
Considering that the following statements return 4, what is the difference between the int and long types in C++? sizeof(int) sizeof(long)
From this reference: An int was originally intended to be the "natural" word size of the processor. Many modern processors can handle different word sizes with equal ease. Also, this bit: On many (but not all) C and C++ implementations, a long is larger than an int. Today's most popular desktop platfor...
900,240
900,281
C++ project source code layout
One of the popular way to organize project directory is more or less like this: MyLib +--mylib_class_a.h mylib_class_a.cpp mylib_library_private_helpers.h mylib_library_private_helpers.cpp MyApp +--other_class.h other_class.cpp app.cpp app.cpp: #include "other_class....
Well, it all depends on how big these projects are. If you've only got a few files, then whack them all in one folder. Too many folders when you haven't got many files to manage is in my opinion overkill. It gets annoying digging in and out of folders when you've only got a few files in them. Also, it depends on who's ...
900,262
900,284
Initializing pointers in C++
Can assign a pointer to a value on declaration? Something like this: int * p = &(1000)
Yes, you can initialize pointers to a value on declaration, however you can't do: int *p = &(1000); & is the address of operator and you can't apply that to a constant (although if you could, that would be interesting). Try using another variable: int foo = 1000; int *p = &foo; or type-casting: int *p = (int *)(1000...
900,278
900,539
import data from web stream in c++
i was wondering if is possible to import data from a live stream from a web site and perform computation on the data in real time? if this is possible what is the most efficient(computationally fast) way of doing it? thank you for any help or commpents.
you can use cURL. A curl handle can have a function called each time new data comes in.
900,319
900,576
Limit on cout stream?
A puzzle that hit me. In some simple test harness code, if I stream too many characters to stdout, the program fails. Strange but very reproducable. This may be a Windows only issue, but it's easy to see: #include <iostream> #include <deque> using namespace std; int main() { deque<char> d; char c; while (ci...
Thanks for all the suggestions, especially to Michael Burr who correctly theorized that the cat command, not reverse.exe, may be failing! That's exactly what it was.. reverse.exe < bigfile.txt works fine, but cat bigfile.txt | reverse.exe fails with "error writing stdout". Now why CAT would fail is also a mystery b...
900,326
900,414
how do I elegantly format string in C++ so that it is rounded to 6 decimal places and has extra '0's or '9's trimmed
How do I write a function that formats a string with decimals digits, without trailing 0's or unnecessary 9's? Given that decimals is 2, here's what I expect: 0.999 -> 1.0 0.99 -> 0.99 1.01 -> 1.01 1.001 -> 1.0 123 -> 123.0 0 -> 0.0 0.1 -> 0.1 (negatives as you'd expect) Here's what I have so far, but it's pretty ugl...
std::string toStrMaxDecimals(double value, int decimals) { std::ostringstream ss; ss << std::fixed << std::setprecision(decimals) << value; std::string s = ss.str(); if(decimals > 0 && s[s.find_last_not_of('0')] == '.') { s.erase(s.size() - decimals + 1); } return s; }
900,338
900,363
Why can't I use strerror?
I'm porting some code to Windows, and the Microsoft compiler (Visual C++ 8) is telling me that strerror() is unsafe. Putting aside the annoyance factor in all the safe string stuff from Microsoft, I can actually see that some of the deprecated functions are dangerous. But I can't understand what could be wrong with str...
strerror is deprecated because it's not thread-safe. strerror works on an internal static buffer, which may be overwritten by other, concurrent threads. You should use a secure variant called strerror_s. The secure variant requires that the buffer size be passed to the function in order to validate that the buffer is l...
900,361
900,530
When I created my helper classes, am I over designing?
I am a C++ programmer and recently joined a new company that uses a lot of C. When they reviewed my code, they were thinking I over-designed some of the things which I totally disagreed. The company is doing everything in embedded system, so my code needs to be memory efficient, but the stuff I am doing is not CPU inte...
You're probably right, but on the other hand if everyone in the company decided that they don't like the existing APIs, and each designed their own shims and helper functions, that only they used, then maintenance would be tricky. If your array wrapper is "over-designed", then I'd question whether the code reviewer con...
900,754
900,902
What are the good parts in the poorly-thought-of non-standard C++ libraries?
In trying to get up to speed with C++ (coming from a long experience with C), I am obviously trying to do the right thing, and use as much as is standard as is possible. However, in my readings on the matter I come accross a lot of criticism for standard things, and praise for non-standard things. For example, even the...
My personal grunge is with ACE. It was sort of the other way around - great idea, nothing else was available at the time for cross-platform threaded and network development in C++, wide deployment, books by the library authors, etc. But the implementation was terrible, usage patterns were complicated, almost all the us...
900,890
901,233
Is the maven-native-plugin widely used to build C++ projects using maven?
It's been a little while since I did C++ development professionally and I'd like to get caught up on what the current state of C++ development is in a number of areas. Most of my recent work has been Java, making heavy use of Maven. When I last did C++ development for work, some variant of make was widely accepted as...
In my experience, the C++ community still hasn't standardised on a common build tool. While the GNU autotools (and GNU make) are still popular for Open Source projects, other options include SCons, CMake, makepp and bjam/jam. Personally, I would only use Maven for a project that's mainly written in Java with a small JN...
901,114
901,128
Does the new C++ Standard provide new containers?
With C++ STL being updated, will there ever be a set number of containers. Edit: When it comes to containers, Will there be new addition to the library in addition vectors, lists etc..
The proposed C++ Standard (aka C++0x) adds the following templated containers: array (rather like a fixed size vector) forward_list (singly-linked list) unordered_map and unordered_multimap (hash table as dictionary) unordered_set and unordered_multiset (hash table as set)
901,216
901,234
why STL header files have no extension?
I got this basic doubt. The STL header doesn't have .h extension. #include <vector> #include <map> Is there is any specific reason behind this? Anybody knows history behind this, please share. EDIT: @GMan found Michael Burr's answer which addresses this question.
The #include directive doesn't discriminate file types (it's just a glorified copy-paste operation) - no automatic adding of .h is happening. C++ standard header files are provided without the .h extension Sometimes backward compatibility header files are provided by the vendor with the same name with the .h extension...
901,473
901,502
Read Unicode files C++
I have a simple question to ask. I have a UTF 16 text file to read wich starts with FFFE. What are the C++ tools to deal with this kind of file? I just want to read it, filter some lines, and display the result. It looks simple, but I just have experience in work with plain ascci files and I'm in the hurry. I'm using ...
You can use fgetws, which reads 16-bit characters. Your file is in little-endian,byte order. Since x86 machines are also little-endian you should be able to handle the file without much trouble. When you want to do output, use fwprintf. Also, I agree more information could be useful. For instance, you may be using ...
901,786
901,804
Order like a list but access by a key?
I used list to place cities into a trip. Then I iterate over the list to display the trip itinerary. I would like to access the cities by the name rather than by the trip order. So, I thought I could use a map rather than a list but the key determines the order. I would still like to control the order of the sequence b...
Often times you will need to compose multiple lists and maps. The common way is to store a pointer to the Cities in your by city lookup map from the pointers in your list. Or you can use a class like Boost.MultiIndex to do what you want in what I would say is much cleaner. It also scales much better and there is a lot...
901,848
901,853
Make a c++ iterator that traverses 2 containers
I have a need for a "container" that acts like the following. It has 2 subcontainers, called A and B, and I need to be able to iterate over just A, just B, and A and B combined. I don't want to use extra space for redundant data, so I thought of making my own iterator to iterate over A and B combined. What is the easie...
I will repost my answer to a similar question. I think this will do what you want. Use a library like Boost.MultiIndex to do what you want. It scales well and there is a lot less boiler plate code if you want to add new indexes. It is also usually more space and time efficient typedef multi_index_container< Container...
901,907
902,942
How to use typelists
I read about typelists in 'Modern C++ Design' and I understood it as some kind of union for types. By putting diffrent, non-related types in a typelist, one can use it to represent more than one type at once, without inheritance. I tested typelist in some simple functions with primitive types, but I couldn't get any of...
The typelists are generic compile-time collections of types. If you use dynamic_cast, you are missing the point, because it should not be needed, because it is a static, compile time concept. This works but I don't see the advantage over inheritance which is capable to do the same. You cannot make any existing type i...
902,062
902,069
What are some of the more obscure parts of C++?
I've read quite a few beginner's books on C++, and a little beyond that, but what are some of the more obscure aspects of C++, or where can I find information/tutorials on these?
Herb Sutter's books are an excellent source for this topic -- start with http://www.gotw.ca/publications/xc++.htm .
902,077
902,091
Advantage using an aggregate initialization list over a constructor?
I'm new to C++ and I have a question... I tried answering the question myself by making a test application... in debug, the class B initialization generates less assembly code, but in release mode, I can't really say... it optimizes the initializations away :( Let's say I have two classes: class A { public: int a,...
I don't know about performance advantages, but in general using the constructor is preferred. This is because with A, members a,b,c,d can be made private. Thus, you get encapsulation with your A approach, which you don't have in B. As a class designer, you can enforce strict usage and assignment of member variables via...
902,082
902,122
What is the reverse of cout.width? (C++)
I was trying std::cout.width(int) to see what it did, and it pushes the text right to fill a minimum width: TH becomes: TH to fill a minimum width of 10. I am wondering if A) there is a way to reverse this, have a number of spaces put AFTER the text to fill a minimum width, and B) is there a way to create a m...
Width sets the "column" size for what you are printing next with cout. std::cout << left << "Hello"; would print the above as "left" aligned in the column you made. Different "types" are aligned to certain sides by default. More info on this reference page.
902,095
902,111
c++ typedef another class's enum?
So here's my problem: struct A { enum A_enum { E0, E1, E2 }; }; struct B { typedef A::A_enum B_enum; bool test(B_enum val) { return (val == E1); // error: "E1" undeclared identifier } }; I specifically do not want to say A::E1. If I try B_enum::E1 I receive ...
I reckon that A should be a namespace instead of a struct.
902,261
902,269
Is there a decent wait function in C++?
One of the first things I learned in C++ was that #include <iostream> int main() { std::cout<<"Hello, World!\n"; return 0; } would simply appear and disappear extremely quickly without pause. To prevent this, I had to go to notepad, and save helloworld.exe pause ase helloworld.bat This got tedious when I nee...
you can require the user to hit enter before closing the program... something like this works. #include <iostream> int main() { std::cout << "Hello, World\n"; std::cin.ignore(); return 0; } The cin reads in user input, and the .ignore() function of cin tells the program to just ignore the input. The program wil...
902,309
902,319
Why does this program display seemingly random characters? (C++)
Well, not random, because its the same every time, but #include<iostream> using namespace std; int main() { char box[10][10]; for(int i=-1;i<11;i++) { cout<<"---------------------"<<endl<<"|"; for(int j=0;j<10;j++) { cout<<box[j][i]<<"|"; } cout<<endl; ...
Your loop over i doesn't make sense... for(int i=-1;i<11;i++) This will hit two indices that aren't valid, -1 and 10, when you reference box here: cout<<box[j][i]<<"|"; It should be 0 to < 10 like the other loop. Also you haven't initialized the contents of box to anything, so you're printing uninitialized memory. Y...