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

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 <typename Iter>
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();
}

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

#include <algorithm> // for std::copy
#include <iterator>  // for std::ostream_iterator

std::vector<int> values(); // initialize these
std::stringstream buffer;
std::copy(values.begin(), values.end(), std::ostream_iterator<int>(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.


simply, where the type in the container is an int:

std::string s = std::accumulate(++v.begin(), v.end(), std::to_string(v[0]),
                     [](const std::string& a, int b){
                           return a + ", " + std::to_string(b);
                     });

Tags:

Algorithm

C++