从 stdio 获取一行空格分隔的整数,而不知道它们是多少 (C++)
Get a line of space-separated integers from stdio without knowing how much they are (C++)
我正在处理一个竞争性的编程挑战,我必须从标准输入中获取一行空格分隔的整数,将它们放入数组中,并以某种方式处理它们。问题是我不知道在每个测试用例中我可能会得到多少个整数。 如果我知道,我的代码是这样的:
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;
}
相关文章:
- 努力将整数转换为链表。不知道我在这里做错了什么
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 叮当不知道PTRDIFF_MAX?
- 如何在不知道向量大小的情况下输入向量内部的向量?
- 我正在尝试使用 c++ 创建一个货币转换程序,我不知道如何继续
- 不知道某个东西是否被忽略会引入未定义的行为吗
- 如何在C++中读取空格分隔的输入 当我们不知道输入的数量时
- 我不知道这条线是做什么的
- 如何在不知道C++中有多少可选参数的情况下在循环中使用va_arg?
- 在不知道套接字的情况下关闭网络连接
- 如果我不知道每个列表中有多少个数字,我如何将给定数量的数字列表作为输入?
- 我不知道导致错误的原因 (C3074)
- 我不知道为什么这段代码会让核心被转储?
- 我正在尝试制作一个自平衡机器人,但编译时存在错误。我不知道如何解决它
- 循环通过网格获取温度,但不知道如何告诉程序停止循环
- 如何在不知道对应关系的情况下在字符串中搜索字符并将其分配给另一个字符?
- 反转字符串.不知道为什么这个逻辑是错误的.C++
- 不知道如何在家庭作业任务中实现一件事
- 如何在不知道属性具有哪些构造函数的情况下初始化属性?