检查下一个元素是否是STL列表中的最后一个元素

时间:2013-11-06 12:42:41

标签: c++ stl

我一直在尝试很多解决方案。但无法弄清楚如何做到这一点:

for (current = l.begin();current != l.end();current++)
{
    next = ++current;
     if(next != l.end())
            output << (*current)  << ", ";
     else
            output << (*current);
}

我正在尝试打印列表并删除最后一个逗号:

{1,3,4,5,}
There --^

请告知。

3 个答案:

答案 0 :(得分:8)

您的代码最简单的修复方法是:

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

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

答案 1 :(得分:5)

以不同的方式做到这一点......

if(!l.empty())
{
    copy(l.begin(), prev(l.end()), ostream_iterator<T>(output, ", "));
    output << l.back();
}

循环中没有条件(std::copy循环),所以这也是更优的。

答案 2 :(得分:0)

我会以不同的方式做到这一点。假设集合通常有多个元素,我会这样做:

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

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

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

将所有这些放入模板函数中以获得可重用的代码:

    //! 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;
    }
相关问题