C ++ Array Library - ฟังก์ชัน swap ()

คำอธิบาย

ฟังก์ชัน C ++ std::array::swaps()สลับเนื้อหาของอาร์เรย์ วิธีนี้ใช้อาร์เรย์อื่นเป็นพารามิเตอร์และ exchage เนื้อหาของอาร์เรย์ทั้งสองในรูปแบบเชิงเส้นโดยดำเนินการสลับกับองค์ประกอบเหนี่ยวนำของอาร์เรย์

คำประกาศ

ต่อไปนี้เป็นคำประกาศสำหรับ std :: array :: swap () รูปแบบฟังก์ชัน std :: array header

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

พารามิเตอร์

arr - อาร์เรย์อื่นประเภทและขนาดเดียวกันซึ่งจะแลกเปลี่ยนเนื้อหา

ส่งคืนค่า

ไม่มี

ข้อยกเว้น

ไม่มี

ความซับซ้อนของเวลา

Linear คือ 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 ++

Language