简体   繁体   English

如何将同一行中的多个整数作为输入并将它们存储在 c++ 中的数组或向量中?

[英]How to take multiple integers in the same line as an input and store them in an array or vector in c++?

For solving problems on Leetcode, Kickstart or other competitive competitions, we need to take input of multiple integers in a single line and store them in an array or vector, like为了解决 Leetcode、Kickstart 或其他竞赛中的问题,我们需要在一行中输入多个整数并将它们存储在数组或向量中,例如

Input: 5 9 2 5 1 0输入:5 9 2 5 1 0

int arr[6];
for (int i = 0; i < 6; i++)
    cin >> arr[i];

or或者

vector<int> input_vec;
int x;

for (int i = 0; i < 6; i++) {
     cin >> x;
     input_vec.push_back(x);
}

This works, but also contributes to the execution time drastically, sometimes 50% of the execution time goes into taking input, in Python3 it's a one-line code.这很有效,但也大大增加了执行时间,有时 50% 的执行时间用于接受输入,在 Python3 中它是一行代码。

input_list = list(int(x) for x in (input().split()))

But, couldn't find a solution in C++.但是,在 C++ 中找不到解决方案。

Is there a better way to do it in c++?在 c++ 中是否有更好的方法?

Take the help of std::istringstream :借助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;
}

How to take multiple integers in the same line as an input and store them in an array or vector in c++?如何将同一行中的多个整数作为输入并将它们存储在 c++ 中的数组或向量中?

Like this:像这样:

int arr[6]; for(int i=0;i<6;i++){ cin>>arr[i]; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM