dzhelil dzhelil - 1 month ago 20
C++ Question

C++ vector to string

I have a

container that has integers (e.g. {1,2,3,4}) and I would like to convert to a string of the form


What is the cleanest way to do that in C++?
In Python this is how I would do it:

>>> array = [1,2,3,4]
>>> ",".join(map(str,array))


Definitely not as elegant as Python, but nothing quite is as elegant as Python in C++.

You could use a stringstream ...

std::stringstream ss;
for(size_t i = 0; i < v.size(); ++i)
  if(i != 0)
    ss << ",";
  ss << v[i];
std::string s = ss.str();

You could also make use of std::for_each instead.