Detailed explanation of stack, queue and priority queue

stack

The stack pushes elements from the end of the underlying container and removes elements from the end of the underlying container. A stack can be thought of as a house with no front door, only a back door. After entering through the back door, those who enter later will exit through the back door first.

Insert image description here

Queue

The queue pushes elements to the tail of the underlying container and pops them from the front of the underlying container. The queue can be regarded as a place for ticket checking. After checking the ticket, you can get on the bus directly.

Insert image description here

So first in first out. First in First out.

Detailed explanation of priority queue

The priority queue is defined in the header file https://cplusplus.com/reference/queue/. There are two container classes in this header file, one is queue and the other is priority_queue. The first is a first-in-first-out queue, and the second is a priority queue.

A priority queue is a type of container adapter specifically designed so that its first element is always the "most priority" element it contains, and the priority standard is some strict weak ordering standard ( strict weak sequence criterion).

template<
    class T,
    class Container = std::vector<T>,
    class Compare = std::less<typename Container::value_type>
> class priority_queue;

The above is the template class definition of priority_queue. Compare provides a definition of "priority".

About Compare : If the first parameter of Compare is in front of the second parameter, it returns true. For example, the default parameter of the above template class is std::less, that is, the smaller number is in front, and the first one in the priority queue The (front) element is the largest element, so the element in front in the compare function is actually output later. That is, the front of the queue contains the elements at the back according to the weak ordering specified by Compare. Still taking less as an example, 2<3, 2 is in front of 3. Therefore, output after 2. It can be vividly remembered as: people on the left side of the less than number come first, and those who come first wait at the door of the ticket hall, leaving the front seats for the more respected people who come later.
Insert image description here

Guess you like

Origin blog.csdn.net/ChenglinBen/article/details/130973422