Comparator for min-heap in C++

前端 未结 3 1076
借酒劲吻你
借酒劲吻你 2021-02-05 05:37

I am trying to make a min-heap1 of longs in C++ using the STL make_heap, etc., but my comparator doesn\'t seem to be comparing properly. The

3条回答
  •  渐次进展
    2021-02-05 05:58

    Perhaps you are missing something somewhere, the code below works as intended:

    #include 
    #include 
    #include 
    
    struct greater1{
      bool operator()(const long& a,const long& b) const{
        return a>b;
      }
    };
    
    int main() {
      std::vector 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;
    }
    

提交回复
热议问题