如何将一个数值转为std::vector
时间: 2024-06-20 19:00:16 浏览: 7
将一个数值转为std::vector需要将数值中的每个数字分离出来,然后将它们存储到std::vector中。以下是一种简单的方法:
```
#include <vector>
#include <iostream>
std::vector<int> convertToVector(int num){
std::vector<int> vec;
while(num > 0){
vec.insert(vec.begin(), num % 10);
num /= 10;
}
return vec;
}
int main(){
int num = 12345;
std::vector<int> vec = convertToVector(num);
for(auto i:vec){
std::cout << i << " ";
}
return 0;
}
```
上述代码中,convertToVector函数将整数num转换为std::vector。在while循环中,通过num % 10取出num的末位数字并存储到vec的头部,然后将num除以10以删除已经存储的末位数字。最终,返回存储数字的std::vector。在main函数中,调用convertToVector函数将整数12345转换为std::vector,并打印出std::vector中的每个数字。
相关问题
std::vector<cstring>转为std::vector<int>
可以使用std::transform函数将std::vector<cstring>转换为std::vector<int>。需要注意的是,需要将字符串先转为整数再存入新的vector中,例如使用std::stoi函数。示例代码如下:
```c++
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
int main() {
std::vector<std::string> str_vec = {"1", "2", "3", "4", "5"};
std::vector<int> int_vec(str_vec.size());
std::transform(str_vec.begin(), str_vec.end(), int_vec.begin(), [](const std::string& str) {
return std::stoi(str);
});
for (const auto& i : int_vec) {
std::cout << i << " ";
}
return 0;
}
```
MFC将std::vector<CString>转为std::vector<int>
在MFC中,可以使用循环遍历std::vector<CString>,并将每个字符串转换为int类型,然后将其添加到std::vector<int>中。可以使用CString类的ToInt()函数将CString转换为int类型。以下是一个示例代码:
```
std::vector<CString> strVec; // 原始的字符串vector
std::vector<int> intVec; // 转换后的整型vector
// 假设strVec已经被填充好了
// 循环遍历每个字符串,将其转换为整型并添加到intVec中
for (auto str : strVec) {
int intValue = _ttoi(str); // 将CString转换为int
intVec.push_back(intValue); // 添加到intVec中
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)