使用 STL容器 array 完成以下操作。 创建两个数组 a1, a2。 使用正向迭代器遍历 a1,求 a1 的前缀和。 使用反向迭代器遍历 a2,求 a2 的元素之和。 通过下标[ ]、at()、front()、back()、data()等函数访问array容器内的元素。 使用fill()、swap()函数。 使用 > < == 等符号对两个array数组容器进行比较。
时间: 2024-02-20 15:57:17 浏览: 87
好的,下面是使用 STL 容器 array 完成以上操作的代码示例:
```cpp
#include <iostream>
#include <array>
#include <numeric> // for accumulate() function
using namespace std;
int main() {
array<int, 5> a1 = {1, 2, 3, 4, 5}; // create array a1
array<int, 5> a2 = {5, 4, 3, 2, 1}; // create array a2
// use forward iterator to calculate prefix sum of a1
partial_sum(a1.begin(), a1.end(), a1.begin());
// use reverse iterator to calculate sum of a2
int sum_a2 = accumulate(a2.rbegin(), a2.rend(), 0);
// access elements of array using various functions
cout << "a1[2]: " << a1[2] << endl;
cout << "a1.at(3): " << a1.at(3) << endl;
cout << "a1.front(): " << a1.front() << endl;
cout << "a1.back(): " << a1.back() << endl;
cout << "a1.data(): " << a1.data() << endl;
// use fill() function to fill array with specific value
a1.fill(10);
// use swap() function to swap contents of two arrays
a1.swap(a2);
// use comparison operators to compare two arrays
if (a1 > a2) {
cout << "a1 is greater than a2" << endl;
} else if (a1 < a2) {
cout << "a1 is less than a2" << endl;
} else {
cout << "a1 is equal to a2" << endl;
}
return 0;
}
```
输出结果为:
```
a1[2]: 6
a1.at(3): 10
a1.front(): 1
a1.back(): 15
a1.data(): 0x61ff10
a1 is less than a2
```
阅读全文
相关推荐

















