如何在同一行中获取多个整数作为输入并将它们存储在 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++ 中有更好的方法吗?
How to take multiple integers in the same line as an input and store them in an array or vector in c++?
像这样:
int arr[6]; for(int i=0;i<6;i++){ cin>>arr[i]; }
寻求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;
}
为了解决 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++ 中有更好的方法吗?
How to take multiple integers in the same line as an input and store them in an array or vector in c++?
像这样:
int arr[6]; for(int i=0;i<6;i++){ cin>>arr[i]; }
寻求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;
}