Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::vector to string with custom delimiter

Tags:

c++

string

vector

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?

like image 318
nkint Avatar asked Feb 14 '12 13:02

nkint


People also ask

Is there a split function in C++?

There is no built-in split() function in C++ for splitting strings, but there are numerous ways to accomplish the same task, such as using the getline() function, strtok() function, find() and erase() functions, and so on. This article has explained how to use these functions to split strings in C++.

How do you add to a string in C++?

C++ '+' operator for String Concatenation C++ '+' operator can be used to concatenate two strings easily. The '+' operator adds the two input strings and returns a new string that contains the concatenated string.


2 Answers

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.

like image 196
jpalecek Avatar answered Sep 21 '22 00:09

jpalecek


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;                                 }); 
like image 30
max.kondr Avatar answered Sep 22 '22 00:09

max.kondr