4

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

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

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

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

请指教。

4

3 回答 3

9

对您的代码最简单的修复是:

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

    if (++current != l.end())
        output << ", ";
}
于 2013-11-06T12:45:28.480 回答
5

换个方式怎么办...

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

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

于 2013-11-06T12:45:33.340 回答
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;
    }
于 2013-11-06T13:44:21.433 回答