将字符串转换为整数向量
Convert string to a vector of integers
我需要在C 中制作功能,该字符串仅包含数字,例如:
string s = "7654321"
并将其转换为整数的向量。因此向量应该这样:
vec[1] = '7'
vec[2] = '6'
等。
我试图使用isstringstream,但这在这种情况下没有用,因为字符串中没有空间。
您可以使用for loop迭代字符串,并使用push_back()和-'0'
填充每个值假设向量vec;
void fillVec(const string str1, vector<char> & vec) {
for(int i = 0; i < str1.length(); i++)
vec.push_back(str1[i]) - '0';
}
实施此
的示例程序// Example program
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void fillVec(const string, vector<int> &);
int main()
{
vector<int> vec;
string str1 = "1234567";
fillVec(str1, vec);
for(int i = 0; i < vec.size(); i++)
cout << vec[i] << ", ";
return 0;
}
void fillVec(const string str1, vector<int> & vec) {
for(int i = 0; i < str1.length(); i++)
vec.push_back(str1[i]-'0');
}
相关文章:
- C++ 如何比较n个排序的整数向量以找到互元素?
- 如何使用 STL 算法将整数向量转换为字符串向量?
- 使用192/256位整数求和无符号64位整数向量的点积的最快方法
- 如何将整数向量插入到键中,标准::映射的值
- 整数对的向量转化为整数向量的向量
- 如何组合两个整数向量
- C++中整数向量的序列化/反序列化
- 我无法在C++中启动整数向量
- 根据偶数值对整数向量进行排序
- 从整数向量向量搜索整数向量的最佳算法
- 如何将数字转换为整数向量?
- 我需要声明一个包含整数向量的 4x4 矩阵
- 基于整数向量执行位排列的有效方法?
- 将整数向量转换为字节数组向量,然后调用每个字节数组
- 如何将整数向量转换为 2 位十六进制并按顺序添加到 c 字符串?
- 为什么从右值整数向量的元素中推导 decltype(auto) 的类型是 int&?
- 将字符串转换为整数向量
- 尝试创建随机整数向量时的OpenMPI编译器错误
- 整数向量可以创建的整数项的最大数量
- 初始化和显示整数向量时出现意外结果