c++ - 用 STL 维护最小堆的简单方法?

标签 c++ stl heap min-heap

据我所知,对于用户定义的结构,这很容易。只需重载运算符 <。但是,对于 int/float 等,我真的需要为 int 重载 operator < 吗? 这是我尝试过的:

       #include <iostream>
       #include <algorithm>
       #include <vector>
       using namespace std;

       bool comp(const int& a, const int& b)
       {
          return a<b?false:true;
       }

       int main () 
       {
         int myints[] = {10,20,30,5,15};
         vector<int> v(myints,myints+5);
         vector<int>::iterator it;
         make_heap(v.begin(), v.end(), comp);
         cout << "initial min heap   : " << v.front() << endl;
         for (unsigned i=0; i<v.size(); i++) cout << " " << v[i];
         cout<<endl;

         pop_heap (v.begin(),v.end());
         v.pop_back();
         for (unsigned i=0; i<v.size(); i++) cout << " " << v[i];
         cout<<endl;
       }

结果是:

        initial min heap   : 5
        5 10 30 20 15
        30 10 15 20

现在 pop_heap,push_heap 不会正确维护最小堆?有没有更简单的方法来实现这一点? 谢谢!

编辑: 对不起,我没有仔细检查手册。是的,将 comp 传递给 pop_heap 或 push_heap 应该可以解决问题。但是,您是什么意思,我不应该使用外部比较器?如果这不是正确的方法,实现此目的的常用方法是什么?

最佳答案

使用 std::greater<int>()作为比较器(对所有 make_heappush_heappop_heap )。 ()很重要 - std::greater<int>是一个仿函数类而不是一个函数,所以你需要一个它的实例。

关于c++ - 用 STL 维护最小堆的简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7681779/

相关文章:

c++ - QPointer 可以成为 std::map 的关键吗

algorithm - BuildHeap - Floyd 算法 - FixHeap 概念

c++ - 使用 C++ 标准库以对数时间进行 Heapify

c++ - 为什么 static_cast<Type>(object) 将对象复制到 Type?

c++ - 将 std::bind 与成员函数一起使用,是否为该参数使用对象指针?

c++ - 无法使用对类型键设置映射值

python - python中的LFU缓存实现

c++ - 为什么在类/结构级别不允许 "using namespace X;"?

c++ - 从一组有限的类静态转换为一个类

C++ STL : Why do STL data structures not provide a function for measuring the memory consumption?