C++ 標准模板庫STL 隊列 queue 使用方法與應用介紹
queue
queue模板類的定義在<queue>頭文件中。
與stack模板類很相似,queue模板類也需要兩個模板參數,一個是元素類型,一個容器類型,元素類型是必要的,容器類型是可選的,默認為deque類型。
定義queue對象的示例代碼如下:
queue<int> q1;
queue<double> q2;
queue的基本操作有:
入隊,如例:q.push(x); 將x接到隊列的末端。
出隊,如例:q.pop(); 彈出隊列的第一個元素,注意,並不會返回被彈出元素的值。
訪問隊首元素,如例:q.front(),即最早被壓入隊列的元素。
訪問隊尾元素,如例:q.back(),即最后被壓入隊列的元素。
判斷隊列空,如例:q.empty(),當隊列空時,返回true。
訪問隊列中的元素個數,如例:q.size()
std::queue
queues are a type of container adaptor, specifically designed to operate in a FIFO context (first-in first-out), where elements are inserted into one end of the container and extracted from the other.
queues are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are pushed into the "back" of the specific container and popped from its "front".
The underlying container may be one of the standard container class template or some other specifically designed container class. The only requirement is that it supports the following operations:
- front()
- back()
- push_back()
- pop_front()
Therefore, the standard container class templates deque and list can be used. By default, if no container class is specified for a particular queue class, the standard container class template deque is used.
In their implementation in the C++ Standard Template Library, queues take two template parameters:
|
|
Where the template parameters have the following meanings:
- T: Type of the elements.
- Container: Type of the underlying container object used to store and access the elements.
In the reference for the queue member functions, these same names are assumed for the template parameters.