简体   繁体   中英

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

Input: 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.

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

But, couldn't find a solution in C++.

Is there a better way to do it in c++?

Take the help of 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++?

Like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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