nkint nkint - 1 month ago 12
C++ Question

std::vector to string with custom delimiter

I would like to copy the contents of a

vector
to one long
string
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
charT*
but I get

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


Then I tried using
char
and
ostream_iterator<int>(s,&delimiter)

but I get strange characters in the string.

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

Answer

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.

Comments