I'm looking for the most elegant way to implode a vector of strings into a string. Below is the solution I'm using now:
static std::string& implode(const std::vector<std::string>& elems, char delim, std::string& s)
{
for (std::vector<std::string>::const_iterator ii = elems.begin(); ii != elems.end(); ++ii)
{
s += (*ii);
if ( ii + 1 != elems.end() ) {
s += delim;
}
}
return s;
}
static std::string implode(const std::vector<std::string>& elems, char delim)
{
std::string s;
return implode(elems, delim, s);
}
Is there any others out there?
Firstly, a stream class
ostringstream
is needed here to do concatenation for many times and save the underlying trouble of excessive memory allocation.Code:
Explanation:
when thinking, treat
oss
here asstd::cout
when we want to write:
std::cout << string_vector[0] << "->" << string_vector[1] << "->"
,we can use the following STL classes as help:
ostream_iterator
returns an wrapped output stream with delimiters automatically appended each time you use<<
.for instance,
ostream my_cout = ostream_iterator<string>(std::cout, "->")
wraps
std:cout
asmy_cout
so each time you
my_cout << "string_vector[0]"
,it means
std::cout << "string_vector[0]" << "->"
As for
copy(vector.begin(), vector.end(), std::out);
it means
std::cout << vector[0] << vector[1] (...) << vector[end]
(include
<string>
,<vector>
,<sstream>
and<iterator>
)If you want to have a clean end (no trailing delimiter) have a look here
Slightly long solution, but doesn't use
std::ostringstream
, and doesn't require a hack to remove the last delimiter.http://www.ideone.com/hW1M9
And the code: