priority_queue为复合结构排序:
#include <iostream>
#include <queue> using namespace std;
struct Node{
int x;
string y;
Node( int a= , string b = "" ):
x(a), y(b) {}
};
bool operator<( Node a, Node b ){ // 注意这里的顺序和sort()里面的谓词函数不一样!
// bool为真的 优先级小
if( a.x == b.x ) return a.y < b.y;
return a.x < b.x;
}
//自定义重载小于操作符
int main(){
/********************************************
对于自定义类型,则必须自己重载 operator<
自定义类型重载 operator< 后,声明对象时就可以只带一个模板参数。
看下面的例子
*******************************************/ cout<<"自定义: "<<endl;
priority_queue<Node> q2;
priority_queue<int> q3;
std::string tmp = ""; for( int i= ; i>; --i ){
tmp = tmp + "";
q2.push( Node(i, tmp) );
q3.push(i);
}
while( !q2.empty() ){
cout << q2.top().x << ' ' << q2.top().y << endl;
q2.pop();
}
while( !q3.empty() ){
cout << "q3 output: "<<q3.top() << endl;
q3.pop();
}
//注意上面不能这样来定义:priority_queue<Node, vector<Node>, greater<Node> >;
//这样定义是错误的!!!!
//原因是:greater<node>没有定义 //必须定义如下函数对象,才能这样定义:
// priority_queue<Node, vector<Node>, cmp >;
/*
struct cmp{
bool operator() ( Node a, Node b ){
if( a.x== b.x ) return a.y> b.y; return a.x> b.x; }
};
*/
return ;
} root@u18:~/cp/test# g++ priority.cpp -g -Wall
root@u18:~/cp/test# valgrind --tool=memcheck --leak-check=yes ./a.out
==== Memcheck, a memory error detector
==== Copyright (C) -, and GNU GPL'd, by Julian Seward et al.
==== Using Valgrind-3.7. and LibVEX; rerun with -h for copyright info
==== Command: ./a.out
====
自定义: q3 output:
q3 output:
q3 output:
q3 output:
q3 output:
q3 output:
q3 output:
q3 output:
q3 output:
q3 output:
====
==== HEAP SUMMARY:
==== in use at exit: bytes in blocks
==== total heap usage: allocs, frees, , bytes allocated
====
==== All heap blocks were freed -- no leaks are possible
====
==== For counts of detected and suppressed errors, rerun with: -v
==== ERROR SUMMARY: errors from contexts (suppressed: from )