问题描述
嗨^ _ ^
我们可以输入
Hi ^_^
we can type
array <int , 10> s = {0};
声明一维数组,现在我该如何声明一个二维数组用这种方式?另一方面,
如何使用这种方式声明动态数组(我的意思是让用户在运行程序后输入数组长度的方法是什么(1D和2D数组)) ?
非常感谢提前。
to declaration a 1D array, now how do I can declare a 2D array using this way ?
on the other hand how do i can declare a dynamic array using this way (I mean what is the way to let user type the length of the array after running the program (1D and 2D array)) ?
many thanks in advance.
推荐答案
#include <array>
...
using namespace std;
...
enum { OUTER = 3, INNER = 2 };
array<array<int, INNER>, OUTER> a = { {{ 1, 2 }, { 3, 4 }, { 5, 6 }} } ;
for(size_t outer = 0; outer < OUTER; ++outer) {
for(size_t inner = 0; inner < INNER; ++inner) {
cout << "a[" << outer << "][" << inner << "] = " << a[outer][inner] << endl;
}
}
结果:
a[0][0] = 1
a[0][1] = 2
a[1][0] = 3
a[1][1] = 4
a[2][0] = 5
a[2][1] = 6
除了外括号之外,您可以将所有元素保留为平面元素序列。
参见 []和引用的 []修复缺陷。
For动态数组你可以使用嵌套 std :: vector
s。
问候
Andi
You may leave away all but the outer braces and initialize the array as flat sequence of elements.
See also http://stackoverflow.com/questions/17759757/multidimensional-stdarray[^] and the referenced C++14 proposal[^] to fix that "defect".
For dynamic "arrays" you may use nested std::vector
s.
Regards
Andi
这篇关于如何使用数组文件声明动态数组和2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!