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

lil*_*ily 2 c++ stl

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

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

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

{1,3,4,5,}
There --^
Run Code Online (Sandbox Code Playgroud)

请指教.

Bar*_*zKP 8

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

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

    if (++current != l.end())
        output << ", ";
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*vid 5

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

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

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