当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ Array swap()用法及代码示例



描述

C++ 函数std::array::swaps()交换数组的内容。该方法以其他数组为参数,通过对数组的单个元素进行交换操作,以线性方式交换两个数组的内容。

声明

以下是 std::array::swap() 函数形式 std::array 标头的声明。

void swap (array& arr) noexcept(noexcept(swap(declval<value_type&>(),declval<value_type&>())));

参数

arr- 另一个相同类型和大小的数组,其内容将被交换。

返回值

异常

时间复杂度

线性,即 O(n)

示例

下面的例子展示了 std::array::swap() 函数的用法。

#include <iostream>
#include <array>

using namespace std;

int main(void) {

   array<int, 3> arr1 = {10, 20, 30};
   array<int, 3> arr2 = {51, 52, 53};

   cout << "Contents of arr1 and arr2 before swap operation\n";
   cout << "arr1 = ";
   for (int &i:arr1) cout << i << " ";
   cout << endl;

   cout << "arr2 = ";
   for (int &i:arr2) cout << i << " ";
   cout << endl << endl;

   arr1.swap(arr2);

   cout << "Contents of arr1 and arr2 after swap operation\n";
   cout << "arr1 = ";
   for (int &i:arr1) cout << i << " ";
   cout << endl;

   cout << "arr2 = ";
   for (int &i:arr2) cout << i << " ";
   cout << endl;

   return 0;
}

让我们编译并运行上面的程序,这将产生以下结果——

Contents of arr1 and arr2 before swap operation
arr1 = 10 20 30 
arr2 = 51 52 53 

Contents of arr1 and arr2 after swap operation
arr1 = 51 52 53 
arr2 = 10 20 30 

相关用法


注:本文由纯净天空筛选整理自 C++ Array Library - swap() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。