如何制作数组

How to make array

本文关键字:数组 何制作      更新时间:2023-10-16

我想在数组中创建n个数字元素。在第一行输入中,我要求给出元素的数量,在第二行输入实际元素。我试过这个代码

int main() {
int first_line;
cin >> first_line;
int second[first_line];
cin>>second;
cout<< second;

return 0;
}

输入应该看起来像

input
8
1 2 3 4 5 6 7 8
output
1 2 3 4 5 6 7 8

我需要第二行是整数数组。

数组(至少在C++中定义(根本无法满足您的要求。

你真正想要的是一个std::vector,它做得很好。

int main() {
int first_line;
cin >> first_line;
std::vector<int> second(first_line);
for (int i=0; i<first_line; i++) {
int temp;
cin>>temp;
second.push_back(temp);
}
for (auto i : second) {
cout<< i << ' ';
}
cout << "n";
return 0;
}

首先,您不能在C++中使用可变长度数组。因此,请使用std::矢量。

std::vector<int> second(first_line);

为了阅读,你需要在一个循环中cin,例如for循环。

执行留给OP作为一种惯例。

C++标准模板库中有几种集合类型,其中一种std::vector<>可以正常工作。

然而,如果你想使用一个具有简单数组机制和语法的数组,那么另一种选择是创建自己的数组,如下所示:

#include <iostream>
#include <memory>
int main() {
int first_line;
std::cin >> first_line;
int *second = new int[first_line];    // create an array, must manage pointer ourselves
// read in the element values
for (int i = 0; i < first_line; i++)
std::cin >> second[i];
// write out the element values with spaces as separators
for (int i = 0; i < first_line; i++)
std::cout << second[i] << "  ";
delete [] second;    // delete the array as no longer needed.
return 0;
}

使用std::unique_ptr<>来包含指向数组的指针将更方便、更安全,并且同样易于使用。使用std::unique_ptr<int[]> second( new int[first_line]);创建阵列,然后删除不再需要的delete[]。一旦数组超出范围,std::unique_ptr[]将负责删除该数组。