- //
- // CopyRight(c) 2009, YOYO, All Rights Reserved.
- // Author: LIN YiQian
- // Created: 2009/08/24
- // Describe: STL priority_queue 使用DEMO
- //
- #include <iostream>
- #include <queue>
- #include <vector>
- #include <Windows.h>
- using namespace std;
- // 队列元素
- template <class T>
- class PriorityMessage
- {
- public:
- PriorityMessage(int priority, T objMessage): m_nPriority(priority), m_objMessage(objMessage)
- {
- LARGE_INTEGER liValue;
- ::QueryPerformanceCounter(&liValue);
- m_tInQueue = liValue.LowPart;
- }
- ~PriorityMessage()
- {
- }
- public:
- int m_nPriority;
- unsigned long m_tInQueue;
- T m_objMessage;
- };
- // 比较器
- template <class _Ty>
- struct PMessageCmp: public binary_function<_Ty, _Ty, bool>
- {
- bool operator()(const PriorityMessage<_Ty>& _Left, const PriorityMessage<_Ty>& _Right) const
- {
- if (_Left.m_nPriority != _Right.m_nPriority)
- {
- return _Left.m_nPriority < _Right.m_nPriority;
- }
- else
- {
- return _Left.m_tInQueue < _Right.m_tInQueue;
- }
- }
- };
- typedef PriorityMessage<string> STR_PM;
- typedef priority_queue<STR_PM, vector<STR_PM>, PMessageCmp<string> > STR_PMQ;
- void main(void)
- {
- STR_PMQ pmqStr;
- // 插入优先队列
- pmqStr.push(STR_PM(1, "level11"));
- pmqStr.push(STR_PM(3, "level31"));
- pmqStr.push(STR_PM(1, "level12"));
- pmqStr.push(STR_PM(2, "level21"));
- pmqStr.push(STR_PM(3, "level32"));
- pmqStr.push(STR_PM(4, "level41"));
- pmqStr.push(STR_PM(5, "level51"));
- pmqStr.push(STR_PM(2, "level23"));
- pmqStr.push(STR_PM(4, "level42"));
- pmqStr.push(STR_PM(1, "level13"));
- pmqStr.push(STR_PM(2, "level24"));
- pmqStr.push(STR_PM(4, "level43"));
- pmqStr.push(STR_PM(4, "level44"));
- // 打印优先队列
- while (!pmqStr.empty())
- {
- STR_PM& pmStr = pmqStr.top(); // 获取头部元素
- cout << "[LEVEL: " << pmStr.m_nPriority << "] "
- << "[QUEUE TIME: " << pmStr.m_tInQueue << "] "
- << "[MESSAGE: " << pmStr.m_objMessage.c_str() << "] " << endl;
- pmqStr.pop();
- }
- system("pause");
- }