I've been trying many solutions. But can't figure out how to do this:
for (current = l.begin();current != l.end();current++)
{
next = ++current;
if(next != l.end())
output << (*current) << ", ";
else
output << (*current);
}
I'm trying to print the list and eliminate the last comma:
{1,3,4,5,}
There --^
Please advise.
The simplest fix for your code would be:
for (current = l.begin();current != l.end();)
{
output << (*current);
if (++current != l.end())
output << ", ";
}
How about doing it a different way...
if(!l.empty())
{
copy(l.begin(), prev(l.end()), ostream_iterator<T>(output, ", "));
output << l.back();
}
There are no conditions in the loop (the std::copy
loops) so this is more optimal too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With