[英]How to take multiple arrays as input in C++?
我一周前开始学习C ++,来自C。
我输入的内容具有以下格式:
7
13 -4 -10 4 9 7 -3
4
0 -2 -1 2
2
3 5
0
第一个数字给出第一个数组中元素的数量。 一旦该数字为零,我们将停止扫描阵列。
我想将这些数组扫描成数组,如下所示:
[[13,-4,-10,4,9,7,-3] , [0,-2,-1,2] , [3,5]]
我知道如何在第一个数组中进行扫描:
int n;
int array1[MAXLENGTH];
cin >> n;
for (int i = 0; i < n; i++) {
cin >> array1[i];
// scanf("%d", &array1[i]);
}
我陷入0 -2 -1 2
因为它从零开始。
我如何扫描这些数组并在遇到最后一个零时停止?
无论数据如何,输入模式都相同:
unsigned int array_index = 0U;
unsigned int quantity;
std::vector<std::vector<int> > database;
while (cin >> quantity)
{
if (quantity == 0U)
{
break;
}
int value = 0;
for (unsigned int i = 0; i < quantity; ++i)
{
cin >> value;
database[array_index].push_back(value);
}
++array_index;
}
向量的向量应该能够包含数据。
输入数据行:
4
0 -2 -1 2
4
代表第二组数字的数量。 0
是第二组数据的第一数据。
输入文件中有3组数据。
如其他答案所述,您应该有两个嵌套循环。
这是外循环:
std::vector<std::vector<int>> data;
while (true)
{
int size = 0;
std::cin >> size;
if (size == 0)
break;
std::vector<int> array;
... // fill the array
data.push_back(array);
}
C ++向量具有动态大小。 也就是说,在定义动态数组时,您不需要知道大小是多少-当元素添加到其中时,它会调整大小(使用push_back
)。 这对于外循环很方便。
但是,对于内部循环,使用预先分配的向量会更方便,因为您的代码会尽早“知道”数组的大小:
std::vector<int> array(size); // allocate the array and set all elements to zero
for (int i = 0; i < size; ++i)
{
std::cin >> array[i];
}
您还可以使用基于范围的循环:
std::vector<int> array(size); // allocate the array and set all elements to zero
for (int& value: array)
{
std::cin >> value;
}
int n;
int array1[MAXLENGTH];
while(true)
{
cin >> n;
if(n == 0) break;
for (int i = 0; i < n; i++) {
cin >> array1[i];
// scanf("%d", &array1[i]);
}
}
另外,当然您应该使用std :: vector,并且由于所有输入都存储在同一数组中而每次都会被覆盖,因此您将丢失输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.