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 object remaining, therefore something like:
while( pointer->Release() > 0 );
Would obviously release all references to that pointer?
Or am I not seeing something?
*note I'm talking about this from the concept of the IDirect3DTexture9::Release() function
|
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 the object will be destructed. It's dangerous as others might still hold a reference to it that will become invalid after object's destruction.
Thus, you should only call Release for each AddRef you had previously called.
|
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 versatile as possible.
|
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 to link your libraries.
From the mpc homepage:
supports multiple versions of make (GNU, Microsoft, Borland, Automake), Visual C++ 6.0 and Visual Studio 2003, 2005 and 2008.
|
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 data structure.
|
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 bloated. On the other hand it is quite easy to understand and modify, Depends on boost-1.35.
Advantages
Depends only on boost
Written in C++, looks like less dangerous
Licensed under MIT.
Disadvantages
Slow (it is still about 10 times faster then Perl implementation, but about 10 times slower than Discount)
Discount, This is the code I use for my blog http://art-blog.no-ip.info/cppcms/blog and wiki http://art-blog.no-ip.info/wikipp/en/page/main. It is written by hardcore C programmer and quite hardly mantainable (even the developer activly maintains it).
Advantages
Extremely fast
Written in pure C (no 3rd part dependencies).
Actively maintained
Has permissive 3 clause BSD license
Disadvantages
Almost impossible to maintain (even I could remove/add some fatures).
Has only FILE API, so I should tweak the code to make it work with general buffer.
Licensed under 4 clause BSD license that is incompatible with GPL. It is problematic if you want to use it not as part of your GPL-ed software.
Why do I know them so much?
I'm developing CppCMS, so I need a good markdown to HTML convertor. When I picked one (Discount), it was the only solution. Since then I've needed to replace it due to licensing issues. That said, I still quite like it because it is the fastest Markdown solution.
P.S.: If you want C++ wrapper for Discount, take a look on http://cppcms.svn.sourceforge.net/viewvc/cppcms/cms/trunk/cxxmarkdown/, It is not the latest version, but it is already tweaked.
EDIT: I have just visited Discount site and I had found that it had added a non-FILE API as well. So now it is real library.
EDIT 2: If you find better implementation or write your own under FOSS license, let me know ;)
EDIT 3: as cloose commented, discount had changed the license to 3 clause BSD.
|
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 whether something is a object or function declaration, the compiler sometimes has to scan the whole declaration. Any construct within the declaration that could possibly form a declaration is taken to be a declaration. If not, then any such construct is taken to be an expression. GCC apparently thinks because nonsense is no valid type, it can't be a valid parameter declaration, and thus falls back treating the whole declaration as a field (note that it says in addition error: expected ';' before '(' token ) . Same thing in local scope
int main() {
int a;
// "nonsense * a" not treated as declaration
void f(nonsense*a);
}
=> error: variable or field 'f' declared void
int main() {
// "nonsense * a" treated as parameter declaration
typedef int nonsense;
void f(nonsense*a);
}
=> (compiles successfully)
|
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 unexpected result is returned, but how to know that through the code ? How to know i've reached the max key ?).
Thanks !
|
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
and in there he makes the case that in a large site such as Wikipedia, the database servers only make up 10% of all servers. Therefore C++ would be better than languages like PHP Python Ruby C#.
Are his points valid?
|
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 the bottleneck" is the same thing that's been learned by everyone who ever does run-time profiling of a web application.
Consider an application which takes half a second to return a full response. Suppose you sit down and profile it, and find that that half second of processing time breaks down as follows:
Parsing incoming request: 50ms
Querying database: 350ms
Rendering HTML for response: 50ms
Sending response back out: 50ms
If you saw a breakdown like that, where database queries constitute 70% of the actual running time of the application, you'd rightly conclude that the database is the bottleneck. And that's exactly what most people find when they do profile their applications (and, generally, the database so completely dominates the processing time that the choice of language for the rest of the processing doesn't make any difference anyone will notice).
The number of database servers involved turns out not to matter too much; the famous quote here is that people like the author of the post you've linked are the types who hear that it takes one woman nine months to have a baby, and assume that nine women working together could do it in one month. In database terms: if a given query takes 100ms to execute on a given DB, then adding more DB servers isn't going to make any one of them be able to execute that query any faster. The reason for adding more database servers is to be able to handle more concurrent requests and keep your DB from getting overloaded, not to make isolated requests go any faster.
And from there you go into the usual dance of scaling an application: caching to cut down on the total time spent retrieving data or rendering responses, load-balancing to increase the number of concurrent requests you can serve, sharding and more advanced database-design schemes to keep from bogging down under load, etc., etc.
But, you'll note, none of this has anything whatsoever to do with the programming language in use because, once again, the amount of time spent or saved by other factors grossly outweighs the amount of time gained or lost by a "fast" or a "slow" language (and, of course, there's really no such thing; so much depends on the problem domain and the skill of the programmer that you just can't have a meaningful general comparison).
Anyway, this is getting kind of long and rambling, so I'll just wrap it up with a general guideline: if you see someone arguing that "you should build in Language X because it runs faster", it's a dead giveaway that they don't really know anything about real-world performance or scaling. Because, after all, if it just came down to "write in the fastest language", they'd be recommending that we all use assembly :)
|
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'
cout << stringArray[2]; // ' th'
cout << stringArray[3]; // 'e str'
cout << stringArray[4]; // 'ing we'
cout << stringArray[5]; // ' will use'
I can tokenize the string just fine, but the hardest part for me is how can i specify the number of elements in stringArray before assigning it the current string toke and also how to return stringArray from the function.
Would someone show me how to write the function?
Edit1: I don't necessarily need the results to been in string array just any container that i can call as a regular variable with some sort of indexing.
|
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 character
if (*it == ch) {
// If we have some characters accumulated
if (!next.empty()) {
// Add them to the result vector
result.push_back(next);
next.clear();
}
} else {
// Accumulate the next character into the sequence
next += *it;
}
}
if (!next.empty())
result.push_back(next);
return result;
}
Hopefully this gives you some sort of idea of how to go about this. On your example string it returns the correct results with this test code:
int main (int, char const **) {
std::string blah = "___this_ is__ th_e str__ing we__ will use__";
std::vector<std::string> result = explode(blah, '_');
for (size_t i = 0; i < result.size(); i++) {
cout << "\"" << result[i] << "\"" << endl;
}
return 0;
}
|
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 University...
I've written millions of lines of C# thousands of lines of Java and a few hundred lines of C...
But I don't know C++, I feel a little like I've cheated the profession by not knowing a what I think is a key language. I've written Code in C++ files, mainly for bug fixes, but it was really just C in disguise.
What is the best way to go about learning C++, if you are more used to the nice abstractions that higher level languages give you to get away from the nitty grittyness of C++.
Has anyone on SO gone from being an experienced Java, C# (or some other language) developor to a C++ programmer? if so how did you do it, was it difficult and do you have any pointers?
|
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 to be able to do this. How can I achieve this sort?
|
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() {
ifstream inFile;
int result;
string filename;
cout << "If the executable is not in the same directory as the\nfile, then a directory needs to be provided\n\n";
while (true) {
cout << "Enter the file name: ";
getline(cin, filename);
inFile.open(filename.c_str(), ios::in);
if (!inFile)
cout << "\n**File failed to open**\n\n";
else break;
}
result = countLOC(inFile);
cout << "\nThere are " << result << " lines of code in \"" << filename << "\"\n\n";
inFile.close();
return 0;
}
|
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, current is a pointer to a node class, and the node class contains the data member data of type T.
Iterator is declared like this:
template<class T>
class list
{
public:
class iterator;
};
template<class T>
class list<T>::iterator
{
//stuff
};
I am able to compile the function definition of the overloaded operator* fine, but when I try to do something like:
list<int> lst1;
lst1.add(6);
list<int>::iterator IT;
IT = lst1;
//everything above this point compiles fine
int a = *IT; //error here (line fourteen)
The error I get says <1> that I am using an illegal indirection, and <2> that it cannot convert from list::iterator to int. Both errors occur on line fourteen.
Does anybody know what I am doing wrong and how I can overload the indirection operator correctly?
NB: If you need to see more code, tell me which part, because I don't want to put th entire code up here because it's abot 205 lines, and 204 of those lines don't (I think) have any errors.
|
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>::iterator::operator*()
{
return ((this->lstptr)->current)->data;
}
|
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 could us
vector<string> tokens;
boost::split(tokens, str, boost::is_any_of(delimiters));
// gives the wrong result: tokens = {"string", " with", " comma", " delimited", " tokens", "\"and delimiters", " inside a quote\""}
Which would be nice and concise... however it doesn't seem to work with quotes and instead I have to do something like the following
string delimiters = ",";
string str = "string, with, comma, delimited, tokens, \"and delimiters, inside a quote\"";
vector<string> tokens;
escaped_list_separator<char> separator("\\",delimiters, "\"");
typedef tokenizer<escaped_list_separator<char> > Tokeniser;
Tokeniser t(str, separator);
for (Tokeniser::iterator it = t.begin(); it != t.end(); ++it)
tokens.push_back(*it);
// gives the correct result: tokens = {"string", " with", " comma", " delimited", " tokens", "\"and delimiters, inside a quote\""}
My question is can split or another standard algorithm be used when you have quoted delimiters? Thanks to purpledog but I already have a non-deprecated way of achieving the desired outcome, I just think that it's quite cumbersome and unless I could replace it with a simpler more elegant solution I wouldn't use it in general without first wrapping it in yet another method.
EDIT: Updated code to show results and clarify question.
|
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);
which is only marginally more verbose than the original snippet
vector<string> tokens;
boost::split(tokens, str, boost::is_any_of(","));
|
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;
};
class A
{
public:
A()
{
_b = new B(121);
}
boost::shared_ptr<B> _b;
};
class C
{
public:
C()
{
}
void setRef( boost::shared_ptr<B> b)
{
_b = b;
}
boost::shared_ptr<B> _b;
};
int main()
{
C c;
{
A *a = new A();
cout << "a._b.use_count: " << a->_b.use_count() << endl;
c.setRef(a->_b);
cout << "a._b.use_count: " << a->_b.use_count() << endl;
delete a;
}
cout << c._b->_val << endl;
}
|
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 at the end of its block, then the reference count of the B-object drops to 1 again since only c's shared_ptr is referencing it now.
After c is destroyed at the end of main, its shared_ptr will be destroyed too as part of c's destruction, and now as the reference count drops to zero, the pointed-to B object will be deleted by shared_ptr.
So, the reference counts of the B-object:
0: before existence of a.
1: from start of lifetime of a until c.setRef
2: from c.setRef until copy of its parameter
3: from copy of c.setRef''s parameter until return of it
2: from return of c.setRef until end of a''s block
1: from end of a''s block until end of main
0: after main returned (object doesn''t exist anymore now)
|
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 throws this error:
error: request for member ‘push_front’ in ‘complexList’, which is of non-class type ‘std::list<complexNode, std::allocator<complexNode> > ()()’
The class complexNode has a copy contructor.
I really don't understand the problem and what that error actually means... please help!
|
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<10;i++)
{
for(j=0;j<10;j++)
std::cin>>array[j][i];
}
I'm pretty sure the answer has to do with how arrays are implemented on a hardware level; that the [ ][ ] syntax is just a programmer's abstraction to aid visualisation/modelling. However, I forgot which of the above code accesses the memory block sequentially from start till end...
Thanks for all the answers...
Just to confirm my understanding, does this mean the first code is equivalent to
int array[10][10], k;
for(k=0;k<100;k++)
{
std::cin>>*(array+k);
}
|
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 sequentially A[0], A[1], A[2] ..
|
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 there a way to include the data in the *.obj files in the *.lib? Maybe a switch in the compiler?
This is my config for the static library:
C/C++
/Od /GT /D "WIN32" /D "NDEBUG" /D "_LIB" /D "_WINDOWS" /D "_UNICODE" /D "UNICODE" /Gm /EHsc /MD /Yu"stdafx.hpp" /Fp"e:\Development\Projects\nsGameLib\Source\Core\Intermediate\nsglCore-Win32-Release.pch" /Fo"e:\Development\Projects\nsGameLib\Source\Core\Intermediate\\" /Fd"e:\Development\Projects\nsGameLib\Source\Core\Intermediate\vc90-Release.pdb" /W3 /nologo /c /Zi /TP /errorReport:prompt
Librarian
/OUT:"e:\Development\Projects\nsGameLib\Source\Core\Output\nsglCore-Win32-Release.lib" /NOLOGO /LTCG
This is my config for the project using the static library:
C/C++
/O2 /Oi /I "E:\Development\Projects\nsGameLib\Samples\\DummyEngine\\" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_UNICODE" /D "UNICODE" /FD /EHsc /MD /Gy /Fo"e:\Development\Projects\nsGameLib\Samples\OnlyCore\Intermediate\\" /Fd"e:\Development\Projects\nsGameLib\Samples\OnlyCore\Intermediate\vc90-Release.pdb" /W3 /nologo /c /Zi /TP /errorReport:prompt
Linker
/OUT:"e:\Development\Projects\nsGameLib\Samples\OnlyCore\Output\SampleOnlyCore-Win32-Release.exe" /INCREMENTAL:NO /NOLOGO /LIBPATH:"E:\Development\Projects\nsGameLib\Samples\..\Deployment\Libraries" /MANIFEST /MANIFESTFILE:"e:\Development\Projects\nsGameLib\Samples\OnlyCore\Intermediate\SampleOnlyCore-Win32-Release.exe.intermediate.manifest" /MANIFESTUAC:"level='asInvoker' uiAccess='false'" /DEBUG /PDB:"e:\Development\Projects\nsGameLib\Samples\OnlyCore\Intermediate\SampleOnlyCore-Win32-Release.pdb" /SUBSYSTEM:WINDOWS /OPT:REF /OPT:ICF /LTCG /DYNAMICBASE /NXCOMPAT /MACHINE:X86 /ERRORREPORT:PROMPT nsglCore kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib
|
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>
iterator& list<T>::iterator::operator++()
{
(this->lstptr)->current = ((this->lstptr)->current)->next;
return this;
}
I get these errors:
s:\jeffrey_\my_freeware_games\o\resources\container class\container(spec- o)\container_def.h(213) : error C2143: syntax error : missing ';' before '&'
s:\jeffrey_\my_freeware_games\o\resources\container class\container(spec- o)\container_def.h(213) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
s:\jeffrey_\my_freeware_games\o\resources\container class\container(spec- o)\container_def.h(213) : error C2065: 'T' : undeclared identifier
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(235) : error C2039: 'Yes' : is not a member of 'vc_attributes'
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(235) : error C2065: 'Yes' : undeclared identifier
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(236) : error C2039: 'No' : is not a member of 'vc_attributes'
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(236) : error C2065: 'No' : undeclared identifier
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(237) : error C2039: 'Maybe' : is not a member of 'vc_attributes'
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(237) : error C2065: 'Maybe' : undeclared identifier
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(240) : error C2039: 'NoAccess' : is not a member of 'vc_attributes'
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(240) : error C2065: 'NoAccess' : undeclared identifier
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(241) : error C2039: 'Read' : is not a member of 'vc_attributes'
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(241) : error C2065: 'Read' : undeclared identifier
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(242) : error C2039: 'Write' : is not a member of 'vc_attributes'
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(242) : error C2065: 'Write' : undeclared identifier
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(243) : error C2039: 'ReadWrite' : is not a member of 'vc_attributes'
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(243) : error C2065: 'ReadWrite' : undeclared identifier
c:\program files\microsoft visual studio 9.0\vc\include\crtdefs.h(582) : error C2146: syntax error : missing ';' before identifier 'time_t'
c:\program files\microsoft visual studio 9.0\vc\include\crtdefs.h(2047) : error C2143: syntax error : missing ';' before 'identifier'
c:\program files\microsoft visual studio 9.0\vc\include\crtdefs.h(2047) : warning C4091: 'typedef ' : ignored on left of 'localeinfo_struct' when no variable is declared
c:\program files\microsoft visual studio 9.0\vc\include\crtdefs.h(2047) : fatal error C1075: end of file found before the left brace '{' at 'c:\program files\microsoft visual studio 9.0\vc\include\crtdefs.h(174)' was matched
NB: container_def.h is the header file for my list and iterator classes, I have no idea what souceannotations or crtdefs are.
|
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 required, since list<T>::iterator is a type prefixed with a template specialization, and you need to tell the compiler about that - in spite of the fact that Visual C++ probably will accept code not putting typename before it. Omitting the typename, the compiler should assume it's not a type and should sort of produce the same error message.
You could safe yourself that hassle by putting the code straight into the class:
template<class T>
class list<T>::iterator
{
public:
iterator& operator++() {
(this->lstptr)->current = ((this->lstptr)->current)->next;
return *this; // *this here, since this is a pointer only
}
protected:
list* lstptr;
};
|
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 << "Hello world!" << std::endl;
Because, of course, < is the html entity for <.
Finally, something somewhere decided to change the ampersands to percent signs, possibly as part of a url-encoding scheme.
|
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
return snprintf( str, format);
#endif
}
These function are in a String class which is a separate project and is compiled as a lib. I use it in another program. Now if I use the mysprintf()
msprintf(str,10, _M("%d,%d"),height,width);
I get some garbage values in the string buffer. But if I directly call the swprintf function from the program it works fines. I have defined UNICODE in the build and the function swprintf does get called, but it fills some garbage values. I dont understand what is going wrong.
Thanks
Amit
|
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_t size, const MCHAR* format, ... )
{
va_list args;
va_start(args, format);
int result;
#ifdef MYUNICODE
result = vswprintf( str, size, format, args);
#else
result = ..
#endif
va_end(args);
return result;
}
Cheers !
|
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; larger, after your pivot. (This step will move your pivot. Keep track of its position in your array.)
You now know that your pivot is larger than pivot_position number of elements. Therefore, your pivot is the (pivot_position + 1)th smallest element.
If k is equal to pivot_position + 1, then you've found your kth smallest value. Congratulations, return pivot_position as the position of that value in the array.
If k is less than pivot_position + 1, you want some value that's smaller than your pivot. Look in the part of the array before your pivot for the kth smallest value.
If k is greater than pivot_position + 1, you want some value that's larger than your pivot. Look in the part of the array after your pivot for the *k - (pivot_position + 1)*th smallest value (since that part of the array excludes the (pivot_position + 1) smallest values).
Since you're using C++, you should probably implement your functions as follows:
int select(int *array, int left, int right, int k);
int partition(int *array, int left, int right, int pivot_position);
select takes your array, left and right bounds, and your k. To clarify, array[left] will be the first element; array[right] will be the last; right - left + 1 will be the length of the array. select returns the position of the kth smallest element.
partition takes your array, left and right bounds, and the starting position of your pivot. It's safe to just pass 0 for pivot_position every time, meaning that you want to use the first element in the array as the pivot. (In a variation called randomized quickselect, you pick a random pivot_position.) partition returns the position of the pivot after you're done moving things around.
|
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;j++)
{
c = a.back();
a.pop_back();
delete c;
printf(" %d \n\r",j);
c = NULL;
}
}
The printf in there is since I have a talking destructor to see in which Chromosome the segmentation fault happens. When clearPool() is called and say we got a size of 100, it can give a segmentation fault in any Chromosome between 0 and 100.
I have no idea why this might be happening nor do I have a way to actually find what's wrong since while debugging with breakpoints all I see is that it happens in there at random chromosomes.
I am using codeblocks IDE and the gdb debugger. The stack trace when the segmentation fault happens has 4 memory addresses and a function wsncpy().
|
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 pointers in the copy, the pointers in the original are now all invalid - I suspect you are using those invalid pointers in some way not shown in the code you posted.
As a couple of template solutions have been posted that use C++ library algorithms, you might also want to consider a template solution that does not:
template <class C> void FreeClear( C & cntr ) {
for ( typename C::iterator it = cntr.begin();
it != cntr.end(); ++it ) {
delete * it;
}
cntr.clear();
}
Using this you can free any container of dynamically allocated objects:
vector <Chromosome *> vc;
list <Chromosome *> lc;
// populate & use
FreeClear( lc );
FreeClear( vc );
|
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 experience and lack of screen realestate.
Decide on whether you want to go 13" / 15" / 17" and do a pro's & con's list of portability Vs. dev experience.
After that, max the machine out in terms of RAM/CPU/HD Speed to the whatever your budget can afford.
Edit
Just to re-iterate some other good comments made.
If an SSD is an option for storage, go for it, though these tend to be quite expensive add ons.
4Gb of RAM should be the standard.
And for comparison, dell categorises it's laptops in terms of weight/portability as:
Less than 2.2 Kg (Light)
Between 2.2 - 2.8 Kg (Medium)
More than 2.8 Kg (Heavy)
|
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:
doA();
break;
case 2:
doB();
break;
case 5:
Foo();
break;
}
}
};
Now, based on the derived class, I want to 'add' more case statements to the switch. What are my options here? I can declare virtual functions and only define them in the derived classes that are going to use them:
class Basic {
protected:
virtual void DoSomethingElse();
public:
Run() {
int input = something->getsomething();
switch(input)
{
/* Basic functionality */
...
case 6:
DoSomethingElse();
}
}
};
class Derived : public Basic {
protected:
void DoSomethingElse() { ... }
}
But this would mean when changing functions in any derived class, I would have to edit my base class to reflect those changes.
Is there a design pattern specifically for this kind of issue? I purchased a number of books on Design Patterns but I'm studying them on "by-need" basis, so I have no idea if there is such a pattern that I am looking for.
|
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 care over default copy and assignments which is fair enough, but default copy and assignment is also bad with pointers, so there's little advantage there.
I always try to use references where I can since naked pointers introduce uncertaintly about who is responsible for deleting that pointer. I prefer to embed objects by value but if I need a pointer, I use auto_ptr in the member data of the class that owns the pointer, and pass the object around as a reference.
I would generally only use a pointer in member data when the pointer could be null or could change. Are there any other reasons to prefer pointers over references for data members?
Is it true to say that an object containing a reference should not be assignable, since a reference should not be changed once initialised?
|
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 initialiser list: there's no way to factor out this initialisation into another function (until C++0x, anyway edit: C++ now has delegating constructors)
the reference cannot be rebound or be null. This can be an advantage, but if the code ever needs changing to allow rebinding or for the member to be null, all uses of the member need to change
unlike pointer members, references can't easily be replaced by smart pointers or iterators as refactoring might require
Whenever a reference is used it looks like value type (. operator etc), but behaves like a pointer (can dangle) - so e.g. Google Style Guide discourages it
|
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" //modified
gettnig error:
1>.\amcap.cpp(3887) : error C2440: '='
: cannot convert from 'WCHAR' to
'WCHAR [260]'
What can I do to correct this?
|
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 boils down to
1) How do each of the above store characters as bytes
2) What are the differences between the above standards
3) What is a code page
4) Method of converting characters between the various types.
Many many thanks :)
|
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 to do this, using c++ and win32?
|
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 results you get aren't most likely what you're looking for.
|
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; // day
uint8_t iso_hour; // hour
uint8_t iso_minute; // minute
uint8_t iso_second; // second
uint8_t iso_centi; // centi-second
uint8_t iso_hundred; // hundreds of micro-seconds
uint8_t iso_micro; // micro-seconds
uint32_t iso_unused; // pad out to 16 bytes
} ISOTIME;
I'm trying to figure out what standard that this is supposed to be implementing. Anyone have a clue? My Google-fu is failing me.
|
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 unlikely.
|
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() {
std::cout << "Derived::Derived()" << std::endl;
}
~Derived() {
std::cout << "Derived::~Derived()" << std::endl;
}
};
int main() {
Base a = Derived();
return EXIT_SUCCESS;
}
Here is a sample of the output when the program is run:
Base::Base()
Derived::Derived()
Derived::~Derived()
Base::~Base()
Base::~Base()
|
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 (and its base-class sub-object of type Base) only exists for the time of initialization, while the remaining Base object exists until end of main.
Since there are two Base objects and one Derived object, you will also see one more Base destructors run.
|
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 client application then reads the first four bytes, sets a buffer to the appropriate size and then reads the rest. The problem that I'm having is that the first time through the message will be sent perfectly. Every other time after that there is extra data being sent so a message like "what a nice day out" would come out like "what a nice day out??X??". So I feel like a buffer is not being cleared correctly but I can't seem to find it.
Client code:
listen(sock, 5);
for (;;)
{
msgsock = accept(sock, 0, 0);
if (msgsock == -1)
perror("accept");
else do
{
char buf[4];
bzero(buf, sizeof(buf));
if ((rval = read(msgsock, buf, 4)) < 0)
perror("reading stream message");
printf("--!%s\n", buf);
string temp = buf;
int pos = temp.find("^");
if(pos != string::npos)
{
temp = temp.substr(0, pos);
}
int sizeOfString = atoi(temp.c_str());
cout << "TEMP STRING: " << temp << endl;
cout << "LENGTH " << sizeOfString << endl;
char feedWord[sizeOfString];
bzero(feedWord, sizeof(feedWord));
if ((rval = read(msgsock, feedWord, sizeOfString)) < 0)
perror("reading stream message");
else if (rval == 0)
printf("Ending connection\n");
else
printf("-->%s\n", feedWord);
bzero(feedWord, sizeof(feedWord));
sizeOfString = 0;
temp.clear();
}
while (rval > 0);
close(msgsock);
}
close(sock);
unlink(NAME);
Server Code
pthread_mutex_lock(&mylock);
string s;
s.clear();
s = dataQueue.front();
dataQueue.pop();
pthread_mutex_unlock(&mylock);
int sizeOfString = strlen(s.c_str());
char sizeofStringBuffer[10];
sprintf(sizeofStringBuffer, "%i", sizeOfString);
string actualString = sizeofStringBuffer;
int tempSize = strlen(sizeofStringBuffer);
int remainder = 4 - tempSize;
int x;
for(x =0; x < remainder; x++)
{
actualString = actualString + "^";
}
cout << "LENGTH OF ACTUAL STRING: " << sizeOfString << endl;
actualString = actualString + s;
cout << "************************" << actualString << endl;
int length = strlen(actualString.c_str());
char finalString[length];
bzero(finalString, sizeof(finalString));
strcpy(finalString, actualString.c_str());
if (write(sock, finalString, length) < 0)
perror("writing on stream socket");
|
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 current code, and it doesn't match your description of the protocol.
Ideally - split your sending routine into a function of its own. You can also take advantage of writev() to handle coalescing the string holding the "length" field with the buffer holding the actual data and then sending them as a single atomic write().
Untested code follows:
int write_message(int s, std::string msg)
{
struct iovec iov[2];
char hdr[5];
char *cmsg = msg.c_str();
int len = msg.length();
snprintf(hdr, 5, "%04d", len); // nb: assumes len <= 9999;
iov[0].iov_base = hdr;
iov[0].iov_len = 4;
iov[1].iov_base = cmsg;
iov[1].iov_len = len;
return writev(s, iov, 2);
}
|
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 wondering really =)
|
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 same class yes yes yes
members of derived classes yes yes no
not members yes no no
|
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 can only access public member variables.
There is no "best way" -- these are the rules presented in a reasonable fashion.
|
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 is an obsolete PRNG, and I'm trying to understand how one inverts such a function).
Updated
If A is relatively prime to (2^N)-1, then g(A,Y) is just f(A-1, y).
If A isn't relatively prime, then the range of y is constrained...
Does g( ) still exist if restricted to that range?
|
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 create an inverse function using the Extended Euclidean Algorithm where
g(A,y) = F(A^-1, y),
otherwise you're out of luck.
UPDATE: In response to your updated question, you still can't get a unique inverse in the restricted range. Even if you use CookieOfFortune's brute force solution, you'll have problems like
G(12345, F(12345, 4294967294)) == 286331152 != 4294967294.
|
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://sourceware.org/binutils/docs/ld/Options.html#Options
|
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, but is there a way to achieve this for the Mac? Perhaps using C++ or objective C?
|
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 prefix/postifx forms?
|
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 = new char [100];
...
myString = "1" //user input
cout << eval("function"+myString)();
}
How is it usually done?
UPD: Based on slacy's and clinisbut's answers I think I need to make a function registry. I suppose it should be made as an array of pointers to functions. Here's the question, how do I declare an array of pointers to functions?
|
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 performance will be very poor, they may accomplish what you want. Google search for "C++ interpreter". I've seen results for "Ch", "CINT" and "clipp"
|
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 Mac OS using either C++ or objective C?
It can be via either HTTP/HTTPS or FTP/FTPS (or both).
Thanks!
|
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 << data;
}
data is a data member of the same class where the accessor was defined... same with the display() method.
I'm thinking of the overhead for doing that especially if you need to invoke the accessor lots of times inside the same class rather than just using the data member directly.
|
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 syntax.
Googling around, it seems I have two options:
SpiderMonkey from Mozilla
JavaScriptCore from WebKit
Has anyone tried those? Which one would be easier to set up?
Do you know of some other implementation that is better for my needs?
BTW, I target Windows and Linux platforms.
|
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;
return 0;
}
I get what I expect and my arguments are printed out.
However, if I use _tmain:
int _tmain(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;
return 0;
}
It just displays the first character of each argument.
What is the difference causing this?
|
_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, wchar_t* argv[]);
And then, to make it easier to switch between Unicode (UTF-16) and their multibyte character set, they've defined _tmain which, if Unicode is enabled, is compiled as wmain, and otherwise as main.
As for the second part of your question, the first part of the puzzle is that your main function is wrong. wmain should take a wchar_t argument, not char. Since the compiler doesn't enforce this for the main function, you get a program where an array of wchar_t strings are passed to the main function, which interprets them as char strings.
Now, in UTF-16, the character set used by Windows when Unicode is enabled, all the ASCII characters are represented as the pair of bytes \0 followed by the ASCII value.
And since the x86 CPU is little-endian, the order of these bytes are swapped, so that the ASCII value comes first, then followed by a null byte.
And in a char string, how is the string usually terminated? Yep, by a null byte. So your program sees a bunch of strings, each one byte long.
In general, you have three options when doing Windows programming:
Explicitly use Unicode (call wmain, and for every Windows API function which takes char-related arguments, call the -W version of the function. Instead of CreateWindow, call CreateWindowW). And instead of using char use wchar_t, and so on
Explicitly disable Unicode. Call main, and CreateWindowA, and use char for strings.
Allow both. (call _tmain, and CreateWindow, which resolve to main/_tmain and CreateWindowA/CreateWindowW), and use TCHAR instead of char/wchar_t.
The same applies to the string types defined by windows.h:
LPCTSTR resolves to either LPCSTR or LPCWSTR, and for every other type that includes char or wchar_t, a -T- version always exists which can be used instead.
Note that all of this is Microsoft specific. TCHAR is not a standard C++ type, it is a macro defined in windows.h. wmain and _tmain are also defined by Microsoft only.
|
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::string;
using std::cout;
using std::endl;
char* bufferToCString(char *buff, int buffSize, char *str)
{
memset(str, '\0', buffSize + 1);
return(strncpy(str, buff, buffSize));
}
string& bufferToString(char* buffer, int bufflen, string& str)
{
char temp[bufflen];
memset(temp, '\0', bufflen + 1);
strncpy(temp, buffer, bufflen);
return(str.assign(temp));
}
int main(int argc, char *argv[])
{
char buff[4] = {'a', 'b', 'c', 'd'};
char str[5];
string str2;
cout << bufferToCString(buff, sizeof(buff), str) << endl;
cout << bufferToString(buff, sizeof(buff), str2) << endl;
}
|
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 version. This would give:
std::string bufferToString(char* buffer, int bufflen)
{
std::string ret(buffer, bufflen);
return ret;
}
If you really must use the C-string version, either drop a 0 at the bufflen position (if you can) or create a buffer of bufflen+1, then memcpy the buffer into it, and drop a 0 at the end (bufflen position).
|
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 basic operation of sets.
Of course I can write a function by myself, but I just wonder if there are built in function from tr1.
Thank you very much.
|
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 performance, since successive lookups in hash B will be going to the same hash bucket (assuming that both hashes are using the same hash function). That should give you decent memory locality, even though these buckets are almost certainly implemented as linked lists.
Here's some code for unordered_set_difference(), you can tweak it to make the versions for set union and set difference:
template <typename InIt1, typename InIt2, typename OutIt>
OutIt unordered_set_intersection(InIt1 b1, InIt1 e1, InIt2 b2, InIt2 e2, OutIt out) {
while (!(b1 == e1)) {
if (!(std::find(b2, e2, *b1) == e2)) {
*out = *b1;
++out;
}
++b1;
}
return out;
}
Assuming you have two unordered_sets, x and y, you can put their intersection in z using:
unordered_set_intersection(
x.begin(), x.end(),
y.begin(), y.end(),
inserter(z, z.begin())
);
Unlike bdonlan's answer, this will actually work for any key types, and any combination of container types (although using set_intersection() will of course be faster if the source containers are sorted).
NOTE: If bucket occupancies are high, it's probably faster to copy each hash into a vector, sort them and set_intersection() them there, since searching within a bucket containing n elements is O(n).
|
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 where currentTime does not seem to reset (or it does reset but then update sets it back somehow.
The method update is called roughly every second or so while restart only occurs when a user initiates a restart event (presses a button). I think this is threading timing issue, any suggestions or comments on what is happening are welcome.
|
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 + timeDelay;
}
restart(Time newTime)
{
boost::mutex::scoped_lock lock(_access);
currentTime = newTime;
}
};
|
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.
Say I have a string s of chars s[0]:s[N] and where each char s[i] <= s[i+1]
For example the string
aaacdddghzz
I want to generate all combinations of substrings while keeping the same relationship between chars.
So for example I would get
a
aa
aaa
ad
aad
aaad
add
aadd
aaadd
addd
aaddd
aaaddd
d
dd
ddd
.
.
.
ac
aac
.
.
.
acdddghzz
aacdddghzz
aaacdddghzz
But not
ca
hdz
...etc
Now I know how to work out how many combinations there are. You create a histogram of the frequency of letters in the string. So in the above example the that would be
For string aaacdddghzz
a=3
d=3
c=1
g=1
h=1
z=2
and the formula is (a+1)(c+1)(d+1)(g+1)(h+1)(z+1) = 4*4*2*2*2*3 = 384. There are 384 substrings that keep the s[i] <=s [i+1] relationship.
So the question is how do I generate those 384 substrings recursively? Actually an iterative method would be just as good, maybe better as large strings with many unique chars might cause the stack to overflow. This sounds like homework but it isn't. I'm just useless at coming up with algorithms like this. I use C++ but pseudocode would be fine.
|
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(int i, int j) {
/* print the current output string */
output[j] = '\0';
printf("%s\n", output);
/* extend the output by each character from each remaining group and call ourselves recursively */
while(input[i] != '\0') {
output[j] = input[i];
printsubs(i + 1, j + 1);
/* find the next group of characters */
do ++i;
while(input[i] == input[i - 1]);
}
}
int main(void) {
printsubs(0, 0);
return 0;
}
If your interest is merely in counting how many subsequences there are, you can do it much more efficiently. Simply count up how many of each letter there are, add 1 to each value, and multiply them together. In the above example, there are 3 a's, 3 b's, 3 c's, and 2 d's, for (3 + 1) * (3 + 1) * (3 + 1) * (2 + 1) = 192 subsequences. The reason this works is that you can choose between 0 and 3 a's, 0 and 3 b's, 0 and 3 c's, and 0 and 2 d's, and all of these choices are independent.
|
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: Cannot open source file: '.\$(lib3rdparty)\qt\qtwinmigrate- 2.5-commercial\src\qmfcapp.cpp': No such file or directory
As you can see, our project compiles in several source files from QT. QT lives inside a folder of external libraries, and we don't want hardcode the path from our project to that folder (we have a very large solution)
|
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 to go with the good ole' C/C++ types from <time.h>. Any drawbacks down the road? Any other time type I miss that is a darling of the iPhone SDK?
|
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 is only used to represent values and intervals within a media file, and is usually based on a configurable time base.
|
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)/(x1 - x0), then y = (1 - t) * y0 + t * y1 = y0 + t * (y1 - y0).
The problem is when x1 - x0 is small. The result will introduce cancellation error. When combined with the one of x - x0, in the division I expect a significant error in t.
The question is if there exist another way to determine y with a better accuracy ?
i.e. should I compute (x - x0)*(y1 - y0) first, and divide by (x1 - x0) after ?
The difference y1 - y0 will always be big.
|
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 between them.
In your best algorithm, the t term represents these lower bits. And to continue or example, if x0 and x1 differ by 4 bits, then t can take on only 16 values either. The calculation of these possible values is fairly robust. Whether you're calculating 3E0/14E0 or 3E-12/14E-12, the result is going to be close to the mathematical value of 3/14.
Your formula has the additional advantage of having y0 <= y <= y1, since 0 <= t <= 1
(I'm assuming that you know enough about float representations, and therefore "(x1-x0) is small" really means "small, relative to the values of x1 and x0 themselves". A difference of 1E-1 is small when x0=1E3 but large if x0=1E-6 )
|
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 to decrease deployment size of application?
How about static linking? Will it embed the whole dll, or only parts of it that are used?
And also is it possible with Qt to link some dlls staticly and some dynamicly?
|
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 you can do (which I do for my Qt apps is):
use UPX to compress your DLL
or
use strong compression in your installer
If you already UPX your dll, you can not reduce it further with the installer compression, but this can reduce other files.
|
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 object-oriented, and has by far better documentation and its better maintained.
See it online: http://qt-project.org/doc/qt-4.8/
EDIT-
6 years since the original Answer. I should point to Qt5 - http://www.qt.io/
|
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
Output size: 1600x1200
I have a compatible webcam and works fine on changing manually to YUY2 and 1600x1200 in AMcap app.
By default it is:
Color Space/Compression: MJPG
Output size: 160x120
I tried to find 'YUY2' string in whole project, but I could not find it, so that I could hardcode it. It seems it is created dynamically and then operated; refer: in the file amcap.cpp nearby line no 3395.
|
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_IAMStreamConfig, (void **)&gcap.pVSC);
if(hr != NOERROR)
{
// this means we can't set frame rate (non-DV only)
ErrMsg(TEXT("Error %x: Cannot find VCapture:IAMStreamConfig"), hr);
}
}
gcap.fCapAudioIsRelevant = TRUE;
Paste:
CMediaType *pmt;
// default capture format
if(gcap.pVSC && gcap.pVSC->GetFormat((AM_MEDIA_TYPE**)&pmt) == S_OK)
{
// DV capture does not use a VIDEOINFOHEADER
if(pmt->formattype == FORMAT_VideoInfo)
{
pmt->SetType(&MEDIATYPE_Video);
pmt->SetFormatType(&FORMAT_VideoInfo);
pmt->SetSubtype(&MEDIASUBTYPE_YUY2);
pmt->SetTemporalCompression(FALSE);
VIDEOINFOHEADER* lpvihin = (VIDEOINFOHEADER*) pmt->pbFormat;
{
//DWORD fccYUY2 = 'YUY2' ;
//lpvihin->bmiHeader.biCompression =fccYUY2;
//'YUY2';// MAKEFOURCC('Y','U','Y','2');
//lpvihin->bmiHeader.biBitCount = 16;
lpvihin->bmiHeader.biWidth = 1600;// 960; //1600;
lpvihin->bmiHeader.biHeight = 1200;// 720; //1200;
lpvihin->bmiHeader.biSizeImage = 1600*1200*3;
hr = gcap.pVSC->SetFormat(pmt);
ResizeWindow(HEADER(pmt->pbFormat)->biWidth,
ABS(HEADER(pmt->pbFormat)->biHeight));
}
}
if(pmt->majortype != MEDIATYPE_Video)
{
// This capture filter captures something other that pure video.
// Maybe it's DV or something? Anyway, chances are we shouldn't
// allow capturing audio separately, since our video capture
// filter may have audio combined in it already!
gcap.fCapAudioIsRelevant = FALSE;
gcap.fCapAudio = FALSE;
}
DeleteMediaType(pmt);
}
Thanks a lot
|
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
the parent of the calling process.
The kill() system call can be used to send any signal to any process group or process.
Remarks:
1. Using system is evil. Use internal functions to send signals.
2. killall would be even more evil. Consider several instances of your program running at once.
|
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, and secondly the suspend might fail if the thread is running kernel code. I can work around this, but I feel there should be a more elegant solution. I could also reverse it using
int Count = ResumeThread(ThreadHandle);
SuspendThread(ThreadHandle);
But this has similar problems. Any good alternative method of getting the suspend count from the handle?
|
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 1: " << solution1 << endl;
float solution2 = (float)(-b) - (sqrt((b*b) - (4 * a * c)));
solution2 = solution2 / (2*a);
cout << "Solution 2: " << solution2;
If, for example, I use the equation: x^2 - x - 6, I get the solution 3, -2 correctly.
My question is how would I account for complex numbers....for example, given the equation:
x^2 + 2x + 5
Solving by hand, I would get -1 + 2i, -1 - 2i.
Well, I guess two question, can I write the above better and also make it account for the complex number?
Thanks for any help!
|
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("no solutions");
return result;
}
double delta=b*b-4*a*c;
if(delta>=0)
{
result.p1.r=(-b-sqrt(delta))/2/a;
result.p2.r=(-b+sqrt(delta))/2/a;
}
else
{
result.p1.r=result.p2.r=-b/2/a;
result.p1.i=sqrt(-delta)/2/a;
result.p2.i=-sqrt(-delta)/2/a;
}
return result;
}
That way you get the results in a similar way for both real and complex results (the real results just have the imaginary part set to 0). Would look even prettier with boost!
edit: fixed for the delta thing and added a check for degenerate cases like a=0. Sleepless night ftl!
|
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 into the vector. This space isn't deallocated until the program terminates (since the vector is static). Is this right?
In the destructor of the class that contains the vector, I'm deleting the object that I put into the vector. However, the memory that's allocated when the insertion happened is still hanging around. Is there anyway to delete this space?
|
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 appreciate your help.
#include <iostream>
using namespace std;
class TestStaticVariables
{
// Private member variable:
static const double static_double_variable;
public:
// Constructor:
TestStaticVariables()
{
// Initialization:
static const double static_double_variable = 20.0;
cout << static_double_variable;
}
// Member Function:
void test();
};
void TestStaticVariables::test()
{
When this next line is uncommented I get the following error message:
Line Location Tool:0: "TestStaticVariables::static_double_variable", referenced from:
//cout << static_double_variable;
}
int main(int argc, char* const argv[])
{
TestStaticVariables test_instance;
return 0;
}
|
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::_bar << std::endl;
}
int main( int argc, char *argv[] ) {
Foo f;
f.Bar();
return 0;
}
|
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 called:
void SomeFunction();
int main(int argCount, char ** argList)
{
// at this point, the memory reserved for 'answer'
// already contains the value of 42
SomeFunction();
}
void SomeFunction()
{
static int answer = 42;
}
However, if the static variable is an instance of a class:
class MyClass
{
//...
};
void SomeFunction();
int main(int argCount, char ** argList)
{
SomeFunction();
}
void SomeFunction()
{
static MyClass myVar;
}
I know that it will not be initialized until the first time that the function is called. Since the compiler has no way of knowing when the function will be called for the first time, how does it produce this behavior? Does it essentially introduce an if-block into the function body?
static bool initialized = 0;
if (!initialized)
{
// construct myVar
initialized = 1;
}
|
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 function once in the main thread before any others are called will usually do the trick.
I should add that if the initialization of the local static is by a simple constant like in your example, the compiler doesn't need to go through these gyrations - it can just initialize the variable in the image or before main() like a regular static initialization (because your program wouldn't be able to tell the difference). But if you initialize it with a function's return value, then the compiler pretty much has to test a flag indicating if the initialization has been done or something equivalent.
|
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 *dir;
d = opendir(".");
if (d)
{
while ((dir = readdir(d)) != NULL)
{
// Stuff
}
closedir(d);
}
return(0);
}
But need to add recursive directory searching as well. To do this, my solution was to attempt to opendir() on the next file, and judge the error code to determine if it was successfully opened as a directory (which I would then recurse on) or if it was returned to be 'not a directory', which would then be listed as just a file.
I admit it feels very klugey, but I have been unable to find a better method that can retain some portability (not win32), even after hours of searching.
So my simplified solution (some psuedo for simplicity) is looking something like this:
int scan(string startdir)
{
DIR *d;
struct dirent *dir;
d = opendir(startdir.cstr());
if (d)
{
while ((dir = readdir(d)) != NULL)
{
if( NOT '.' AND NOT '..')
{
if(temp = opendir(startdir + d) == NULL)
{
//FILE OR ERROR
}else{
//Opened successfully as a directory, so recurse
scan(startdir + d->d_name + "\\");
}
}
}
closedir(d);
}
return(0);
}
This is just half rewritten psuedo code to keep it simple, but it seems to work (although I'm very open to suggestions on better ways to do this).
The major issue I'm having, however, is a particular link file 'c:\cygwin\dev\fd' which seems to be opening as a directory and recursively opening itself over and over infinitely.
The 'fd' file is 4KB, 106 bytes with no extension and is a shortcut that does not point anywhere in Windows.
This error seems to indicate that either this kludgey method is bugged, or there's a problem in the cygwin implementation that I'm compiling in.
As a short example:
Error Reading: c:\cygwin\dev\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\0 No such file or directory
Excluding that directory, the search seems to work well. But I'm not alright with hard coding an exclusion in to the scanner.
If anyone has any ideas, suggestions, solutions, or alternative methods to this problem, your input would be appreciated.
Thanks.
|
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 levels of scanning, it becomes unreliable and the errors can still occur.
I am now looking into other ways to achieve this functionality (ie boost::filesystem).
|
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.
I used to hold the oipinion that by-const-ref can replace by-value in call cases since even Herb Sutter and Bjarne said they are conceptually equal, and "by ref"(be it const) implies being faster. until recently, I read somewhere that by-val may be better optimized in some cases.
Then when and how?
|
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 object from memory a number of times through the function, to be sure the value hasn't changed.
This is the reason for C99's restrict keyword (the same issue but with pointers).
|
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 "multiple queues" thing. I know how to implement this with a single queue. The workers need to wait on all the queues that they can process (wait for ANY of them).
On Windows I would use WaitForMultipleObjects, but this needs to be multi-platform.
I don't want any particular code for this, only a hint or a description of the model which I should use. Thanks in advance.
|
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. Otherwise, it goes back to waiting on the condition variable. Waiting on a condition variable puts the thread to sleep, so it does not consume CPU time.
Of course, it goes without saying that you should protect all accesses to the job queues with a mutex (e.g. pthread_mutex_t).
|
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 how to check for errors.
How can I see if connect() did not succeed, and if that is the case, why it did not succeed?
|
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;
} else {
/* error */
}
Now error gives you the error number, if any.
|
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 the most difficult part here, so lets assume they are of the exact same dimensions.
I want to show my shape on the usb camera picture. The white part will be considered as transparent for the combinaison purpose. Right now I'm thinking of editing the image pixels by pixels, but I'm searching for an API which will do it for me.
So if I take a picture with a house in the middle of it and overlay a red rectagle, the resulting image will have the original picture with a red rectangle around the house.
I'm using .NET if this can help. I could also use win32 API if it contains some useful functions.
Edit :
I accepted the answer since it put me on the right track. This is actually super easy to do.
Bitmap^ overlay_image = gcnew Bitmap("overlay.bmp");
Bitmap^ original_image = gcnew Bitmap("original.bmp");
overlay_image->MakeTransparent(Color::White);
Graphics^ g_original = Graphics::FromImage(original_image);
g_original->DrawImage(overlay_image, 0, 0);
Voilà, original_image now has a red rectangle over it. It is actually fast enough for my 30fps usb camera so I can get it in real time.
There is no scaling done right now. Also, it assumes that the overlay image background is white, which will be made transparent.
|
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 char *str = strs[i];
...
If I already have an STL container, I can use BOOST_FOREACH
std::vector<std::string> strs;
BOOST_FOREACH(std::string str, strs) {
...
I've tried to create a macro to combine all these concepts but without success.
I'd like to be able to write code like this:
SPECIAL_STRING_FOREACH(const char* str, {"abc", "xyz", "123"}) {
...
}
Surely someone's cooked this up before.
|
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 \
for(boost::remove_reference<boost::function_traits<void(D)> \
::arg1_type>::type _t[] = __VA_ARGS__; \
!c; c = true) \
BOOST_FOREACH(D, _t)
int main() {
SEQ_FOR_EACH(std::string &v, { "hello", "doctor" }) {
std::cout << v << std::endl;
}
}
Note that you can also iterate with a reference variable, to avoid useless copying. Here is one using boost.preprocessor and the (a)(b)... syntax, compiling down to the same code after pre-processing stage.
#define SEQ_FOR_EACH(D, SEQ) \
if(bool c = false) ; else \
for(boost::remove_reference<boost::function_traits<void(D)> \
::arg1_type>::type _t[] = { BOOST_PP_SEQ_ENUM(SEQ) }; \
!c; c = true) \
BOOST_FOREACH(D, _t)
int main() {
SEQ_FOR_EACH(std::string &v, ("hello")("doctor")) {
std::cout << v << std::endl;
}
}
The trick is to assemble a function type that has as parameter the enumeration variable, and getting the type of that parameter. Then boost::remove_reference will remove any reference. First version used boost::decay. But it would also convert arrays into pointers, which i found is not what is wanted sometimes. The resulting type is then used as the array element type.
For use in templates where the enumerator variable has a dependent type, you will have to use another macro which puts typename before boost::remove_reference and boost::function_traits. Could name it SEQ_FOR_EACH_D (D == dependent).
|
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 print different coloured text to the Windows Console?
|
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 namespace std;
enum colour { DARKBLUE = 1, DARKGREEN, DARKTEAL, DARKRED, DARKPINK, DARKYELLOW, GRAY, DARKGRAY, BLUE, GREEN, TEAL, RED, PINK, YELLOW, WHITE };
struct setcolour
{
colour _c;
HANDLE _console_handle;
setcolour(colour c, HANDLE console_handle)
: _c(c), _console_handle(0)
{
_console_handle = console_handle;
}
};
// We could use a template here, making it more generic. Wide streams won't
// work with this version.
basic_ostream<char> &operator<<(basic_ostream<char> &s, const setcolour &ref)
{
SetConsoleTextAttribute(ref._console_handle, ref._c);
return s;
}
int main(int argc, char *argv[])
{
HANDLE chandle = GetStdHandle(STD_OUTPUT_HANDLE);
cout << "standard text" << setcolour(RED, chandle) << " red text" << endl;
cin.get();
}
|
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 <stdlib.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 exist in the environment, then string is added to the
environment. If name does exist, then the value of name in the
environment is changed to value. The string pointed to by string becomes
part of the environment, so altering the string changes the environment.
On Win32 it's called _putenv I believe.
See SetEnvironmentVariable also if you're a fan of long and ugly function names.
|
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 hinted recently that this might not be the most accurate way.
Any thoughts?
|
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 processors, 64-bit float operations are actually internally computed using 80 bits when using the default FPU mode, and storing it off in a variable will cause those extra precision bits to be truncated according to your FPU rounding mode (which defaults to nearest). This only really matters if you are concatenating many float operations and have to worry about the error accumulation.
|
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 worked with this or that knows about this technology.
Where to start? Any ideas? Any example (like Hello World DCOM)?
|
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 in C, but it will be very, very painful. COM is optimized for C++ development.
This book is not perfect nor "complete". There are some (granted, a bit esoteric) areas that the book skims over. For example, the book has like 1 1/2 pages on "monikers" (I have never seen a treatment of monikers that satisfies me). I consider this book to be THE fundamental book.
Second, in real life you are likely to want to use a supporting library such as ATL, rather than writing all the COM glue directly. There are too many ways to make subtle mistakes in COM even in the basic set up. ATL will give you good patterns and implement the boring code for you. In learning, you are better off using plain C++.
There are many books about ATL and several are quite good. I understand that ATL has changed quite a bit since the old days of VC++6, but I don't have first hand knowledge there: sadly, most of the COM code I work with is forever locked to the flavor of C++ in VC6.
Make sure whatever book you get is written for the version of Visual Studio and/or ATL you are planing on using.
Some background on COM books:
Note that there are a lot of books out there that misunderstand COM, or focus on the wrong things. The older books are worse in this respect. Some of the first few books treated COM as little more than a plumbing detail needed to make OLE work ("Object Linking and Embedding", that's what allows you to drag-and-drop a spreadsheet range into a Word document). Because of that, a lot of the material out there is very confusing. It took a while before people realized that OLE wasn't that important and that COM really was.
By the time Don Box published "Essential COM", the cracks on the foundation of COM had started to become evident. There isn't anything terribly flawed with COM, but the needs of the development community had evolved and outgrown what COM could do without serious revamping.
.NET was born out of that effort to address the limitations in COM, especially in the area of "type information". Just a few years after "Effective COM" was published, the attention of the community shifted away to .NET. Because of that, good COM training material is now and will likely remain forever limited.
So, COM is not broken, and it works great for the things it's used for (that's why Explorer still uses it). It's just not the best solution anymore for many of the problems that need solving today.
In summary:
I recommend "Essential COM" for the basics. Then, any of many good ATL books available (no strong preferences there), and then use other resources like MSDN or -- of course -- Stack Overflow, to cover areas that are of particular interest to you.
If you'd rather avoid relying on resources of the dead-tree variety, go ahead and learn ATL from the web. But some books are worth reading the old fashioned way -- and "Essential COM" is one of them.
Good luck.
|
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 Python.
As for learning C++, first get a good understanding of C. C is quite simple, so it shouldn't take that long. Once you know C, start learning about the C++ specific features one at a time. This way, you can still write useful programs (C is mostly a subset of C++), before you learn the real "C++ic" way.
|
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
platforms, such as Windows and Linux,
run primarily on 32 bit processors and
most compilers for these platforms use
a 32 bit int which has the same size
and representation as a long.
|
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.h"
#include <mylib_class_a.h> // using library MyLib
All .h and .cpp files for the same library are in the same directory. To avoid name collision, file names are often prefix with company name and/or library name. MyLib will be in MyApp's header search path, etc. I'm not a fan of prefixing filenames, but I like the idea of looking at the #include and know exactly where that header file belongs. I don't hate this approach of organizing files, but I think there should be a better way.
Since I'm starting a new project, I want to solicit some directory organization ideas. Currently I like this directory structure:
ProjA
+--include
+--ProjA
+--mylib
+--class_a.h
+--app
+--other_class.h
+--src
+--mylib
+--class_a.cpp
library_private_helpers.h
library_private_helpers.cpp
+--app
+--other_class.cpp
app.cpp
util.h
app.cpp:
#include "util.h" // private util.h file
#include <ProjA/app/other_class.h> // public header file
#include <ProjA/mylib/class_a.h> // using class_a.h of mylib
#include <other3rdptylib/class_a.h> // class_a.h of other3rdptylib, no name collision
#include <class_a.h> // not ProjA/mylib/class_a.h
#include <ProjA/mylib/library_private_helpers.h> // error can't find .h
.cpp files and private (only visible to immediate library) .h files are stored under the src directory (src is sometimes called lib). Public header files are organized into a project/lib directory structure and included via <ProjectName/LibraryName/headerName.h>. File names are not prefixed with anything. If I ever needed to package up MyLib to be used by other teams, I could simply change my makefile to copy the appropriate binary files and the whole include/ProjA directory.
Once files are checked into source control and people start working on them it will be hard to change directory structure. It is better to get it right at the get-go.
Anyone with experience organizing source code like this? Anything you don't like about it? If you have a better way to do it, I would very much like to hear about it.
|
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 using this stuff. If you're writing a library and its going to be used by other programmers, then it's good to organize the headers they want to use into an include folder. If you're creating a number of libraries and publishing them all, then your structure might work. But, if they're independent libraries, and the development isn't all done together and they get versioned and released at different times, you'd be better off sticking with having all files for one project locatable within one folder.
In fact, I would say keep everything in one folder, until you get to a point where you find its unmanagable, then reorganize into a clever scheme of dividing the source up into folders like you've done. You'll probably know how it needs to be organized from the problems you run into.
KISS is usually always the solution in programming -> keep everything as simple as possible.
|
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); // or reinterpret_cast<>/static_cast<>/etc
|
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 (cin.get(c)) d.push_back(c);
for (deque<char>::reverse_iterator j = d.rbegin(); j != d.rend(); j++)
cout << (*j);
}
The previous code just loads a stream of chars from stdin and outputs them in reverse order. It works fine for up to 100K or so characters, but dies with "error writing stdout" message in Windows for files that are larger. It always dies with the same character.
A shell command like "cat bigfile.txt | reverse.exe" is all you need to reproduce the problem. Both MSFT and Intel compilers both act similarly.
I realize there may be a buffer on stdout, but shouldn't that be flushed automatically when it's filled?
|
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 but at least it's now not something code related.
|
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 ugly code. Is there a nicer way to do this?
string toStrMaxDecimals(double value, uint decimals) {
value *= pow(10, decimals);
value = round(value);
value *= pow(0.1, decimals);
string temp = boost::lexical_cast<string>(value);
size_t dot = temp.find('.');
if (dot != string::npos) {
if (temp.size() > dot + decimals + 1)
temp.erase(dot + decimals + 1);
if (*temp.rbegin() == '0')
temp.erase(temp.find_last_not_of("0") + 1);
if (*temp.rbegin() == '.')
temp.append("0");
} else {
temp.append(".0");
}
return temp;
}
|
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 strerror(). It takes a code (int), and returns the corresponding string, or the empty string if that code is not known.
Where is the danger?
Is there a good alternative in C?
Is there a good alternative in C++?
[edit]
Having had some good answers, and now understanding that some implementations may be crazy enough to actually write to a common shared buffer - unsafe to reentrancy within a single-thread, never mind between threads! - my question stops being "Why can't I use it, and what are the alternatives?" to "Are there any decent, succinct alternatives in C and/or C++?"
Thanks in advance
|
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 large enough before writing to it, helping to avoid buffer overruns that could allow malicious code to execute.
|
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 intensive. I would like to know how you guys think what my design. Here is the list.
I have some arrays that need to pass around and eventually need to pass to some C code. I could pass a pointer and a size all over of the place. But I chose to create a class that represents this -- a class that has a fixed size (we know the maximum size) buffer, and a length which should be always <= the size of the buffer, otherwise assert. In this way, I can pass the array around with only one variable instead of two, and if the maximum size changes in the future, I should be able to change it easily. I don't use dynamic allocation for the array because it is embedded system and memory allocation could potentially fail and we don't use exception. The class is probably less than 30 lines code, and I use it for quite a few places. They said I over-designed it.
They have their own containers implementation in C. I needed to use one of them, but I wanted to hide all the detailed code away from my main logic, so I created a wrapper class
for it. The wrapper class is similar to stl, so I have iterators and it manages the memory
allocation internally, but unlike stl, it returns a error code when it can't allocate more
memory. Their argument on this one is that I am the only one uses it, so they don't want it to be in the repository. I found it stupid to be honest.
EDIT: The following class is more or less that I used for point 1. All I wanted to do is to have something to pass around without carrying the length all the time.
class A
{
static const MAX_SIZE = 20;
int m_Array[MAX_SIZE];
size_t m_Len;
public:
A(const int* array, size_t len)
{
assert(len <= MAX_SIZE);
memcpy(m_Array, array, len);
m_Len = len;
}
size_t GetLen() const { return m_Len; }
const int* GetArray() const { return m_Array; }
};
|
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 considers any amount of design to be acceptable. It looks harmless to me[*]. I suppose you could have just made it a struct with two public members, and lose the benefit of read-onliness. How keen are your colleagues on const-correctness in general?
I think the goal for 2 should be to reach consensus on whether that C API should be used directly from C++, or wrapped. If it should be wrapped (and the arguments for that are probably quite strong, what with namespacing and RAII), design a wrapper that everyone will use, and designate it "the C++ API for this module" rather than "a C++ wrapper that one module uses for this other module".
It's possible that everyone else genuinely prefers the API as it is, over a more OO API or using STL. Following their conventions will make it easiest for them to maintain your code, as long as their conventions are solid C programming style. C++ is a multi-paradigm language, and "C with a limited number of bells and whistles" isn't the paradigm you're used to. But it is a valid paradigm, and if it's what the existing codebase uses then you have to question whether what your company needs right now is a one-man revolution, however enlightened.
[*] (the API, that is. They might question whether it will be passed by value inappropriately, and whether it's wise for every instance to have to be as big as the biggest. That's all for you to argue out with the reviewer, but is nothing to do with "over-design".
|
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 the (I assume) poorly-thought-of MFC library has features in, for example, its CString class that some folks think useful enough to cause them to continue using it despite the fact that it's (a) non-standard and (b) that it's (I assume, from the wealth of criticism) deficient in many important ways.
My question is twofold, then:
A. What libraries that are poorly-thought-of contain features that nonetheless make it worth continuing to use them, what are those features, and what's so good about them?
B. Are there "adaptor" libraries out there that simplify and/or tighten up the use of such libraries, e.g. providing nice interfaces that abstract resources leaks, adaptors that go from a non-STL library interface to a STL, and so on
As a relative newbie to StackOverflow, I'm not 100% sure that this question is sufficiently on-point, so I apologise up-front if it's too open-ended.
Thanks in advance
|
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 useful features of C++ suppressed (or didn't exist at the time.) I think this library alone is responsible for good chunk of people thinking that C++ is hard and ugly. Very recently Boost collection started catching up with threads, ipc, and networking, so there is at least an alternative. BUT with all that said, I still think it's worth to be familiar with ACE if you are in that space since, again, way too many people use it, the ideas are good, and it can serve as great negative example for library design.
|
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 the way to go for building C++ projects (we were also using make to do builds the Java code in our mixed Java and C++ projects, although I believe ant was starting to become mainstream).
I like using Maven for builds. My question is not to debate the relative merits of using Maven, but to determine what the level of adoption is for the Native Maven Plugin for building C++ projects and what people's experience with this has been. Alternately, is there a new common toolchain for C++ builds that has a lot of momentum?
|
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 JNI part.
|
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 added
It all has to do with namespaces. The .h counterparts for C++ standard headers usually #includes the proper C++ standard header (without .h extension) and then issues a bunch of using (something like this):
FILE: iostream.h
#include <iostream>
using std::iostream;
using std::ostream;
using std::ios;
...
whereas the headerfile without the .h extension does not pollute the namespace with all the defined classes and types.
|
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 VS C++, but I'm not want to work with managed C++.
Regards
Here a put a very simple example
wifstream file;
file.open("C:\\appLog.txt", ios::in);
wchar_t buffer[2048];
file.seekg(2);
file.getline(buffer, bSize-1);
wprintf(L"%s\n", buffer);
file.close();
|
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 a library that abstracts away some of this.
|
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
but be able to access the entries by a key.
Can these features be combined? Is there some standard way to address
this?
#include <list>
#include <iostream>
struct City{
City(std::string a_n, int a_d):name(a_n), duration(a_d){}
std::string name;
int duration;
};
int main(){
std::list<City*> trip;
trip.push_back(new City("NY", 5));
trip.push_back(new City("LA", 2));
for (std::list<City*>::iterator ii=trip.begin(); ii!=trip.end(); ++ii)
std::cout << (*ii)->name << " for " << (*ii)->duration << " days." <<std::endl;
}
|
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 less boiler plate code if you want to add new indexes. It is also usually more space and time efficient
typedef multi_index_container<
City,
indexed_by<
sequenced<>, //gives you a list like interface
ordered_unique<City, std::string, &City::name> //gives you a lookup by name like map
>
> city_set;
|
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 easiest way to make your own iterator? Or, what is another way to do this?
EDIT Ultimately, I don't think it was good design. I have redesigned the entire class heirarchy. +1 for refactoring. However, I did solve this problem sufficiently. Here's an abbreviated version of what I did, for reference; it uses boost::filter_iterator. Let T be the type in the container.
enum Flag
{
A_flag,
B_flag
};
class T_proxy
{
public:
T_proxy(const T& t, Flag f) : t_(t), flag_(f) {}
operator T() const {return t_;}
Flag flag() const {return flag_;}
class Compare
{
public:
Compare(Flag f) : matchFlag_(f) {}
operator() (const T_proxy& tp) {return tp.flag() == matchFlag_;}
private:
Flag matchFlag_;
};
private:
T t_;
Flag flag_;
};
class AB_list
{
public:
typedef T_proxy::Compare Compare;
typedef vector<T_proxy>::iterator iterator;
typedef boost::filter_iterator<Compare, iterator> sub_iterator;
void insert(const T& val, Flag f) {data_.insert(T_proxy(val, f));}
// other methods...
// whole sequence
iterator begin() {return data_.begin();}
iterator end() {return data_.end();}
// just A
sub_iterator begin_A() {return sub_iterator(Compare(A_flag), begin(), end());
sub_iterator end_A() {return sub_iterator(Compare(A_flag), end(), end());
// just B is basically the same
private:
vector<T_proxy> data_;
};
// usage
AB_list mylist;
mylist.insert(T(), A_flag);
for (AB_list::sub_iterator it = mylist.begin_A(); it != mylist.end_A(); ++it)
{
T temp = *it; // T_proxy is convertible to T
cout << temp;
}
|
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,
indexed_by<
sequenced<>, //gives you a list like interface
ordered_unique<Container, std::string, &Container::a_value>, //gives you a lookup by name like map
ordered_unique<Container, std::string, &Container::b_value> //gives you a lookup by name like map
>
> container;
If you are iterating over one index, you can switch to another index by using the iterator projection concept in the library.
|
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 them to work.
Could someone tell me if my unterstanding of typelists is right and give an simple real world example how to use typelists in every day average code? Thanks in advance.
Btw, I'm using Windows and Visual Studio 2005 and its compiler.
EDIT: my examples are gone, I use a sandbox project in vs to test those things. But it was quiet similar to code in Dobbs tutorial:
void SomeOperation(DocumentItem* p)
{
if (TextArea* pTextArea = dynamic_cast<TextArea*>(p))
{
... operate on a TextArea object ...
}
else if (VectorGraphics* pVectorGraphics =
dynamic_cast<VectorGraphics*>(p))
{
... operate on a VectorGraphics object ...
}
else if (Bitmap* pBitmap = dynamic_cast<Bitmap*>(p))
{
... operate on a Bitmap object ...
}
else
{
throw "Unknown type passed";
}
}
This works but I don't see the advantage over inheritance which is capable to do the same. And dynamic cast don't work on primitive types. Is it possible to use it as a return value like:
typedef Typelist<int, string> mylist
mylist myfunction() {
if(foo == bar)
return 5;
return "five";
}
|
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 inherit from anything you want. This is simply not feasible, because this existing type may be a built in type or a type from a library.
Think of the typelists as extensions of lists of types (e.g. in std::pair) for any reasonable number of types (instead of just 2).
The typelists can be used to create a facility to pass around a set of arguments to a function. This is a piece of code that calls generalized functors of 5 parameters (another concept from Modern C++ design) with the arguments supplied in a tupe (yet another one) with the typelist that defines types of objects held in the tuple:
//functor is just a holder of a pointer to method and a pointer to object to call this
//method on; (in case you are unfamiliar with a concept)
template<class R, class t0, class t1, class t2, class t3, class t4>
R call(Loki::Functor<R,LOKI_TYPELIST_5(t0, t1, t2, t3, t4
)> func,
Loki::Tuple<LOKI_TYPELIST_5(t0, t1, t2, t3, t4)> tuple)
{
///note how you access fields
return func(Loki::Field<0>(tuple), Loki::Field<1>(tuple),
Loki::Field<2>(tuple), Loki::Field<3>(tuple),
Loki::Field<4>(tuple));
}
//this uses the example code
#include<iostream>
using namespace std;
int foo(ostream* c,int h,float z, string s,int g)
{
(*c)<<h<<z<<s<<g<<endl;
return h+1
}
int main(int argc,char**argv)
{
Loki::Functor<int,LOKI_TYPELIST_5(ostream*, int, float, string, int)> f=foo;
//(...)
//pass functor f around
//(...)
//create a set of arguments
Loki::Tuple<LOKI_TYPELIST_5(ostream*, int, float, string, int)> tu;
Field<0>(tu)=&cout;
Field<1>(tu)=5;
Field<2>(tu)=0.9;
Field<3>(tu)=string("blahblah");
Field<4>(tu)=77;
//(...)
//pass tuple tu around, possibly save it in a data structure or make many
//specialized copies of it, or just create a memento of a call, such that
//you can make "undo" in your application; note that without the typelist
//you would need to create a struct type to store any set of arguments;
//(...)
//call functor f with the tuple tu
call(f,tu);
}
Note that only with other concepts like tuples or functors the typelists start to be useful.
Also, I have been experiencing Loki for about 2 years in a project and because of the template code (a lot of it) the sizes of executables in DEBUG versions tend to be BIG (my record was 35 MB or so). Also there was a bit of hit on the speed of compilation. Also recall that C++0x is probably going to include some equivalent mechanism. Conclusion: try not to use typelists if you don't have to.
|
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, b, c, d;
A(int _a, int _b, int _c, int _d) : a(_a), b(_b), c(_c), d(_d)
{
}
};
class B
{
public:
int a, b, c, d;
};
Is there any advantage of using
B b = {1, 2, 3, 4}
instead of
A a = A(1, 2, 3, 4);
?
|
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 a constructor. In your B, class scenario, you can't.
So while you may get a small boost in perf, for using B, I would wager it to be negligible, and would be negated by the potential headache of having unprotected class members.
|
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 maximum width AND a minimum width?
And on a lesser note, is it possible to create a class derived from cout or ostream?
|
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 a warning that it is nonstandard. Is there a good way to do something like this?
|
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 needed to create a bunch of small test programs, and eventually I simply put while(true); at the end on most of my test programs, just so I could see the results. Is there a better wait function I can use?
|
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 will continue once the user hits enter.
Link
|
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;
}
intx;cin>>x;
return 0;
}
outputs a series of international characters (well, not all of them are 'international' per se, but I get things like pi and spanish inverted question mark). Anyways, I know this is becuase the program access chars that have not been initialized, but why do particular values create particular symbols, what are the ASCII values of the symbols (if they have ASCII values) and how can I get the symbols without glitching my program?
|
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. You have to put something into your "box" before you can take anything out.
The symbols themselves are probably extended ASCII, you can get at them through any extended ASCII table. This one came up first on google. For instance, you could do:
cout << "My extended ascii character is: " << (char)162 << endl;
to get a crazy international o.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.