额外的模板版亚历克赛·马利斯托夫的回答:
template <class T, class M, const M T::*member>
struct MemberGenericDereferenceLess
{
bool operator()(const T* lhs, const T* rhs) const
{
return ((*lhs).*member < (*rhs).*member);
}
};
typedef std::priority_queue<benchmark::vertex*,
std::vector<benchmark::vertex*>,
MemberGenericDereferenceLess<benchmark::vertex,
int,
&benchmark::vertex::cost> > q_type;
我以为你只需要第一个和第三个模板参数,但我无法推断
class M
几分钟的黑客攻击。(读者练习)
这样做的好处是您可以快速更改您排序的成员。假设你
vertex
看起来像…
namespace benchmark
{
struct vertex
{
vertex(double a_, double b_) : a(a_), b(b_) {}
double a;
double b;
int cost;
};
}
你可以让typedef排序
a
或
b
:
typedef std::priority_queue<benchmark::vertex*,
std::vector<benchmark::vertex*>,
MemberGenericDereferenceLess<benchmark::vertex,
double,
&benchmark::vertex::a> > q_type;
typedef std::priority_queue<benchmark::vertex*,
std::vector<benchmark::vertex*>,
MemberGenericDereferenceLess<benchmark::vertex,
double,
&benchmark::vertex::b> > q_type;
下面是一个小的驱动程序:
#include <iostream>
#include <queue>
#include <vector>
namespace benchmark
{
struct vertex
{
vertex(double a_, double b_) : a(a_), b(b_) {}
double a;
double b;
int cost;
};
}
template <class T, class M, const M T::*member>
struct MemberGenericDereferenceLess
{
bool operator()(const T* lhs, const T* rhs) const
{
return ((*lhs).*member < (*rhs).*member);
}
};
int main(int argc, char** argv)
{
typedef std::priority_queue<benchmark::vertex*,
std::vector<benchmark::vertex*>,
MemberGenericDereferenceLess<benchmark::vertex,
int,
&benchmark::vertex::cost> > q_type;
q_type q;
benchmark::vertex* v1 = new benchmark::vertex(0.1,0.1);
v1->cost = 4;
benchmark::vertex* v2 = new benchmark::vertex(0.1,0.1);
v2->cost = 8;
benchmark::vertex* v3 = new benchmark::vertex(0.1,0.1);
v3->cost = 6;
benchmark::vertex* v4 = new benchmark::vertex(0.1,0.1);
v4->cost = 10;
benchmark::vertex* v5 = new benchmark::vertex(0.1,0.1);
v5->cost = 2;
q.push(v1);
q.push(v2);
q.push(v3);
q.push(v4);
q.push(v5);
while(q.empty() == false)
{
std::cout << q.top()->cost << std::endl;
q.pop();
}
// Clean up all of those new()s
delete v1;
delete v2;
delete v3;
delete v4;
delete v5;
std::cin.get();
return 0;
}