簡體   English   中英

如何將同一行中的多個整數作為輸入並將它們存儲在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM