Printing lists with commas C++

后端 未结 28 2350
时光取名叫无心
时光取名叫无心 2020-11-22 03:33

I know how to do this in other languages, but not C++, which I am forced to use here.

I have a Set of Strings that I\'m printing to out in a list, and they need a co

28条回答
  •  情书的邮戳
    2020-11-22 03:48

    In python we just write:

    print ", ".join(keywords)
    

    so why not:

    template
    std::string
    join(const S& sep, const V& v)
    {
      std::ostringstream oss;
      if (!v.empty()) {
        typename V::const_iterator it = v.begin();
        oss << *it++;
        for (typename V::const_iterator e = v.end(); it != e; ++it)
          oss << sep << *it;
      }
      return oss.str();
    }
    

    and then just use it like:

    cout << join(", ", keywords) << endl;
    

    Unlike in the python example above where the " " is a string and the keywords has to be an iterable of strings, here in this C++ example the separator and keywords can be anything streamable, e.g.

    cout << join('\n', keywords) << endl;
    

提交回复
热议问题