บทนำ
งานนี้แสดงการทำงานของ list::assign() ใน C++
list::assign() เป็นส่วนหนึ่งของ C++ STL ใช้กำหนดค่าให้ลิสต์ และคัดลอกค่าจากลิสต์หนึ่งไปอีกลิสต์หนึ่ง
ต้อง include <list>
Syntax
รูปแบบสำหรับกำหนดค่าใหม่:
List_Name.assign(size, value)
รูปแบบสำหรับคัดลอกจากลิสต์อื่น:
First_List.assign(Second_List.begin(), Second_List.end())
Parameters
- Size - ขนาดของลิสต์
- Value - ค่าที่จะเก็บในทุกตำแหน่ง
Return Value
ไม่คืนค่า
ตัวอย่าง
Input: Lt.assign(3, 10) Output: Size = 3, Elements: 10 10 10
ค่าที่ 1 = size, ค่าที่ 2 = value ทุกตำแหน่ง
Input: int array[5] = {1,2,3,4}; Lt.assign(array, array+3)
Output: Size = 3, Elements: 1 2 3
คัดลอกจากอาร์เรย์ 3 ตัวแรก ถ้าระบุมากกว่าขนาดอาร์เรย์ ตัวแปรเพิ่มจะเป็น 0
แนวทางในโปรแกรม
- สร้างฟังก์ชัน ShowList(list<int> L) แสดงลิสต์
- สร้าง iterator itr วนลูปพิมพ์
- ใน main(): สร้าง L1, L2, L3 และอาร์เรย์ arr[]
- assign() ให้ L1 ด้วย size, value → แสดง
- assign() คัดลอก L1 → L2 → แสดง
- assign() คัดลอก arr[] → L3 → แสดง
อัลกอริทึม
Start
Step 1 → Declare function DisplayList(list<int> L)
Declare iterator itr
Loop itr = L.begin() to itr != L.end() itr++
Print *itr
End
Step 2 → In main()
Declare L1, L2, L3
Initialize arr[]
Call L1.assign(size, value)
Print L1.size()
Call DisplayList(L1)
Call L2.assign(L1.begin(), L1.end())
Print L2.size()
Call DisplayList(L2)
Call L3.assign(arr, arr+4)
Print L3.size()
Call DisplayList(L3)
Stop
ตัวอย่างโค้ด
#include <iostream>
#include <list>
using namespace std;
int ShowList(list<int> L) {
cout << "The elements of the list are ";
list<int>::iterator itr;
for (itr = L.begin(); itr != L.end(); itr++) {
cout << *itr << " ";
}
cout << "\n";
}
int main() {
list<int> L1, L2, L3;
int arr[10] = { 6, 7, 2, 4 };
L1.assign(3, 20);
cout << "The size of list L1 is " << L1.size() << "\n";
ShowList(L1);
L2.assign(L1.begin(), L1.end());
cout << "The size of list is L2 " << L2.size() << "\n";
ShowList(L2);
L3.assign(arr, arr + 4);
cout << "The size of list is L3 " << L3.size() << "\n";
ShowList(L3);
return 0;
}
ผลลัพธ์
The size of list L1 is 3 The elements of the list are 20 20 20 The size of list L2 is 3 The elements of the list are 20 20 20 The size of list L3 is 4 The elements of the list are 6 7 2 4
คำอธิบาย
L1: assign(3, 20) → size 3, ค่า 20 ทุกตัว
L2: คัดลอกจาก L1 → size และค่าเหมือน L1
L3: คัดลอกจาก arr[] 4 ตัวแรก → size 4, ค่าเหมือน arr