Convert a vector<int> to a string

D R picture D R · Sep 16, 2009 · Viewed 96.5k times · Source

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

"1,2,3,4"

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))
'1,2,3,4'

Answer

Brian R. Bondy picture Brian R. Bondy · Sep 16, 2009

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

You could use a stringstream ...

#include <sstream>
//...

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.