-3

Suppose I have a vector<int> and I want to convert it into string, what should I do? What I got from searching on the internet is

std::ostringstream oss;

if (!vec.empty())
{
  // Convert all but the last element to avoid a trailing ","
 std::copy(vec.begin(), vec.end()-1,
    std::ostream_iterator<int>(oss, ","));

// Now add the last element with no delimiter
oss << vec.back();
}

But I cannot understand what it means or how it works. Is there any other simple to understand way?

ronilp
  • 455
  • 2
  • 9
  • 25

2 Answers2

2

That code is only needed if you want to add a delimiter after every inserted integer, but even then it doesn't have to be that complicated. A simple loop and the use of to_string is far more readable:

std::string str;

for (int i = 0; i < vec.size(); ++i) {
    str += std::to_string(vec[i]);
    if (i+1 != vec.size()) { // if the next iteration isn't the last
        str += ", "; // add a comma (optional)
    }
}
David G
  • 94,763
  • 41
  • 167
  • 253
0

Delimiting to numbers,

std::vector<int> v {0, 1, 2, 3, 4};
std::string s("");
for(auto i : v)
    s += std::to_string(i);

With a comma seperator

std::vector<int> v {0, 1, 2, 3, 4};
std::string s("");
for(auto i : v)
    s += std::to_string(i) + ",";
s.pop_back();
Achilles Rasquinha
  • 353
  • 1
  • 3
  • 11