如何打印以逗号分隔的元素列表?

新手上路,请多包涵

我知道如何用其他语言做到这一点,但不知道在 C++ 中,我不得不在这里使用它。

我有一组字符串( keywords ),我正在打印到 out 作为列表,这些字符串之间需要一个逗号,但不是尾随逗号。例如,在 Java 中,我会使用 StringBuilder 并在构建字符串后删除末尾的逗号。我怎样才能在 C++ 中做到这一点?

 auto iter = keywords.begin();
for (iter; iter != keywords.end( ); iter++ )
{
    out << *iter << ", ";
}
out << endl;

我最初尝试插入以下块来执行此操作(在此处移动逗号打印):

 if (iter++ != keywords.end())
    out << ", ";
iter--;

原文由 quandrum 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 930
2 个回答

使用中缀迭代器:

 // infix_iterator.h
//
// Lifted from Jerry Coffin's 's prefix_ostream_iterator
#if !defined(INFIX_ITERATOR_H_)
#define  INFIX_ITERATOR_H_
#include <ostream>
#include <iterator>
template <class T,
          class charT=char,
          class traits=std::char_traits<charT> >
class infix_ostream_iterator :
    public std::iterator<std::output_iterator_tag,void,void,void,void>
{
    std::basic_ostream<charT,traits> *os;
    charT const* delimiter;
    bool first_elem;
public:
    typedef charT char_type;
    typedef traits traits_type;
    typedef std::basic_ostream<charT,traits> ostream_type;
    infix_ostream_iterator(ostream_type& s)
        : os(&s),delimiter(0), first_elem(true)
    {}
    infix_ostream_iterator(ostream_type& s, charT const *d)
        : os(&s),delimiter(d), first_elem(true)
    {}
    infix_ostream_iterator<T,charT,traits>& operator=(T const &item)
    {
        // Here's the only real change from ostream_iterator:
        // Normally, the '*os << item;' would come before the 'if'.
        if (!first_elem && delimiter != 0)
            *os << delimiter;
        *os << item;
        first_elem = false;
        return *this;
    }
    infix_ostream_iterator<T,charT,traits> &operator*() {
        return *this;
    }
    infix_ostream_iterator<T,charT,traits> &operator++() {
        return *this;
    }
    infix_ostream_iterator<T,charT,traits> &operator++(int) {
        return *this;
    }
};
#endif

用法类似于:

 #include "infix_iterator.h"

// ...
std::copy(keywords.begin(), keywords.end(), infix_iterator(out, ","));

原文由 Jerry Coffin 发布,翻译遵循 CC BY-SA 2.5 许可协议

从 C++11 开始,您可以使用 partition_copy 有条件地输出。

 std::vector<int> arr{0, 1, 2, 3, 4};

//C++11 example
int count = arr.size();
std::partition_copy(
    arr.begin(), arr.end(),
    std::ostream_iterator<int>(std::cout),
    std::ostream_iterator<int>(std::cout, ", "),
    [count] (int) mutable {
        return (--count) == 0;
    }
);

//after C++14, it support lambda capture initialization
std::partition_copy(
    arr.begin(), arr.end(),
    std::ostream_iterator<int>(std::cout),
    std::ostream_iterator<int>(std::cout, ", "),
    [count = arr.size()] (int) mutable {
        return (--count) == 0;
    }
);

现场演示

原文由 firejox 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题