Usually, when I had to display a list of separated strings, I was doing 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;
}
}
Which outputs:
apple, banana, orange
I recently discovered std::ostream_iterator
which if found really 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 ,
. Is there an elegant way to handle the special "first (or last) element case" and to have the same output than the first code, without its "complexity" ?