std::set::operator=
#include <set>
// 1. Copy assignment operator
set& operator=(const set& other);
// 2. Move assignment operator (C++11)
set& operator=(set&& other);
// 3. Initializer list assignment operator (C++11)
set& operator=(initializer_list<value_type> ilist);
Gán nội dung của một std::set khác hoặc một initializer_list cho std::set hiện tại.
Tham số
other
- std::set nguồn cần gán.
ilist
- Danh sách khởi tạo chứa các phần tử cần gán.
Giá trị trả về
set&
- Tham chiếu đến std::set hiện tại (sau khi đã gán).
Đặc điểm
- Thay thế nội dung: Các toán tử gán thay thế toàn bộ nội dung hiện tại của std::set bằng nội dung mới.
- Copy vs. Move:
- Copy assignment tạo một bản sao độc lập của std::set nguồn.
- Move assignment di chuyển tài nguyên (dữ liệu) từ std::set nguồn sang std::set đích, làm cho std::set nguồn trở thành rỗng, hiệu quả hơn sao chép.
- Initializer list: Phiên bản gán từ danh sách khởi tạo cung cấp cách thức tiện lợi để gán các giá trị cố định cho std::set.
- Tự gán (self-assignment): Toán tử
operator=
được cài đặt để tự phát hiện và xử lý đúng các trường hợp tự gána = a;
- An toàn exception: Nếu exception xảy ra trong khi copy assignment đang copy các phần tử, set đích sẽ không bị thay đổi. Nếu exception xảy ra khi move assignment đang move các phần tử, thì set nguồn vẫn hợp lệ nhưng trạng thái không xác định.
- noexcept: Move assignment operator được đánh dấu là
noexcept
, nghĩa là nó được đảm bảo không ném ra ngoại lệ nào. - Độ phức tạp:
- Copy assignment: Độ phức tạp tuyến tính theo kích thước của std::set nguồn (
O(n)
). - Move assignment: Độ phức tạp thường là hằng số (
O(1)
). - Initializer list assignment: Độ phức tạp tuyến tính theo kích thước của danh sách khởi tạo (
O(n)
).
- Copy assignment: Độ phức tạp tuyến tính theo kích thước của std::set nguồn (
Ví dụ
#include <iostream>
#include <set>
int main() {
std::set<int> set1 = {1, 2, 3};
std::set<int> set2 = {4, 5};
std::set<int> set3;
// 1. Copy assignment
set3 = set1;
std::cout << "set3 after copy assignment from set1:";
for (int x : set3) std::cout << ' ' << x; // Output: set3 after copy assignment from set1: 1 2 3
std::cout << '\n';
// 2. Move assignment
set3 = std::move(set2);
std::cout << "set3 after move assignment from set2:";
for (int x : set3) std::cout << ' ' << x; // Output: set3 after move assignment from set2: 4 5
std::cout << '\n';
std::cout << "set2 after move assignment:";
for (int x : set2) std::cout << ' ' << x; // Output: set2 after move assignment: (empty)
std::cout << '\n';
// 3. Initializer list assignment
set3 = {7, 8, 9, 10};
std::cout << "set3 after initializer list assignment:";
for (int x : set3) std::cout << ' ' << x; // Output: set3 after initializer list assignment: 7 8 9 10
std::cout << '\n';
return 0;
}
Các hàm liên quan
insert | Chèn một phần tử mới vào std::set |