【问题标题】:what is the c++ equivalent of map(int,input().split()) of python? [duplicate]python的map(int,input().split())的c ++等价物是什么? [复制]
【发布时间】:2019-05-28 08:06:18
【问题描述】:

我发现很难在 c++ 中完成所有字符串操作然后解析成整数数组,而我们可以在 python 中只使用一行代码。

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

【问题讨论】:

  • 你可能想分享你的字符串的实际样子
  • 这真的是两个问题; “如何在 C++ 中拆分字符串”和“如何在 C++ 中将字符串转换为整数”。您应该能够轻松找到这两个问题的答案,而无需进行搜索。

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


【解决方案1】:

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

#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);

【讨论】:

  • 你为什么用for(std::string s; iss &gt;&gt; s; ) result.push_back(std::stoi(s));而不是for(int n; iss &gt;&gt; n; ) result.push_back(n);
  • 因为我显然在睡觉。感谢您修复 ;)
【解决方案2】:

这个问题太宽泛了,有很多解决方案取决于你的字符串格式。如果您想使用自定义分隔符拆分字符串并将其转换为整数(或其他),我个人使用以下函数(我完全不知道是否有更快的方法):

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));
}

【讨论】:

    猜你喜欢
    • 2010-09-24
    • 2014-03-14
    • 2014-02-06
    • 1970-01-01
    • 2011-06-12
    • 2016-07-03
    • 1970-01-01
    • 2012-02-26
    • 2021-07-01
    相关资源
    最近更新 更多