4

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

ereOn
  • 53,676
  • 39
  • 161
  • 238
  • Sadly, the answer is no. – John Dibling Sep 27 '10 at 13:27
  • possible duplicate of [Printing lists with commas C++](http://stackoverflow.com/questions/3496982/printing-lists-with-commas-c) Call me biased if you will (after all, I am), but I think my answer to that question is particularly clean... :-) – Jerry Coffin Sep 27 '10 at 13:28
  • I mean, you can do funky things with `transform` or `accumulate`, but those would involve using functors. You wouldnt have to write a loop, but you would have to write code. – John Dibling Sep 27 '10 at 13:28

1 Answers1

5

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>), ", "
);
Yakov Galka
  • 70,775
  • 16
  • 139
  • 220
  • 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 Sep 27 '10 at 13:35