[英]How to accept space separated integers and store them in a vector in C++?
[英]How to take multiple integers in the same line as an input and store them in an array or vector in c++?
为了解决 Leetcode、Kickstart 或其他竞赛中的问题,我们需要在一行中输入多个整数并将它们存储在数组或向量中,例如
输入:5 9 2 5 1 0
int arr[6];
for (int i = 0; i < 6; i++)
cin >> arr[i];
或者
vector<int> input_vec;
int x;
for (int i = 0; i < 6; i++) {
cin >> x;
input_vec.push_back(x);
}
这很有效,但也大大增加了执行时间,有时 50% 的执行时间用于接受输入,在 Python3 中它是一行代码。
input_list = list(int(x) for x in (input().split()))
但是,在 C++ 中找不到解决方案。
在 c++ 中是否有更好的方法?
借助std::istringstream
的帮助:
#include <iostream>
#include <vector>
#include <sstream>
#include <string>
int main(void) {
std::string line;
std::vector<int> numbers;
int temp;
std::cout << "Enter some numbers: ";
std::getline(std::cin, line);
std::istringstream ss(line);
while (ss >> temp)
numbers.push_back(temp);
for (size_t i = 0, len = numbers.size(); i < len; i++)
std::cout << numbers[i] << ' ';
return 0;
}
如何将同一行中的多个整数作为输入并将它们存储在 c++ 中的数组或向量中?
像这样:
int arr[6]; for(int i=0;i<6;i++){ cin>>arr[i]; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.