Is there a `[“foo”,”bar”].join(” “)` in c++?

Recently i have been asked if there is python / javascript like join() in c++. Here is what it could look like:

#include <vector>
#include <string>
#include <numeric>
#include <iostream>

template <typename Iter>
string join(Iter begin, Iter end, std::string const&amp; sep) {
  static_assert(is_same_v<typename Iter::value_type, std::string>);
  if(begin == end) { return ""; }
  if(std::next(begin) == end) { return *begin; }
  return std::accumulate(std::next(begin), end, *begin
                        ,[&amp;sep](std::string const&amp; a, std::string const&amp; b) {
                          return a + sep + b;

using namespace std;

int main(){
    vector<string> strings = { "hallo", "wilder", "willi" };
    cout << join(strings.begin(), strings.end(), " ") << endl;

Leave a Reply

Your email address will not be published. Required fields are marked *