在 C++ 中,将整数向量(即 vector
)转换为字符串的最简单方法是什么?
In C++, what is the simplest way to convert a vector of ints (i.e. vector<int>
) to a string ?
也许 std::ostream_iterator
和 std::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;
}
这篇关于转换向量<int>串起来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!