C++ 中"priority_queue" 優(yōu)先級隊列實例詳解
C++ 中"priority_queue" 優(yōu)先級隊列實例詳解
1. 簡介
標準庫隊列使用了先進先出(FIFO)的存儲和檢索策略. 進入隊列的對象被放置在尾部, 下一個被取出的元素則取自隊列的首部. 標準庫提供了兩種風格的隊列: FIFO 隊列(FIFO queue, 簡稱 queue), 以及優(yōu)先級隊列(priority queue).
priority_queue 允許用戶為隊列中存儲的元素設(shè)置優(yōu)先級. 這種隊列不是直接將新元素放置在隊列尾部, 而是放在比它優(yōu)先級低的元素前面. 標準庫默認使用元素類型的 "<" 操作符來確定它們之間的優(yōu)先級關(guān)系. 如需改變大小關(guān)系, 需要使用std::greater<temple>函數(shù), 在functional頭文件中.
2. 代碼
#include <iostream> // std::cout #include <queue> // std::priority_queue #include <vector> // std::vector #include <functional> // std::greater int main () { int myints[]= {10,60,50,20}; std::priority_queue<int> intPQueue1 (myints, myints+4); std::priority_queue<int, std::vector<int>, std::greater<int> > intPQueue2 (myints,myints+4); std::cout << "less than: " << std::endl; while( !intPQueue1.empty() ){ int pvalue = intPQueue1.top(); std::cout << pvalue << " "; intPQueue1.pop(); } std::cout << std::endl; std::cout << "bigger than: " << std::endl; while( !intPQueue2.empty() ){ int pvalue = intPQueue2.top(); std::cout << pvalue << " "; intPQueue2.pop(); } std::cout << std::endl; return 0; }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
C++時間戳轉(zhuǎn)化操作實例分析【涉及GMT與CST時區(qū)轉(zhuǎn)化】
這篇文章主要介紹了C++時間戳轉(zhuǎn)化操作,結(jié)合實例形式分析了C++時間戳轉(zhuǎn)換與顯示操作的原理與具體實現(xiàn)技巧,涉及GMT與CST時區(qū)轉(zhuǎn)化,需要的朋友可以參考下2017-05-05C語言根據(jù)協(xié)議分割獲取字符串單元的實現(xiàn)代碼
今天小編就為大家分享一篇關(guān)于C語言根據(jù)協(xié)議分割獲取字符串單元的實現(xiàn)代碼,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-12-12