array容器的创建、初始化、插入与遍历的使用方法
时间: 2023-12-10 14:06:12 浏览: 42
`std::array` 是一个 STL 容器,可以在 C++11 及以上版本中使用。与传统数组相比,`std::array` 具有更好的封装性和安全性,同时也支持迭代器和算法等 STL 特性。
以下是 `std::array` 的创建、初始化、插入和遍历的使用方法:
1. 创建 `std::array` 对象
可以使用以下语法创建一个 `std::array` 对象:
```
std::array<int, 5> arr;
```
此语句创建了一个名为 `arr` 的 `std::array` 对象,它包含 5 个 `int` 类型的元素。需要注意的是,`std::array` 的大小是固定的,一旦创建就不能改变。
2. 初始化 `std::array` 对象
可以使用以下语法初始化 `std::array` 对象:
```
std::array<int, 5> arr = {1, 2, 3, 4, 5};
```
此语句创建了一个名为 `arr` 的 `std::array` 对象,并将其初始化为包含整数 1、2、3、4、5 的数组。
3. 插入元素到 `std::array` 对象
由于 `std::array` 的大小是固定的,因此不能像 `std::vector` 那样动态地插入或删除元素。可以使用下标运算符来访问和修改 `std::array` 中的元素,例如:
```
arr[0] = 10;
```
以上语句将 `arr` 的第一个元素设置为 10。
4. 遍历 `std::array` 对象
可以使用传统的 for 循环或 C++11 提供的 for-each 循环遍历 `std::array` 对象,例如:
```
// 使用传统的 for 循环遍历 std::array
for (int i = 0; i < arr.size(); ++i) {
std::cout << arr[i] << " ";
}
// 使用 C++11 的 for-each 循环遍历 std::array
for (auto x : arr) {
std::cout << x << " ";
}
```
以上两个循环语句都可以遍历 `arr` 中的元素,并将它们依次输出到标准输出流中。
需要注意的是,`std::array` 的下标从 0 开始,最大下标为 `arr.size() - 1`。还可以使用 `std::array` 提供的迭代器和算法等 STL 特性来操作 `std::array` 对象,例如:
```
// 使用迭代器遍历 std::array
for (auto it = arr.begin(); it != arr.end(); ++it) {
std::cout << *it << " ";
}
// 使用 std::for_each() 算法遍历 std::array
std::for_each(arr.begin(), arr.end(), [](int x) {
std::cout << x << " ";
});
```
以上两个语句分别使用迭代器和算法来遍历 `arr` 中的元素,并将它们依次输出到标准输出流中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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://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)