Chuyển tới nội dung chính

std::forward_list::operator=

#include <forward_list>

// 1. Copy assignment operator
forward_list& operator=(const forward_list& other);

// 2. Move assignment operator (C++11)
forward_list& operator=(forward_list&& other);

// 3. Initializer list assignment operator (C++11)
forward_list& operator=(initializer_list<value_type> ilist);

Gán nội dung của một forward_list khác hoặc một danh sách khởi tạo cho forward_list hiện tại.

Tham số

other

  • forward_list 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ề

  • Tham chiếu đến forward_list hiện tại (sau khi đã gán).

Đặc điểm

  1. 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 forward_list bằng nội dung mới.
  2. Copy vs. Move:
    • Copy assignment: tạo một bản sao độc lập của forward_list nguồn.
    • Move assignment: di chuyển tài nguyên (dữ liệu) từ forward_list nguồn sang forward_list đích, làm cho forward_list nguồn trở thành rỗng, hiệu quả hơn sao chép.
  3. 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 forward_list.
  4. An toàn: Các toán tử gán của std::forward_list được thiết kế để hoạt động an toàn, bao gồm cả việc tự gán (self-assignment). Trong trường hợp tự gán, toán tử gán sẽ không làm gì cả.
  5. 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.
  6. Độ phức tạp:
    • Copy assignment: Độ phức tạp tuyến tính theo kích thước của forward_list 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)).

Ví dụ

#include <iostream>
#include <forward_list>

int main() {
std::forward_list<int> list1 = {1, 2, 3};
std::forward_list<int> list2 = {4, 5};
std::forward_list<int> list3;

// 1. Copy assignment
list3 = list1;
std::cout << "list3 after copy assignment from list1:";
for (int x : list3) std::cout << ' ' << x; // Output: list3 after copy assignment from list1: 1 2 3
std::cout << '\n';

// 2. Move assignment
list3 = std::move(list2);
std::cout << "list3 after move assignment from list2:";
for (int x : list3) std::cout << ' ' << x; // Output: list3 after move assignment from list2: 4 5
std::cout << '\n';
std::cout << "list2 after move assignment:";
for (int x : list2) std::cout << ' ' << x; // Output: list2 after move assignment: (empty)
std::cout << '\n';

// 3. Initializer list assignment
list3 = {7, 8, 9, 10};
std::cout << "list3 after initializer list assignment:";
for (int x : list3) std::cout << ' ' << x; // Output: list3 after initializer list assignment: 7 8 9 10
std::cout << '\n';

return 0;
}

Các hàm liên quan

assignGán các phần tử mới cho forward_list, thay thế nội dung hiện tại của nó