如何使用stl根据c ++中的值对地图进行排序?
How to sort the map based on value in c++ using stl?
struct node{
int index;
int count;
};
map<int,struct node *> m1;
bool compare(struct node* a, struct node* b) {
if(a->count>b->count)
return 1;
if(a->count==b->count && a->index<b->index)
return 1;
return 0;
}
我可以根据较大的计数值对地图进行排序,如果计数相等则根据较低的索引值进行排序吗?
一种方法是将vector中的所有值压入并进行排序。有没有其他方法可以使用优先级队列完成排序,如下所示?
priority_queue<pair<int,struct node *>, vector<int,struct node *>, compare> pq(m1.begin(),m1.end());
我已经提供了上面的比较功能
您可以尝试使用 Boost Multi-Index。一个索引提供映射访问,另一个提供有序迭代器访问。
解决方案使用 priority_queue
class compare {
public:
bool operator()(pair<int,struct node *> a, pair<int,struct node *> b) {
if(a.second->count>b.second->count)
return 0;
if(a.second->count==b.second->count && a.second->index<b.second->index)
return 0;
return 1;
}
};
priority_queue<pair<int,struct node *>, vector<pair<int,struct node *> >, compare > pq(m1.begin(),m1.end());
struct node{
int index;
int count;
};
map<int,struct node *> m1;
bool compare(struct node* a, struct node* b) {
if(a->count>b->count)
return 1;
if(a->count==b->count && a->index<b->index)
return 1;
return 0;
}
我可以根据较大的计数值对地图进行排序,如果计数相等则根据较低的索引值进行排序吗?
一种方法是将vector中的所有值压入并进行排序。有没有其他方法可以使用优先级队列完成排序,如下所示?
priority_queue<pair<int,struct node *>, vector<int,struct node *>, compare> pq(m1.begin(),m1.end());
我已经提供了上面的比较功能
您可以尝试使用 Boost Multi-Index。一个索引提供映射访问,另一个提供有序迭代器访问。
解决方案使用 priority_queue
class compare {
public:
bool operator()(pair<int,struct node *> a, pair<int,struct node *> b) {
if(a.second->count>b.second->count)
return 0;
if(a.second->count==b.second->count && a.second->index<b.second->index)
return 0;
return 1;
}
};
priority_queue<pair<int,struct node *>, vector<pair<int,struct node *> >, compare > pq(m1.begin(),m1.end());