Re: STL vector - which style of for() loop?
Hi Jeff,
When I tried to run your version it didn't like the "argument list" for
ostream_iterator(cout), I then added this line to the header file
typedef ostream_iterator <string, char, char_traits <char> > OstreamIt;
I then changed the code slightly to
copy( TheStrings.begin()
, TheStrings.end()
, OstreamIt(cout, " ") );
It now works, but it concatenates the strings, instead of putting them
on new lines. I don't understand:
A) the typedef in the header and why it works, or even if it's correct
B) The comma operator where it says OstreamIt(cout, " ")
I like the look of your version, but need more info on how to code it
properly and how to control the formatting.
Jeff Flinn wrote:
See inline below:
Gerry Hickman wrote:
Hi,
I have this code below, and would like to know which for() loop style
is best - the second one seems a bit of a mouthful!
* Beware line wrap *
int _tmain(int argc, _TCHAR* argv[])
{
// Call a function that populates strings
vector< string > TheStrings;
TheStrings = returnStrings();
for(unsigned i = 0; i < TheStrings.size(); i++) {
cout << TheStrings[i] << endl;
}
for(vector<string>::iterator myIterator = TheStrings.begin();
myIterator != TheStrings.end(); myIterator++)
{
cout << *myIterator << endl;
}
std::copy( TheStrings.begin()
, TheStrings.end()
, std::ostream_iterator(cout) );
return 0;
}
vector< string > returnStrings()
{
// From Google Groups, demo of how to return a vector from a func
vector< string > Strings;
Strings.push_back( "hello" );
Strings.push_back( "hello1" );
Strings.push_back( "hello2" );
return Strings; // Original author didn't have this?
}
Jeff F
--
Gerry Hickman (London UK)