C ++ STL中的Array :: fill()和array :: swap()?
在本节中,我们将了解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 << "Array elements: "; for(auto it = arr.begin(); it != arr.end(); it++){ cout << *it << " "; } //用5填充数组 arr.fill(5); cout << "\nArray elements after fill: "; for(auto it = arr.begin(); it != arr.end(); it++){ cout << *it << " "; } }
输出结果
Array elements: 0 11 22 33 44 55 66 77 88 99 Array elements after fill: 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 elements: "; for(auto it = arr1.begin(); it != arr1.end(); it++){ cout << *it << " "; } cout << "\nArray2 elements: "; for(auto it = arr2.begin(); it != arr2.end(); it++){ cout << *it << " "; } //交换数组元素 arr1.swap(arr2); cout << "\nArray1 elements (After swap): "; for(auto it = arr1.begin(); it != arr1.end(); it++){ cout << *it << " "; } cout << "\nArray2 elements (After swap): "; for(auto it = arr2.begin(); it != arr2.end(); it++){ cout << *it << " "; } }
输出结果
Array1 elements: 0 11 22 33 44 55 66 77 88 99 Array2 elements: 85 41 23 65 74 2 51 74 98 22 Array1 elements (After swap): 85 41 23 65 74 2 51 74 98 22 Array2 elements (After swap): 0 11 22 33 44 55 66 77 88 99