【问题标题】:std heap sorting using custom > comparator使用自定义 > 比较器的 std 堆排序
【发布时间】:2014-05-08 01:59:08
【问题描述】:

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

#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,结果就变成了 1, 4, 8, 3, 2。

我在这里做错了什么?

【问题讨论】:

    标签: c++ std comparator


    【解决方案1】:

    啊,我想通了,我也必须在 pop_heap 中包含那个比较器。

    【讨论】:

      猜你喜欢
      • 2011-05-10
      • 1970-01-01
      • 2013-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      相关资源
      最近更新 更多