priority_queue

Overview

estd::priority_queue is a type of queue container that arranges elements based on their priority. Elements with higher priority are retrieved prior to those with lower priority.

The estd::priority_queue operations e.g. push(), pop() use std::push_heap() & std::pop_heap() to maintain the priority.

The priority of estd::priority_queue is defined by the user-provided Comparator supplied to maintain the ordering, which defaults to std::less<T> and would cause the greatest element to appear as the top.

estd::priority_queue uses an encapsulated object of estd::vector (sequential container class) as its underlying container, providing a specific set of member functions to access and modify its elements.

Syntax

::estd::declare::priority_queue<T, N> pqueue_name;

Parameters

T

Type of elements of priority_queue.

N

Size of the priority_queue.

Usage

Below mentioned are the usage constraints and guidelines applicable for prority_queue.

Constraints

The priority_queue has a fixed max_size which is given at the time of declaration. This memory is allocated in stack.

Exceeding the maximum size will trigger an assertion.

Usage guidance

Size of priority_queue should be checked before accessing the elements.

Accessing elements from empty priority_queue using top() function will result in assertion.

Example

The below example shows the construction of priority_queue & its operations.

    // construction of a default estd::declare::priority_queue that stores up to 10 elements
    ::estd::declare::priority_queue<int32_t, 4> q;

    // top() & pop() operations will result in an error as priority_queue is empty
    // q.top(); q.pop();

    // push() elements in priority_queue
    q.push(20);

    // top() shows the highest priority element on priority_queue
    ASSERT_EQ(20, q.top());
    q.push(4);

    // size() shows the number of elements present in priority_queue
    ASSERT_EQ(2U, q.size());

    // max_size() shows the maximum number of elements priority_queue can hold
    ASSERT_EQ(4U, q.max_size());
    q.push(11);
    ASSERT_EQ(20, q.top());
    q.push(5);
    ASSERT_EQ(4U, q.size());
    ASSERT_EQ(4U, q.max_size());

    // push() operation will throw an error as priority_queue is full
    // q.push(12);

    q.pop();
    ASSERT_EQ(11, q.top());
    ASSERT_EQ(3U, q.size());
    ASSERT_EQ(4U, q.max_size());