First, this requires the ostringstream stream ostringstream to concatenate multiple times and preserve the main problem of excessive memory allocation.
the code:
string join(const vector<string>& vec, const char* delim) { ostringstream oss; if(!string_vector.empty()) { copy(string_vector.begin(),string_vector.end() - 1, ostream_iterator<string>(oss, delim.c_str())); } return oss.str(); } vector<string> string_vector {"1", "2"}; string delim("->"); string joined_string = join();
Explanation:
thinking treat oss here as std::cout
when we want to write:
std::cout << string_vector[0] << "->" << string_vector[1] << "->" ,
we can use the following STL classes as reference:
ostream_iterator returns a wrapped output stream with delimiters automatically added each time << used.
eg,
ostream my_cout = ostream_iterator<string>(std::cout, "->")
wraps std:cout as my_cout
so every time you my_cout << "string_vector[0]" ,
this means std::cout << "string_vector[0]" << "->"
As for copy(vector.begin(), vector.end(), std::out);
this means std::cout << vector[0] << vector[1] (...) << vector[end]
Shihao Xu Jun 22 '16 at 3:56 on 2016-06-22 03:56
source share