c_cpp C ++中的MinHeap示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp C ++中的MinHeap示例相关的知识,希望对你有一定的参考价值。

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

// Modify the comparator function to change the heap type
struct comparator {
 bool operator()(int i, int j) {
 return i > j; 
 }
};

// The more correct way of writing a comparator would be to write a comparator clas
// and pass it as an argument

class Compare{
public:
 bool operator()(int i, int j){
  return i>j;
 }
}; 

int main(){
  int myints[] = {10,20,30,5,15};
  // priority_queue is defined inside queue library and that's why you need to include queue before using it.
  
  // Need to understand what the 2nd argument in template about
  std::priority_queue<int, std::vector<int>, comparator> minHeap;
 
  // min priority queue can also be implemented with comparator using this syntax
  // priority_queue< int, vector <int> , greater<int> > pq;

  for(int i=0;i<5;i++){
    minHeap.push(myints[i]);
  }
  std::cout << minHeap.size() << '\n';
  std::cout << minHeap.top() << '\n'; // Get the element at top of the heap
  minHeap.pop(); // Remove the top element
  std::cout << minHeap.top() << '\n';
}

以上是关于c_cpp C ++中的MinHeap示例的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp C中的简单示例

c_cpp 示例C中的氙气图

c_cpp C ++中的char指针示例

c_cpp c中的基本函数指针示例

c_cpp C ++中的基本lambda示例

c_cpp 使用C ++中的无符号字符的示例