gpt4 book ai didi

c++ - 在 pair inside priority_queue 的情况下确定优先级?

转载 作者:行者123 更新时间:2023-11-30 02:31:44 24 4
gpt4 key购买 nike

如果我们要插入 pair<int, int>priority_queue ,那么由哪个元素决定优先级呢?我们可以决定哪个元素决定优先级吗?

最佳答案

是的,您可以使用 Compare 提供自己的比较器priority_queue 的模板参数.默认情况下,Compare默认为 std::less<T>其中 T是元素类型,它导致 <在对上调用运算符,专门为:

template <class T1, class T2>
bool operator<(const pair<T1, T2>& x, const pair<T1, T2>& y)
{ return x.first < y.first || (!(y.first < x.first) && x.second < y.second) }

这是一个如何使用不同比较器的例子:

#include <queue>
#include <utility>
#include <vector>

using namespace std;

struct CompareByFirst {
constexpr bool operator()(pair<int, int> const & a,
pair<int, int> const & b) const noexcept
{ return a.first < b.first; }
};

int main() {
priority_queue<pair<int, int>,
std::vector<pair<int, int> >,
CompareByFirst> myQueue;
}

关于c++ - 在 pair<int, int> inside priority_queue 的情况下确定优先级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37318537/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com