转换向量<int>串起来

2021-12-21 00:00:00 string vector c++

在 C++ 中,将整数向量(即 vector)转换为字符串的最简单方法是什么?

In C++, what is the simplest way to convert a vector of ints (i.e. vector<int>) to a string ?

推荐答案

也许 std::ostream_iteratorstd::ostringstream:

#include <vector>
#include <string>
#include <algorithm>
#include <sstream>
#include <iterator>
#include <iostream>

int main()
{
  std::vector<int> vec;
  vec.push_back(1);
  vec.push_back(4);
  vec.push_back(7);
  vec.push_back(4);
  vec.push_back(9);
  vec.push_back(7);

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

  std::cout << oss.str() << std::endl;
}

相关文章