c++ - C++中最小堆的比较器

标签 c++ stl heap comparator min-heap

我正在尝试使用 STL make_heap 等在 C++ 中创建一个 long 的最小堆1,但是我的比较器似乎没有正确比较。以下是我目前的比较器:

struct greater1{
    bool operator()(const long& a,const long& b) const{
        return a>b;
    }
};

但是,当我执行 std::pop_heap(humble.begin(),humble.end(),g); 其中 g 的一个实例>greater1humble 是一个堆,当 sort_heap 被调用时,我得到了 [9,15,15,25] 15 弹出。

我的比较器正确吗?可能出了什么问题?

编辑:
我意识到我正在运行没有比较器的 sort_heap,而当我运行这个比较器时,我从 sort_heap 得到 [15,15,9,25]。现在我在想我的比较器肯定不起作用,但不确定为什么。

1STL 默认创建一个最大堆,所以我需要一个比较器。

最佳答案

也许您在某处遗漏了什么,下面的代码按预期工作:

#include <vector>
#include <algorithm>
#include <iostream>

struct greater1{
  bool operator()(const long& a,const long& b) const{
    return a>b;
  }
};

int main() {
  std::vector<long> humble;
  humble.push_back(15);
  humble.push_back(15);
  humble.push_back(9);
  humble.push_back(25);

  std::make_heap(humble.begin(), humble.end(), greater1());
  while (humble.size()) {
    std::pop_heap(humble.begin(),humble.end(),greater1());
    long min = humble.back();
    humble.pop_back();  
    std::cout << min << std::endl;
  }

  return 0;
}

关于c++ - C++中最小堆的比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14016921/

相关文章:

c++ - 如何比较两个双向迭代器的(顺序)?

go - Go标准库中的最大堆和最小堆

algorithm - CLRS 的 Fibonacci Heap size(x) 分析有缺陷?

c++ - 有 const 构造函数这样的东西吗?

c++ - 从基类覆盖函数

c++ - 是否有 STL 函数可以将 C 风格的数组拆分/拼接成更小的数组?

c++ - STL模板的特化

algorithm - 使用堆排序,追加数组元素

c++ - 使用来自 OpenCV 的 .hpp 头文件

C++ - 不是类或命名空间错误