Is there a way to implement analog of Python's 'separator'.join() in C++?

后端 未结 6 622
傲寒
傲寒 2021-02-07 03:44

All I\'ve found is boost::algorithm::string::join. However, it seems like overkill to use Boost only for join. So maybe there are some time-tested recipes?

<
6条回答
  •  醉酒成梦
    2021-02-07 04:31

    If you really want ''.join(), you can use std::copy with an std::ostream_iterator to a std::stringstream.

    #include  // for std::copy
    #include   // for std::ostream_iterator
    
    std::vector values(); // initialize these
    std::stringstream buffer;
    std::copy(values.begin(), values.end(), std::ostream_iterator(buffer));
    

    This will insert all the values to buffer. You can also specify a custom separator for std::ostream_iterator but this will get appended at the end (this is the significant difference to join). If you don't want a separator, this will do just what you want.

提交回复
热议问题