acm的STL容器之隊列篇
優先隊列,即Priority Queues
1.簡單介紹一下隊列(介紹功能,不作分析)
C++隊列是一種容器適配器,它給予程序員一種先進先出(FIFO)的數據結構。
1.back() 返回一個引用,指向最後一個元素
2.empty() 如果隊列空則返回真
3.front() 返回第一個元素
4.pop() 刪除第一個元素
5.push() 在末尾加入一個元素
6.size() 返回隊列中元素的個數
簡介:隊列可以用線性表(list)或雙向隊列(deque)來實現(註意vector container 不能用來實現queue,因為vector 沒有成員函數pop_front!):
queue<list<int>> q1;
queue<deque<int>> q2;
其成員函數有“判空(empty)” 、“尺寸(Size)” 、“首元(front)” 、“尾元(backt)” 、“加入隊列(push)” 、“彈出隊列(pop)”等操作。
int main() { queue<int> q; q.push(4); q.push(5); printf("%d\n",q.front()); q.pop(); }
2.Priority Queues(優先隊列)
C++優先隊列類似隊列,但是在這個數據結構中的元素按照一定的斷言排列有序。
1.empty() 如果優先隊列為空,則返回真
2.pop() 刪除第一個元素
3.push() 加入一個元素
4.size() 返回優先隊列中擁有的元素的個數
5.top() 返回優先隊列中有最高優先級的元素
優先級隊列可以用向量(vector)或雙向隊列(deque)來實現(註意list
container 不能用來實現queue,因為list 的叠代器不是任意存取iterator,而pop
中用到堆排序時是要求randomaccess iterator 的!):
priority_queue<vector<int>, less<int>> pq1; // 使用遞增less<int>函數對象排序
priority_queue<deque<int>, greater<int>> pq2; // 使用遞減greater<int>函數對象排序
其成員函數有“判空(empty)” 、“尺寸(Size)” 、“棧頂元素(top)” 、“壓棧(push)” 、“彈棧(pop)”等。
1 #include <iostream> 2 #include <queue> 3 using namespace std; 4 5 class T { 6 public: 7 int x, y, z; 8 T(int a, int b, int c):x(a), y(b), z(c) 9 { 10 } 11 }; 12 bool operator < (const T &t1, const T &t2) 13 { 14 return t1.z < t2.z; // 按照z的順序來決定t1和t2的順序15 } 16 main() 17 { 18 priority_queue<T> q; 19 q.push(T(4,4,3)); 20 q.push(T(2,2,5)); 21 q.push(T(1,5,4)); 22 q.push(T(3,3,6)); 23 while (!q.empty()) 24 { 25 T t = q.top(); 26 q.pop(); 27 cout << t.x << " " << t.y << " " << t.z << endl; 28 } 29 return 1; 30 }
(待完善)
acm的STL容器之隊列篇