admin管理员组文章数量:1624351
优先队列,比较pair元素,实现按第一个值降序,第一个值相同,按第二个值升序。
其它情况均可通过修改cmp类实现。
struct cmp {
bool operator()(pair<int,int>& a, pair<int,int>& b) {
if (a.first == b.first)
return a.second > b.second;
else
return a.first < b.first;
}
};
int main()
{
priority_queue<pair<int, int>, vector<pair<int, int>>, cmp> pq;
pq.push({2, 3});
pq.push({2, 4});
pq.push({2, 2});
pq.push({4, 2});
while (!pq.empty()) {
cout << pq.top().first << " " << pq.top().second << endl;
pq.pop();
}
vector<int> nums{2, 4, 2, 13, 5};
sort(nums.begin(), nums.end(), [](int a, int b) {
return a < b;
});
for (auto n : nums)
cout << n << endl;
return 0;
}
结果:
4 2
2 2
2 3
2 4
本文标签: 自定义函数priorityqueue
版权声明:本文标题:priority_queue自定义比较函数(实用向) 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dongtai/1728896943a1178532.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论