views:

76

answers:

1

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" ?

+5  A: 

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>), ", "
);
ybungalobill
Nice solution, but you should indicate that it only works with lists of `string` (or `string`-convertable objects) while `ostream_iterator` can deal with anything `cout` deals with. Upvoted though.
ereOn
@ereOn: updated.
ybungalobill