C++ STL 中的 Array::fill() 和 array::swap()?
c++server side programmingprogramming更新于 2024/9/4 20:10:00
在本节中,我们将了解 C++ STL 中 array::fill() 和 array::swap() 的用法。
array::fill() 函数用于用某些指定值填充数组。让我们看一个例子来了解一下。
示例
#include<iostream> #include<array> using namespace std; main() { array<int, 10> arr = {00, 11, 22, 33, 44, 55, 66, 77, 88, 99}; cout << "数组元素:"; for(auto it = arr.begin(); it != arr.end(); it++){ cout << *it << " "; } //用 5 填充数组 arr.fill(5); cout << "\n填充后的数组元素:"; for(auto it = arr.begin(); it != arr.end(); it++){ cout << *it << " "; } }
输出
数组元素:0 11 22 33 44 55 66 77 88 99 填充后的数组元素:5 5 5 5 5 5 5 5 5 5
array::swap() 函数用于将一个数组的内容交换到另一个数组。让我们看一个例子来了解这个想法。
示例
#include<iostream> #include<array> using namespace std; main() { array<int, 10> arr1 = {00, 11, 22, 33, 44, 55, 66, 77, 88, 99}; array<int, 10> arr2 = {85, 41, 23, 65, 74, 02, 51, 74, 98, 22}; cout << "Array1 元素:"; for(auto it = arr1.begin(); it != arr1.end(); it++){ cout << *it << " "; } cout << "\nArray2 元素: "; for(auto it = arr2.begin(); it != arr2.end(); it++){ cout << *it << " "; } //交换数组元素 arr1.swap(arr2); cout << "\nArray1 元素 (交换后): "; for(auto it = arr1.begin(); it != arr1.end(); it++){ cout << *it << &" &";; } cout << &"\nArray2 元素(交换后): &";; for(auto it = arr2.begin(); it != arr2.end(); it++){ cout << *it << &" &";; } }
输出
Array1 元素:0 11 22 33 44 55 66 77 88 99 Array2 元素:85 41 23 65 74 2 51 74 98 22 Array1 元素(交换后):85 41 23 65 74 2 51 74 98 22 Array2 元素(交换后):0 11 22 33 44 55 66 77 88 99