Convert vector <int> to delimited string

As I see here , there is a quick and short way to converting a vector to a string separated by a character in C #:

var result = string.Join(";", data); var result = string.Join(";", data.Select(x => x.ToString()).ToArray()); 

I want to know if there is the same way in C ++ for this?

+7
c ++ string vector
source share
1 answer
 #include <sstream> #include <string> #include <vector> #include <iterator> #include <iostream> int main() { std::vector<int> data = {42, 1, 2, 3, 4, 5}; std::ostringstream oss; std::copy(data.begin(), data.end(), std::ostream_iterator<int>(oss, ";")); std::string result( oss.str() ); std::cout << result << "\n"; } 

NB In C ++ 11 you can use a more general form

 using std::begin; using std::end; std::copy(begin(data), end(data), std::ostream_iterator<int>(oss, ";")); 

If declarations of use are not required, if ADL can be used (for example, in the example above).


It is also possible, but perhaps a little less effective:

 std::string s; for(auto const& e : v) s += std::to_string(e) + ";"; 

which can be written via std::accumulate in <algorithm> as:

 std::string s = std::accumulate(begin(v), end(v), std::string{}, [](std::string r, int p){ return std::move(r) + std::to_string(p) + ";"; }); 

(IIRC was some method to exclude copying, perhaps by taking the lambda parameter from std::string& r .)


Option without end semicolon (thanks to Dietmar KΓΌhl ):

 std::vector<int> data = {42, 1, 2, 3, 4, 5}; std::ostringstream out; if (!v.empty()) { std::copy(v.begin(), v.end() - 1, std::ostream_iterator<int>(out, ";")); out << v.back(); } std::string result( out.str() ); std::cout << result << "\n"; 
+12
source share

All Articles