这个python代码的C++等价物是什么

What is the C++ equivalent of this python code?

本文关键字:等价物 是什么 C++ python 代码 这个      更新时间:2024-04-28

li = list(map(int,input().split()))

我对c++还很陌生。我基本上想要这个代码的最简单版本,它接受我通过终端传入的输入,并将输出推回到向量。

我试过:

#include <iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
string input;
vector<int> numbers;
while(getline(cin,input,' ')){
numbers.push_back(stoi(input));
}
for(int i : numbers){
cout << i << endl;
}
return 0;
}

我使用g++9.2.0。同样的代码在在线ide上运行良好。我不确定这是否是g++编译器的问题。奇怪的东西!

您的示例对我来说运行良好:https://ideone.com/bFLjB1

您可以通过使用cinoperator>>:的默认类型推导和空白分割行为来稍微清理一下

std::vector<int> numbers;
int temp = 0;
while (std::cin >> temp) {
numbers.push_back(temp);
}

您可以直接从空白分隔的输入中构造容器。

#include <iostream>
#include <vector>
#include <iterator>
int main() {
std::vector<int> numbers(std::istream_iterator<int>(std::cin), {});
for(int i : numbers){
std::cout << i << std::endl;
}
return 0;
}