python的map(int,input()。split())的C ++等效项是什么?

时间:2019-05-28 08:06:19

标签: python c++ string c++14

我发现很难进行所有的字符串操作,然后在c ++中解析为整数数组,而我们只能在python中仅使用一行即可。

在C ++中将整数字符串拆分为整数数组的最简单方法是什么?

2 个答案:

答案 0 :(得分:2)

有很多选项可以做到这一点。例如,使用标准流可以使用以下方法实现:

#include <vector>
#include <string>
#include <sstream>

std::string s = "1 2 3";
std::vector<int> result;
std::istringstream iss(s);
for(int n; iss >> n; ) 
    result.push_back(n);

答案 1 :(得分:0)

这个问题太广泛了,根据您的字符串格式,有很多解决方案。如果您想使用自定义定界符分割字符串并将其转换为整数(或其他),我个人使用以下函数(我绝对不知道是否有更快的方法):

void split_string_with_delim(std::string input, std::string delimiter, std::vector<std::int> &output){
    ulong pos;
    while ((pos = input.find(delimiter)) != std::string::npos) {
        std::string token = input.substr(0, pos);
        output.push_back(std::stoi(token));
        input.erase(0, pos + delimiter.length());
    }
    output.push_back(std::stoi(input));
}