當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。