deque::assign() gán nội dung mới cho deque (double-ended queue), thay thế hoàn toàn dữ liệu cũ. Deque hỗ trợ truy cập ngẫu nhiên và chèn/xóa đầu/cuối O(1).
Các dạng cú pháp
deq.assign(count, value)-countphần tử giá trịvaluedeq.assign(first, last)- copy từ range [first, last)deq.assign(initializer_list)- từ danh sách {a, b, c} (C++11)
Ví dụ 1: Gán count-value
#include <bits/stdc++.h>
using namespace std;
int main() {
deque<int> deq;
deq.assign(5, 1); // 5 phần tử giá trị 1
cout << "deque elements: ";
for (auto it = deq.begin(); it != deq.end(); ++it)
cout << *it << " ";
return 0;
}
Kết quả
deque elements: 1 1 1 1 1
Ví dụ 2: Gán từ range iterator
#include <bits/stdc++.h>
using namespace std;
int main() {
deque<int> deq;
deq.assign(5, 2); // {2,2,2,2,2}
deque<int> deq1;
// Copy từ phần tử thứ 3 (index 2) đến hết
deq1.assign(deq.begin() + 2, deq.end());
cout << "deq: "; for (int x : deq) cout << x << " ";
cout << "\ndeq1: "; for (int x : deq1) cout << x << " ";
return 0;
}
Kết quả
deq: 2 2 2 2 2 deq1: 2 2 2
Giải thích: deq.begin() + 2 trỏ đến phần tử index 2 (phần tử thứ 3). Copy 3 phần tử còn lại.
Đặc điểm
- Hủy phần tử cũ, tạo phần tử mới
- Invalidates tất cả iterator/reference/pointer cũ
- O(n) thời gian, n = số phần tử mới
- Deque iterator hỗ trợ random access (+, -, [], <)