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”?
ereOn source share