Another alternative is the use of std::copy
and the ostream_iterator
class:
std::ostringstream stream;
std::copy(array.begin(), array.end(), std::ostream_iterator<>(stream));
std::string s=stream.str();
s.erase(s.length()-1);
Also not as nice as Python.
For this purpose, I created a join
function:
template <class T, class A>
T join(const A &begin, const A &end, const T &t)
{
T result;
for (A it=begin;
it!=end;
it++)
{
if (!result.empty())
result.append(t);
result.append(*it);
}
return result;
}
Then used it like this:
std::string s=join(array.begin(), array.end(), std::string(","));
You might ask why I passed in the iterators. Well, actually I wanted to reverse the array, so I used it like this:
std::string s=join(array.rbegin(), array.rend(), std::string(","));
Ideally, I would like to template out to the point where it can infer the char type, and use string-streams, but I couldn't figure that out yet.