从 stdio 获取一行空格分隔的整数,而不知道它们是多少 (C++)

Get a line of space-separated integers from stdio without knowing how much they are (C++)

本文关键字:不知道 C++ 多少 整数 分隔 获取 stdio 一行 空格      更新时间:2023-10-16

我正在处理一个竞争性的编程挑战,我必须从标准输入中获取一行空格分隔的整数,将它们放入数组中,并以某种方式处理它们。问题是我不知道在每个测试用例中我可能会得到多少个整数。 如果我知道,我的代码是这样的:

int n; // number of integers;
int arr[n];
for(int i = 0; i < n; i++)
cin >> arr[i];

如果我没有"n",我将如何实现同样的事情?

std::vector<int>基本上是一个动态大小的整数数组。你可以继续向它添加东西,它会根据需要增长。 如果给你一些元素作为第一个输入,你可以执行以下操作:

std::vector<int> items;
int count;
std::cin >> count;
// Preallocates room for the items. This is not necessary, it's just an optimization.
items.reserve(count);
while (count > 0) {
int item;
std::cin >> item;
items.push_back(item);
--count;
}

如果未提供项目数,只需读取直到读取失败:

std::vector<int> items;
int item;
while (std::cin >> item) {
items.push_back(item);
}

使用向量,因为向量的大小是动态的。继续将元素推入矢量,直到输入在那里。

std::vector<int> v; 
int temp; 
while (std::cin >> temp) { 
v.push_back(temp); 
}

何时将赋予n的值。您可以执行以下两个步骤中的任何一个:

步数:1

#include<iostream>
#include<vector>
using namespace std;
int main()
{
int n;
cin >> n; // Input n
vector<int>vv(n); // It will declare a vector(similar to an array) of size n
for(int i = 0; i < n; i++)
{
cin >> vv[i];
}
return 0;
}

步数:2

#include<iostream>
#include<vector>
using namespace std;
int main()
{
int n, number;
cin >> n; // Input n
vector<int>vv; // It will declare an empty vector
for(int i = 0; i < n; i++)
{
cin >> number; // Take a number as input
vv.push_back(number); // Put the input to the last of the vector
}
return 0;
}

何时不会为您提供n值:

#include<iostream>
#include<vector>
using namespace std;
int main()
{
int number;
vector<int>vv; // It will declare an empty vector.
while(cin >> number)
{
vv.push_back(number); // Push(put) the input to the back(end/last) of the vector
}
/* In case of reading input from a file,
the loop will continue until the end of the file.
When you'll try it from console, you need to enter
end-of-file command from keyboard.*/
return 0;
}
相关文章: