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 << " "; } //fill array with 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 << " "; } //swap array elements 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
广告