lily
lily

Reputation: 395

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

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.

Upvotes: 4

Views: 2303

Answers (3)

wilx
wilx

Reputation: 18228

I would do it differently. Assuming that collections have usually more than one element, I would go with this:

        auto start = c.begin();
        auto last = c.end();

        if (start != last)
            output << *start++;

        for (; start != last; ++start)
            output << "," << *start;

Put all of this into a template function to get a reusable piece of code:

    //! Join a list of items into a string.
    template <typename Iterator>
    inline
    void
    join (std::ostream & output, Iterator start, Iterator last, std::string const & sep)
    {
        if (start != last)
            output << *start++;

        for (; start != last; ++start)
            output << sep << *start;
    }

Upvotes: 0

David
David

Reputation: 28178

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.

Upvotes: 5

BartoszKP
BartoszKP

Reputation: 35891

The simplest fix for your code would be:

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

    if (++current != l.end())
        output << ", ";
}

Upvotes: 9

Related Questions