如何制作数组
How to make array
我想在数组中创建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[]
将负责删除该数组。
相关文章:
- 如何使用用户输入变量制作二维数组?
- 如何制作一个地图,其中的值是C++中的结构数组
- 如何制作不允许重复值的 C++ int 数组循环?
- 如何制作一个作为类对象并具有编译时大小的数组?
- 如何在使用 make_unique<T[]>() 制作的模板类型数组上使用 std::fill?
- 如何在类中制作 2D 数组元素,然后在其构造函数中指定其维度?
- 从矢量数组制作平面文件
- 如何为包含另一个类实例的数组制作常量 getter?
- 如何制作数组
- 如何使函数返回数组?用于制作在VB.NET中使用的DLL
- OpenCv 在C++中从 1 D 数组制作垫子图像的最快方法
- 在编译时使用数组中的字符串制作杂注
- 有没有一种递归的方式来制作这个字符串数组?
- 如何制作一个容纳unique_ptrs的数组?
- Turbo 如何在 Tubo C++ 中制作一个可变大小的数组
- C++:使用数组、指针和 for 循环制作直方图。我就在那里,我可能想得太辛苦了
- 如何使用数组制作随机分数生成器
- 用反向订单编号制作数组
- 如何使用New在C 中制作一个长的双1D数组
- 如何使用并行数组使用 c++ 制作包含数量和单词的列表