priority_queue是STL容器,會按照自己所指定的排序方式存在此容器中,它的樣板聲明帶有三個參數
priority_queue<Type, Container, Functional> |
Type為類別型態,Container為儲存容器的型態,Functional為元素比較的方式。
Container必須為vector或是deque,預設是vector。
範例一:
#include <iostream>
#include <queue>
using namespace std;
int main()
{
priority_queue<int> p;
int numbers[10] = {3, 6, 5, 555, 211, 321, 48, 99, 6773, 4};
for(int i=0; i<10; i++)
{
p.push(numbers[i]);
}
while(!p.empty())
{
cout << p.top() << " ";
p.pop();
}
return 0;
}
Output:
6773 555 321 211 99 48 6 5 4 3
Functional的型式,STL有做了兩個仿函數,less為由大排到小,greater為由小排到大,
若是為自定義的類別,那麼就要重載>或<運算子,也可以自己寫個仿函數進去,例如:
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
class CTest
{
public:
CTest();
~CTest();
CTest(const CTest& rhs) {m_test = rhs.GetTest();}
CTest& operator=(const CTest& rhs) {m_test = rhs.GetTest(); return *this;}
void SetTest(const int input} {m_test = input;}
int GetTest() const {return m_test;}
// overloadding
friend bool operator>(const CTest& lhs, const CTest& rhs) {return lhs.GetTest() > rhs.GetTest();}
private:
int m_test;
};
// functor = function object
struct cmp
{
bool operator() (const CTest& lhs, const CTest& rhs) {return lhs.GetTest() < rhs.GetTest();}
};
int main()
{
CTest XD[10];
// p_greater使用自定義的類別,採用greater<T>
priority_queue< CTest, vector<CTest>, greater<CTest> > p_greater;
// p_functors使用自定義的類別,採用仿函數
priority_queue< CTest, vector<CTest>, cmp > p_functors;
int numbers[10] = { 3, 6, 5, 555, 211, 321, 48, 99, 6773, 4};
for(int i=0; i<10; i++)
{
XD[i].SetTest(numbers[i]);
p_greater.push(XD[i]);
p_functors.push(XD[i]);
}
cout << "Greater: " << endl;
while(!p_greater.empty())
{
cout << p_greater.top().GetTest() << " ";
p_greater.pop();
}
cout << endl << "Functors:" << endl;
while(!p_functors.empty())
{
cout << p_functors.top().GetTest() << " ";
p_functors.pop();
}
return 0;
}
Output:
Greater:
3 4 5 6 48 99 211 321 555 6773
Functors:
6773 555 321 211 99 48 6 5 4 3
有趣且重要的一個容器,記起來~