1
如果我们在priority_queue
中插入pair<int, int>
,那么哪个元素将决定优先级?我们能否决定哪个元素将决定优先权?在priority_queue内部对<int, int>的情况下决定优先级?
如果我们在priority_queue
中插入pair<int, int>
,那么哪个元素将决定优先级?我们能否决定哪个元素将决定优先权?在priority_queue内部对<int, int>的情况下决定优先级?
是的,您可以使用priority_queue
的Compare
模板参数来提供自己的比较器。默认情况下,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;
}
你能解释一下吗? –