如何在 C++ 中将向量 <int> 转换为字符串
How to convert a vector<int> to string in C++
假设我有一个vector<int>
,我想把它转换成字符串,我该怎么办?
我在网上搜索得到的是
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();
}
但我无法理解它的含义或工作原理。还有其他简单易懂的方法吗?
仅当您想在每个插入的整数后添加分隔符时才需要该代码,但即便如此也不必那么复杂。一个简单的循环和 to_string
的使用更具可读性:
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)
}
}
分隔为数字,
std::vector<int> v {0, 1, 2, 3, 4};
std::string s("");
for(auto i : v)
s += std::to_string(i);
带逗号分隔符
std::vector<int> v {0, 1, 2, 3, 4};
std::string s("");
for(auto i : v)
s += std::to_string(i) + ",";
s.pop_back();
假设我有一个vector<int>
,我想把它转换成字符串,我该怎么办?
我在网上搜索得到的是
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();
}
但我无法理解它的含义或工作原理。还有其他简单易懂的方法吗?
仅当您想在每个插入的整数后添加分隔符时才需要该代码,但即便如此也不必那么复杂。一个简单的循环和 to_string
的使用更具可读性:
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)
}
}
分隔为数字,
std::vector<int> v {0, 1, 2, 3, 4};
std::string s("");
for(auto i : v)
s += std::to_string(i);
带逗号分隔符
std::vector<int> v {0, 1, 2, 3, 4};
std::string s("");
for(auto i : v)
s += std::to_string(i) + ",";
s.pop_back();