如何使用 STL 算法将整数向量转换为字符串向量?
How can I convert a vector of ints to be a vector of strings using STL algorithms?
例如,我需要{20,6,143}
才能成为{"20","6","143"}
。
只需使用基于范围的 for 循环,您就可以遍历整数向量,并使用std::to_string
您可以将每个元素转换为字符串并存储为新的字符串向量。
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<int> vec{ 20,6,143 };
std::vector<std::string> strVec;
strVec.reserve(vec.size()); // reserve memory for unwanted reallocations
for (int element : vec)
strVec.emplace_back(std::to_string(element));
for (const auto& str : strVec)
std::cout << str << " ";
}
(在线观看直播(
或者使用std::transform
,您可以按如下方式变换整数的向量。
#include <iostream>
#include <vector>
#include <string>
#include <algorithm> // std::transform
#include <iterator> // std::cbegin
int main()
{
std::vector<int> vec{ 20,6,143 };
std::vector<std::string> strVec;
strVec.reserve(vec.size()); // reserve memory for unwanted reallocations
std::transform(std::cbegin(vec), std::cend(vec),
std::back_inserter(strVec), // insert to the back of strVec
[](const int element) { return std::to_string(element);}
);
for (const auto& str : strVec)
std::cout << str << " ";
}
(在线观看直播(
std::transform 与 std::to_string 相结合应该可以解决问题。
相关文章:
- 将CHW格式的浮点向量转换为cv::Mat
- 将元组的向量转换/构造为堆
- 将编译时常量向量转换为堆分配版本
- 在 Cython 中将C++向量转换为 numpy 数组,而无需复制
- 在<uint8_t> <char> c++ 中将常量向量转换为常量向量
- C++ 将地址保存为字符串的向量转换为新的向量
- 如何使用 STL 算法将整数向量转换为字符串向量?
- 在 c++ 中将集合转换为向量和向量转换为字符串时出现运行时异常
- 如何使用istream_iterator将无符号字符向量转换为字符串?
- 如何在 c++ 中将向量转换为<string>常量字符* const*?
- 将字符向量转换为单个字符串
- <int> 使用 fmt 库将向量转换为字符串
- 将 c++ 向量转换为字符 ** 而不会泄漏内存
- 在C++中将字符向量转换为字符串向量
- 避免从单一元素向量转换为基元类型
- 无法从向量<T>转换为 T
- 将浮点数向量转换为十六进制/二进制字符串
- 虚拟地将结构向量转换为结构成员的向量
- 将整数向量转换为字节数组向量,然后调用每个字节数组
- 如何从向量转换为<char>数字整数