Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if next element is the last element in the STL List

Tags:

c++

stl

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.

like image 485
lily Avatar asked Dec 08 '22 11:12

lily


2 Answers

The simplest fix for your code would be:

for (current = l.begin();current != l.end();)
{
    output << (*current);

    if (++current != l.end())
        output << ", ";
}
like image 194
BartoszKP Avatar answered Feb 01 '23 22:02

BartoszKP


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.

like image 29
David Avatar answered Feb 01 '23 22:02

David