forward_list::assign() gán giá trị mới cho forward_list, thay thế hoàn toàn nội dung cũ.
3 dạng cú pháp
flist.assign(initializer_list)- gán từ danh sách khởi tạoflist.assign(iterator first, iterator last)- copy từ khoảng [first, last)flist.assign(count, value)- gáncountphần tử mang giá trịvalue
Ví dụ
#include <forward_list>
#include <iostream>
using namespace std;
int main() {
forward_list<int> Lt1, Lt2, Lt3;
// 1. Gán từ initializer list
Lt1.assign({4, 9, 7, 8});
// 2. Gán 3 phần tử giá trị 6
Lt2.assign(3, 6);
// 3. Copy từ Lt1
Lt3.assign(Lt1.begin(), Lt1.end());
// In kết quả
cout << "Lt1: "; for (int& x : Lt1) cout << x << " "; cout << endl;
cout << "Lt2: "; for (int& x : Lt2) cout << x << " "; cout << endl;
cout << "Lt3: "; for (int& x : Lt3) cout << x << " "; cout << endl;
return 0;
}
Kết quả
Lt1: 4 9 7 8 Lt2: 6 6 6 Lt3: 4 9 7 8
Đặc điểm: Hàm không trả về giá trị. Tất cả phần tử cũ bị hủy, phần tử mới được cấu trúc. Độ phức tạp: O(n) với n là số phần tử mới.