Cpp-standard-library-cpp-array-swap

提供:Dev Guides
移動先:案内検索

C ++配列ライブラリ-swap()関数

説明

C ++関数* std
array :: swaps()*は、配列の内容をスワップします。 このメソッドは、他の配列をパラメーターとして使用し、配列のinduvisual要素でスワップ操作を実行することにより、両方の配列の内容を線形に交換します。

宣言

以下は、std
arrayヘッダーからのstd :: array :: swap()関数の宣言です。
void swap (array& arr) noexcept(noexcept(swap(declval<value_type&>(),declval<value_type&>())));

パラメーター

*arr* -内容が交換される同じタイプとサイズの別の配列。

戻り値

None

例外

None

時間の複雑さ

線形、すなわち 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