如何使用array定义多维数组?
时间: 2024-10-14 21:17:00 浏览: 41
在C++中,`std::array` 类型可以用来定义固定大小的多维数组,相比于 `std::vector`,它的内存是静态分配的,因此对于已知大小且不常改变的情况,`std::array` 提供了更好的性能和内存效率。以下是如何使用 `std::array` 定义多维数组的例子:
1. **一维数组**:
```cpp
std::array<int, 10> arr1D; // 创建一个包含10个int的数组
```
2. **二维数组**:
```cpp
std::array<std::array<int, 3>, 4> arr2D; // 创建一个4行3列的二维数组
// 或者更明确地指定类型和大小
std::array<std::array<int, 3>, 4> arr2D = {{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, {{10, 11, 12}, {13, 14, 15}, {16, 17, 18}}};
```
3. **三维数组**:
```cpp
std::array<std::array<std::array<int, 2>, 2>, 2> arr3D; // 创建一个2x2x2的三维数组
```
使用时,你可以像操作普通数组一样对这些多维 `std::array` 进行索引,例如:
```cpp
arr2D = 100; // 修改第二个子数组的第三个元素
```
注意,由于 `std::array` 的大小在编译时确定,如果尝试超出范围访问,会触发运行时错误。所以在使用时一定要确保索引不会越界。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)