繁体   English   中英

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

[英]Check if next element is the last element in the STL List

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

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

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

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

请指教。

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

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

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

怎么样以不同的方式做...

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

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

我会做的不同。 假设集合通常有多个元素,我会这样做:

        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;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM