[STL]priority_queue
由于merge k sorted lists要用到优先队列,所以参看各种博客。现在总结一下。
按默认规定,priority_queue简单地用 < <script type="math/tex" id="MathJax-Element-3"><</script>运算符做元素比较。
根据这里:
class mycomparison
{
bool reverse;
public:
mycomparison(const bool& revparam=false)
{reverse=revparam;}
bool operator() (const int& lhs, const int&rhs) const
{
if (reverse) return (lhs>rhs);
else return (lhs<rhs);
}
};
void testPQ()
{
int myints[]= {10,60,50,20};
priority_queue<int> first;
priority_queue<int> second (myints,myints+4);
priority_queue<int, std::vector<int>, std::greater<int> >
third (myints,myints+4);
// using mycomparison:
typedef std::priority_queue<int,vector<int>,mycomparison> mypq_type;
mypq_type fourth(myints,myints+4); // less-than comparison
mypq_type fifth (myints,myints+4, mycomparison(true)); // greater-than comparison
//empty
cout << "first: " << endl;
while (!first.empty())
{
cout << first.top() << " ";
first.pop();
}
cout << endl;
//default maxHeap
cout << "second: " << endl;
while (!second.empty())
{
cout << second.top() << " ";
second.pop();
}
cout << endl;
//minHeap
cout << "third: " << endl;
while (!third.empty())
{
cout << third.top() << " ";
third.pop();
}
cout << endl;
//less than maxHeap-DIY
cout << "fourth: " << endl;
while (!fourth.empty())
{
cout << fourth.top() << " ";
fourth.pop();
}
cout << endl;
//greater than minHeap-DIY
cout << "fifth: " << endl;
while (!fifth.empty())
{
cout << fifth.top() << " ";
fifth.pop();
}
cout << endl;
}
程序的输出结果:
first为空,second默认为最大堆,third用greater(要include <functional>
)变成最小堆,fourth和fifth用的都是自定义的比较函数,mycomparison是一个类,重载operator()。如果参数为true,即lhs>rhs,即greater,为最小堆。
对于自定义的类型,也同样可以插入优先队列。比如现在要把
struct Node
{
int val;
Node* next;
Node(int x) : val(x), next(NULL) {}
};
根据val值插入到最小堆(当然更准确的描述应该是val值越小,越先到达top())。
有两种方法:
- 改变node结构体,重载 < <script type="math/tex" id="MathJax-Element-4"><</script>,修改成:
struct Node
{
int val;
Node* next;
bool operator < (const Node &x) const {return val > x.val;}
Node(int x) : val(x), next(NULL) {}
};
测试函数:
void testPq()
{
priority_queue<Node, vector<Node>> pq;
int a[6] = {5, 6, 8, 10, 230, 0};
for (int i = 0; i < 6; i++)
pq.push(Node(a[i]));
while (!pq.empty())
{
Node temp = pq.top();
pq.pop();
cout << temp.val << " ";
}
cout << endl;
}
输出为:
2. 重新定义一个比较类。
class nodeComparison
{
//此函数要加上public。
//“>”说明是最小堆。“<”说明是最大堆
public: bool operator() (Node &n1, Node &n2)
{
return n1.val > n2.val;
}
};
测试函数同上。初始化priority_queue的时候有一点不同:
priority_queue<Node, vector<Node>, nodeComparison> pq;
如果要push进priority_queue的是Node型指针。则要定义一个比较类了:
class nodeComparison
{
//此函数要加上public。
//“>”说明是最小堆。“<”说明是最大堆
public: bool operator() (Node* n1, Node* n2)
{
return n1->val > n2->val;
}
};
综上,如果是基本内置类型,可以用less,greter或者再定义一个比较类,重载operator()。如果是自定义类型,则直接定义一个比较类。The CPP Languages P414,424
参考:
http://www.cnblogs.com/cszlg/archive/2012/07/27/2611607.html