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

std::priority_queue::size

#include <queue>

size_type size() const;

Trả về số lượng phần tử hiện có trong std::priority_queue.

Tham số

Không có tham số

Giá trị trả về

  • Trả về một giá trị kiểu size_type, thường là std::size_t, là một kiểu số nguyên không dấu, đại diện cho số lượng phần tử hiện có trong std::priority_queue.

Đặc điểm

  1. const: size() là một hàm const, nghĩa là nó không thay đổi trạng thái của std::priority_queue.
  2. Dựa trên underlying container: size() của std::priority_queue thực chất gọi hàm size() của underlying container (ví dụ: std::vector mặc định).
  3. Không ném ngoại lệ: Hàm size() được quy định không ném ra ngoại lệ.
  4. Độ phức tạp: O(1) - thời gian hằng số. Việc lấy kích thước của std::priority_queue rất nhanh chóng.

Ví dụ

#include <iostream>
#include <queue>

int main() {
std::priority_queue<int> mypq;

std::cout << "Initial size: " << mypq.size() << '\n'; // Output: Initial size: 0

mypq.push(10);
mypq.push(20);
mypq.push(30);

std::cout << "Size after pushing elements: " << mypq.size() << '\n'; // Output: Size after pushing elements: 3

mypq.pop();

std::cout << "Size after popping an element: " << mypq.size() << '\n'; // Output: Size after popping an element: 2

return 0;
}

Các hàm liên quan

emptyKiểm tra xem std::priority_queue có rỗng hay không