代码之家  ›  专栏  ›  技术社区  ›  ereOn

如何很好地输出分隔字符串列表?

  •  3
  • ereOn  · 技术社区  · 14 年前

    通常,当我需要显示一个分隔字符串列表时,我会做如下操作:

    using namespace std;
    vector<string> mylist; // Lets consider it has 3 elements : apple, banana and orange.
    
    for (vector<string>::iterator item = mylist.begin(); item != mylist.end(); ++item)
    {
      if (item == mylist.begin())
      {
        cout << *item;
      } else
      {
        cout << ", " << *item;
      }
    }
    

    哪些输出:

    apple, banana, orange
    

    我最近发现 std::ostream_iterator 如果觉得很好用的话。

    但是,使用以下代码:

    copy(mylist.begin(), mylist.end(), ostream_iterator<string>(cout, ", "));
    

    如果得到:

    apple, banana, orange, 
    

    几乎完美,除了多余的 , . 是否有一种优雅的方式来处理特殊的“第一(或最后)元素情况”,并且在不增加“复杂性”的情况下,与第一个代码具有相同的输出?

    1 回复  |  直到 14 年前
        1
  •  5
  •   Yakov Galka    14 年前

    尽管不符合标准:

    cout << boost::algorithm::join(mylist, ", ");
    

    编辑:没问题:

    cout << boost::algorithm::join(mylist | 
        boost::adaptors::transformed(boost::lexical_cast<string,int>), ", "
    );