list::assign() gán nội dung mới cho list, thay thế hoàn toàn nội dung cũ. Có 3 dạng:
Các dạng cú pháp
lst.assign(count, value)-countphần tử giá trịvaluelst.assign(first, last)- copy từ range [first, last)lst.assign(initializer_list)- từ danh sách khởi tạo {a, b, c}
Chương trình mẫu
#include <iostream>
#include <list>
using namespace std;
void ShowList(const list<int>& L) {
cout << "Elements: ";
for (int x : L) cout << x << " ";
cout << endl;
}
int main() {
list<int> L1, L2, L3;
int arr[10] = {6, 7, 2, 4};
// 1. Gán size=3, value=20
L1.assign(3, 20);
cout << "L1 size: " << L1.size() << endl;
ShowList(L1);
// 2. Copy từ L1
L2.assign(L1.begin(), L1.end());
cout << "L2 size: " << L2.size() << endl;
ShowList(L2);
// 3. Copy 4 phần tử từ mảng
L3.assign(arr, arr + 4);
cout << "L3 size: " << L3.size() << endl;
ShowList(L3);
return 0;
}
Kết quả
L1 size: 3 Elements: 20 20 20 L2 size: 3 Elements: 20 20 20 L3 size: 4 Elements: 6 7 2 4
Đặc điểm:
- Hủy tất cả phần tử cũ, tạo phần tử mới
- Invalidates tất cả iterator, reference, pointer đến phần tử cũ
- Độ phức tạp: O(n) với n = số phần tử mới
- Ngoại lệ: strong guarantee (nếu throw, list không đổi)
Lưu ý: Dạng range assign(first, last) yêu cầu InputIterator. Với mảng C-style, dùng pointer như iterator.