nkint nkint - 1 year ago 62
C++ Question

std::vector to string with custom delimiter

I would like to copy the contents of a

to one long
with a custom delimiter. So far, I've tried:

// .h
string getLabeledPointsString(const string delimiter=",");
// .cpp
string Gesture::getLabeledPointsString(const string delimiter) {
vector<int> x = getLabeledPoints();
stringstream s;
copy(x.begin(),x.end(), ostream_iterator<int>(s,delimiter));
return s.str();

but I get

no matching function for call to ‘std::ostream_iterator<int, char, std::char_traits<char> >::ostream_iterator(std::stringstream&, const std::string&)’

I've tried with
but I get

error iso c++ forbids declaration of charT with no type

Then I tried using

but I get strange characters in the string.

Can anyone help me make sense of what the compiler is expecting here?

Answer Source

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.