กำหนดให้เป็นหน้าที่แสดงการทำงานของฟังก์ชัน forward_list::swap( ) ใน C++
รายการส่งต่อคืออะไร
รายการส่งต่อคือคอนเทนเนอร์ลำดับที่อนุญาตให้ดำเนินการแทรกและลบเวลาคงที่ที่ใดก็ได้ภายในลำดับ รายการส่งต่อถูกนำไปใช้เป็นรายการที่เชื่อมโยงแบบเดี่ยว การจัดลำดับจะถูกเก็บไว้โดยการเชื่อมโยงไปยังแต่ละองค์ประกอบของลิงก์ไปยังองค์ประกอบถัดไปในลำดับ
forward_list::swap() คืออะไร
forward_list::swap( ) เป็นฟังก์ชันในฟังก์ชันไลบรารีมาตรฐาน c++ ซึ่งใช้เพื่อสลับเนื้อหาของรายการหนึ่งไปยังรายการอื่นที่มีขนาดเท่ากันและประเภทข้อมูลเดียวกัน
ไวยากรณ์
forward_list1.swap(forward_list2)
หรือ
swap(forward_list first, forward_list second)
ตัวอย่าง
Output – First list : 57 99 54 34 84 Second list : 45 65 78 96 77 After swapping operation outputs are First list : 45 65 78 96 77 Second list : 57 99 54 34 84 Output – First list : 44 37 68 94 73 Second list : 20 11 87 29 40 After swapping operation outputs are First list : 20 11 87 29 40 Second list : 44 37 68 94 73
แนวทางสามารถติดตามได้
-
เริ่มต้นรายการส่งต่อทั้งสองก่อน
-
จากนั้นเราจะพิมพ์รายการส่งต่อทั้งสองรายการ
-
จากนั้นเราจะกำหนดฟังก์ชัน swap( )
-
จากนั้นเราจะพิมพ์รายการส่งต่อหลังจากสลับกัน
โดยใช้วิธีการข้างต้น เราสามารถสลับรายการส่งต่อทั้งสองรายการได้
อัลกอริทึม
เริ่ม -
STEP 1 – Intialize the two forward list and print them
First list forward_list<int> List1 = { 10, 20, 30, 40, 50 }
for( auto x = list1.start( ); x != list1.end( ); ++x )
cout<< *x << “ “ ;
second list forward_list<in> list2 = { 40, 30, 20, 10, 50 }
for( auto x = list2.start( ); x != list2.end( ); ++x )
cout<< *x << “ “ ;
END
STEP 2 – create the swap function to perform swap operation.
swap( list1, list2)
END
Stop ตัวอย่าง
// C++ code to demonstrate the working of forward_list::reverse( )
#include<iostream.h>
#include<forward_list.h>
Using namespace std;
Int main( ){
// initializing two forward lists
forward_list<int> list1 = { 10, 20, 30, 40, 50 }
cout<< “ Elements of List1:”;
for( auto x = list1.start( ); x != list1.end( ); ++x )
cout<< *x << “ “ ;
forward_list<int> list2 = { 40, 30, 20, 10, 50 }
cout<< “Elements of List2:”;
for( auto x = list2.start( ); x != list2.end( ); ++x )
cout<< *x << “ “ ;
// defining of function that performs the swap operation
swap(list1, list2);
cout<< “ After swapping List1 is :”;
for(auto x = list1.start( ); x != list1.end( ); ++x)
cout<< *x<< “ “;
cout<< “ After swapping List2 is :”;
for(auto x = list1.start( ); x!= list2.end( ); ++x)
cout<< *x<< “ “;
return 0;
} ผลลัพธ์
หากเรารันโค้ดด้านบน มันจะสร้างผลลัพธ์ต่อไปนี้
OUTPUT – Elements of List1 : 10 20 30 40 50 Elements of list2 : 40 30 20 10 50 After Swapping List1 : 40 30 20 10 50 After Swapping List2 : 10 20 30 40 50 OUTPUT – Elements of List1 : 23 56 78 49 11 Elements of List2 : 11 49 78 56 23 After Swapping List1 : 11 49 78 56 23 After Swapping List1 : 23 56 78 49 11