-2

when i am using std::list, i have method "back()":

for ( it = list->begin(); it != list.back(); it++ ) {
   cout << it.getName() << ", ";
}
cout << it.getName() << endl;

output: (element, element, element)

std::set has no member back(), and i can't output last element without ", ":

output: (element, element, element, )

  • You can use [`rbegin`](http://en.cppreference.com/w/cpp/container/set/rbegin), it's a little unclear what you're doing why don't you just iterate until the `it != set.end()`? – EdChum Apr 01 '15 at 10:26

1 Answers1

0

This is good enough for most uses:

for (auto it = list.begin(); it != list.end(); ++it)
{
   if (it != list.begin()) cout << ", ";
   cout << it->getName();
}

If you want ( ) around the output, just add couts either side of the loop.

If you're mad-keen to keep the conditional out of the loop:

if (!list.empty())
{
     auto it = list.begin();
     cout << it->getName();
     while (++it != list.end())
         cout << ", " << it->getName();
}
Tony Delroy
  • 102,968
  • 15
  • 177
  • 252