ezpresso ezpresso - 2 months ago 14
C++ Question

How to implode a vector of strings into a string (the elegant way)

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?

Answer

It might not be obvious but while adding strings in implode you are doing lots of memory allocations and deallocations. A possible improvement is to do reserve() for s once and the then all your additions.