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& 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
                        ,[&sep](std::string const& a, std::string const& 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 *