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

标签 c++ pretty-print separator

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

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

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

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

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

最佳答案

使用中缀迭代器:

// 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, ","));

关于c++ - 如何打印以逗号分隔的元素列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3496982/

相关文章:

powershell - 有 PowerShell 代码格式化程序/ pretty-print 吗?

haskell - 如何使用 Haskell pretty-print 分层缩进 "nest"

python - 如何将带有多个字符的定界符的 .text 解析为 pandas df?

javascript - JavaScript 中的连接函数,对于元素数量未知的数组,分隔符不会显示在末尾

c++ - 使用 glut,我如何制作它以便我可以通过单击并拖动它来移动场景中的对象?

c++ - 在 C++ 中为 vector 查找函数

c++ - 以正确的顺序从十进制转换为二进制

c++ - 将 `basename` 与 __FILE__ 一起使用是否安全?

c++ - 在 GDB pretty-print 中显示特定的 std::vector 元素

python - 在 pandas DF 中选择列