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

后端 未结 6 619
傲寒
傲寒 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:16

    Since you're looking for a recipe, go ahead and use the one from Boost. Once you get past all the genericity, it's not too complicated:

    1. Allocate a place to store the result.
    2. Add the first element of the sequence to the result.
    3. While there are additional elements, append the separator and the next element to the result.
    4. Return the result.

    Here's a version that works on two iterators (as opposed to the Boost version, which operates on a range.

    template 
    std::string join(Iter begin, Iter end, std::string const& separator)
    {
      std::ostringstream result;
      if (begin != end)
        result << *begin++;
      while (begin != end)
        result << separator << *begin++;
      return result.str();
    }
    

提交回复
热议问题