Skip to content

Instantly share code, notes, and snippets.

@monhime

monhime/accum_string.cpp

Last active Jan 18, 2021
Embed
What would you like to do?
vector<string>を全結合
#include <iostream>
#include <vector>
#include <numeric>
#include <string>
using namespace std;
int main(){
vector<string> A = {"I", "have", "a", "pen."};
string sum_A = accumulate(A.begin() + 1, A.end(), A[0], [](string &init, string &v){ return init + v; });
cout << sum_A << "\n"; // "Ihaveapen."
string sum_A2 = accumulate(A.begin() + 1, A.end(), A[0], [](string &init, string &v){ return init + " " + v; });
cout << sum_A2 << "\n"; // "I have a pen."
auto f = [](string &init, string &v) -> string { return init + " " + v; };
string sum_A3 = accumulate(A.begin() + 1, A.end(), A[0], f);
cout << sum_A3 << "\n"; // "I have a pen."
const string delim = ", ";
auto f2 = [&delim](string &init, string &v) -> string { return init + delim + v; };
string sum_A4 = accumulate(A.begin() + 1, A.end(), A[0], f2);
cout << sum_A4 << "\n"; // "I, have, a, pen."
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment