How to convert a & lt; Int & gt; Login to C ++

advertisements

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?


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)
    }
}