对于priority_queue,头文件包含在queue.h中,用来实现堆排序,默认是小根堆(小的在前)
函数声明:
template <class T, class Container = vector<T>,
class Compare = less<typename Container::value_type> > class priority_queue;
对于sort(),函数声明:
template <class RandomAccessIterator>
void stable_sort ( RandomAccessIterator first, RandomAccessIterator last );
template <class RandomAccessIterator, class Compare>
void stable_sort ( RandomAccessIterator first, RandomAccessIterator last,
Compare comp );
关于有关自定义排序的Compare comp,我们来看对它的描述:
comp Binary function that accepts two elements in the range as
arguments, and returns a value convertible to bool. The value returned
indicates whether the element passed as first argument is considered
to go before the second in the specific strict weak ordering it
defines. The function shall not modify any of its arguments.This can
either be a function pointer or a function object.
很明确的表示了comp是一个函数指针或函数对象
sort自定义有如下两种方法:
- 可以自定义一个bool型函数,里面的大小规则要是严格弱序的,然后把这个函数名作为参数传给sort;
- 还可以写一个struct或者class,注意要在这个结构体or类中重载调用运算符。然后利用这个结构体or类去实例化一个对象,也就是所谓的函数对象(当成)。把这个函数对象传递给sort也可以完成自定义排序。
可参考具体见:【C++&Leetcode】浅析map与sort的自定义排序
注意
return中的 “>” 和 “<” 符号
优先队列中的排序大小与结构体里重载的符号相反
sort()函数中的排序大小与结构体里重载的符号一致
假设node是一个class类以下方式可以实现重载
struct cmp
{
bool operator()(const node &a, const node &b){
return a.val > b.val; // 大于表示小的在前,小根堆
// 对于sort则相反,大于表示大的在前,降序
}
};
priority_queue<node, vector<node>, cmp> pq;
这里插入一下,对于set重载,这个const 是必不可少的,少了其中一个都会报错:
struct cmp {
//下面形参的const 和 形参之后的 const都不可缺少,不然不能使用set成员函数
bool operator () (const int& a, const int& b) const {
return a > b;
}
//以下写法均不可行
//bool operator () (int& a, int& b) {}
//bool operator () (int& a, int& b) const {}
//bool operator () (const int& a, const int& b) {}
};
set<int, cmp> st;
// 上面的重载相当于 set<int,greater<int>> st;
class Solution {
public:
int thirdMax(vector<int>& nums) {
for (auto s : nums) st.insert(s);
int i = 0;
int res = INT_MIN;
for (auto s : st) {
if (s >= res) res = s;
i++;
if (

&spm=1001.2101.3001.5002&articleId=123204174&d=1&t=3&u=4e7845fbffb148a691dfa341e7a1f1bc)
1477

被折叠的 条评论
为什么被折叠?



