Given a vector of string ["one", "two", "three"].
Question> How do I convert it into "one two three"?
I know the manual way to do it with a loop and would like to know whether there is a simpler way with STL function.
// Updated based on suggestion that I should use accumulate
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
struct BindTwoStrings
{
string operator()(const string& s1, const string& s2) const {
return s1.empty() ? s2 : s1 + " " + s2;
}
};
int main()
{
vector<string> vecString {"one", "two", "three"};
string ret2;
ret2 = accumulate(vecString.begin(), vecString.end(), ret2,
[] (const string& s1, const string& s2) -> string {
return s1.empty() ? s2 : s1 + " " + s2; });
cout << "ret2:\"" << ret2 << "\"" << endl;
string ret;
ret = accumulate(vecString.begin(), vecString.end(), ret, BindTwoStrings());
cout << "ret:\"" << ret << "\"" << endl;
return 0;
}