【问题标题】:How to take multiple integers in the same line as an input and store them in an array or vector in c++?如何在同一行中获取多个整数作为输入并将它们存储在 C++ 中的数组或向量中?
【发布时间】:2020-11-14 16:00:08
【问题描述】:

为了解决 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++ 中有更好的方法吗?

【问题讨论】:

  • 旁注:仅仅因为它是 python 中的一行并不意味着为每个生成的机器代码量不相似。
  • 在 C++ 中有很多更好的方法可以做到这一点。了解它们的最佳方式是read a good C++ textbook,而不是这些毫无意义的在线竞赛网站,它们在学习有价值的 C++ 技能方面几乎没有价值。他们似乎成功的只是教授了你不想拥有的糟糕的编程实践。
  • 无关:int arr[6]; for(int&amp; v : arr) cin &gt;&gt; v;
  • Python3 是一行代码。 但是执行那一行代码需要多长时间?不要陷入认为代码越少总是越快的陷阱。
  • 另一个加快程序速度的好方法是意识到您不必总是在处理数据之前存储它。通常,您可以将输入直接触发到正在进行的计算中。

标签: c++ performance vector input coding-efficiency


【解决方案1】:

求助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;
}

【讨论】:

  • 你应该使用std::istringstream而不是std::stringstream
  • @RemyLebeau 我已经更新了答案(9 小时前)。感谢您的建议。
【解决方案2】:

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

像这样:

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

【讨论】:

  • 同样的事情,只是代码看起来更小了。
  • @ShashankPrasad 我相信这正是 eerorika 试图提出的观点。深埋在input_list = list(int(x) for x in (input().split())) 的内部,将分配一个容器,一个循环,并在该循环中读取容器。这是不可避免的。 Python 只是用少量的字符来表达行为。
  • @ShashankPrasad 它在同一行。这是你要求的。
猜你喜欢
  • 2022-07-27
  • 1970-01-01
  • 2017-08-19
  • 2020-10-19
  • 2021-06-17
  • 2019-01-11
  • 1970-01-01
  • 1970-01-01
  • 2022-11-23
相关资源
最近更新 更多