使用自定义>比较器进行 STD 堆排序

std heap sorting using custom > comparator

本文关键字:STD 堆排序 比较器 自定义 gt      更新时间:2023-10-16

我正在尝试使用std堆对整数数组进行排序。

#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
struct compare {
    bool operator() (const int& s1, const int& s2) const{
        if (s1 < s2) return true;
        return false;
    }
};
int main() {
    vector<int> v;
    v.push_back(8);
    v.push_back(1);
    v.push_back(3);
    v.push_back(2);
    v.push_back(4);
    make_heap(v.begin(), v.end(), compare());
    for (int i=0; i<5; i++) {
        int t = v.front();
        pop_heap(v.begin(), v.end()); v.pop_back();
        cout << t << ' ';
    }
    cout << endl;
}

现在这个排序输出8,4,3,2,1,是正确的。

但是如果我改变s1 <在比较器函数中S2到s1> S2,结果变为1,4,8,3,2。

我在这里做错了什么?

啊,我想起来了,我必须在pop_heap中也包含这个比较器