std::vector to string with custom delimiter
Use delimiter.c_str()
as the delimiter:
copy(x.begin(),x.end(), ostream_iterator<int>(s,delimiter.c_str()));
That way, you get a const char*
pointing to the string, which is what ostream_operator
expects from your std::string
.
C++11:
vector<string> x = {"1", "2", "3"};
string s = std::accumulate(std::begin(x), std::end(x), string(),
[](string &ss, string &s)
{
return ss.empty() ? s : ss + "," + s;
});
Another way to do it:
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
template <typename T>
string join(const T& v, const string& delim) {
ostringstream s;
for (const auto& i : v) {
if (&i != &v[0]) {
s << delim;
}
s << i;
}
return s.str();
}
int main() {
cout << join(vector<int>({1, 2, 3, 4, 5}), ",") << endl;
}
(c++11 range-based for loop and 'auto' though)