我定义的结构如下:
using namespace std;
struct Person {
int id;
int age;
string country_of_origin;
};
并且正在尝试使用STL优先级队列类根据id对人员进行升序排序,并根据来源国按字典顺序对匹配id的值进行排序。下面是我的代码:
#include <queue>
#include <vector>
#include <iostream>
#include <queue>
#include <string>
using namespace std;
struct Person {
int id;
int age;
string country_of_origin;
};
struct PersonCompare
{
bool operator()(const Person &p1, const Person &p2) const
{
if (p1.id>p2.id) {
return true;
} else if (p1.country_of_origin>p2.country_of_origin){
return true;
} else {
return false;
}
}
};
int main(int argc, char ** argv)
{
Person p={1,2,"Zimbabwe"};
Person q={3,4,"New Zealand"};
Person r={5,7,"Wales"};
Person s={2,3,"India"};
Person t={1,4,"Sri Lanka"};
Person u={1,4,"Benin"};
priority_queue<Person,vector<Person>,PersonCompare> queue;
queue.push(p);
queue.push(q);
queue.push(r);
queue.push(s);
queue.push(t);
queue.push(u);
while (!queue.empty())
{
Person p = queue.top();
cout << p.id << "\t"<<p.age<<"\t"<<p.country_of_origin<<endl;
queue.pop();
}
}
我得到的输出是:
1 4 Benin
2 3 India
3 4 New Zealand
1 4 Sri Lanka
1 2 Zimbabwe
5 7 Wales
代替:
1 4 Benin
1 4 Sri Lanka
1 2 Zimbabwe
2 3 India
3 4 New Zealand
5 7 Wales
为什么会这样?
答案 0 :(得分:1)
您可以通过在第一个字段上排序来进行字典比较,仅当它们相等时,然后测试第二个字段以打破平局。如果按如下所示重写比较器,则应该可以正常工作:
struct PersonCompare
{
bool operator()(const Person &p1, const Person &p2) const
{
if (p1.id > p2.id) {
return true;
} else if (p1.id < p2.id) {
return false;
}
return p1.country_of_origin > p2.country_of_origin;
}
};
另一种方法是使用std::tie
,它更简洁并且正确地进行了字典比较:
#include <tuple>
struct PersonCompare
{
bool operator()(const Person &p1, const Person &p2) const
{
return std::tie(p1.id, p1.country_of_origin) > std::tie(p2.id, p2.country_of_origin);
}
};