How nice is it to list split lines?

Usually, when I had to display a list of split lines, I would do something like:

using namespace std; vector<string> mylist; // Lets consider it has 3 elements : apple, banana and orange. for (vector<string>::iterator item = mylist.begin(); item != mylist.end(); ++item) { if (item == mylist.begin()) { cout << *item; } else { cout << ", " << *item; } } 

What outputs:

 apple, banana, orange 

I recently discovered std::ostream_iterator , which, if found, is very nice to use.

However, with the following code:

 copy(mylist.begin(), mylist.end(), ostream_iterator<string>(cout, ", ")); 

If get:

 apple, banana, orange, 

Almost perfect, except for the extra ones,. Is there an elegant way to handle the special “first (or last) case of an element” and have the same result as the first code, without its “complexity”?

+3
source share
1 answer

Although not with std:

 cout << boost::algorithm::join(mylist, ", "); 

EDIT: No problem:

 cout << boost::algorithm::join(mylist | boost::adaptors::transformed(boost::lexical_cast<string,int>), ", " ); 
+5
source

All Articles