简体   繁体   English

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

[英]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. 请指教。

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. 循环中没有条件( std::copy循环),所以这也是更优化的。

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

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

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