Blog Archive

Friday, September 1, 2017

priority_queue in C++ studying notes

refer:
http://www.cplusplus.com/reference/queue/priority_queue/priority_queue/
http://www.cplusplus.com/forum/general/26791/

#include <iostream>       // std::cout
#include <queue>          // std::priority_queue
#include <vector>         // std::vector
#include <functional>     // std::greater

class mycomparison
{
  bool reverse;
public:
  mycomparison(const bool& revparam=false)
    {reverse=revparam;}
  bool operator() (const int& lhs, const int&rhs) const
  {
    if (reverse) return (lhs>rhs);
    else return (lhs<rhs);
  }
};

int main ()
{
  int myints[]= {10,60,50,20};

  std::priority_queue<int> first;
  std::priority_queue<int> second (myints,myints+4);
  std::priority_queue<int, std::vector<int>, std::greater<int> >
                            third (myints,myints+4);
  // using mycomparison:
  typedef std::priority_queue<int,std::vector<int>,mycomparison> mypq_type;

  mypq_type fourth;                       // less-than comparison
  mypq_type fifth (mycomparison(true));   // greater-than comparison
  mypq_type sixth(myints,myints+4);
  mypq_type seventh(myints, myints+4,mycomparison(true));
  std::cout<<"second.top()="<< second.top() << "\nthird.top()=" << third.top()
    << "\nsixth.top()="  <<sixth.top()<< "\nseventh.top()="<< seventh.top() << std::endl;

typedef int node;
priority_queue<node,std::vector<node> > v2;
v2.push(3);
v2.push(5);
const node *p=&v2.top();
std::cout <<p[0]<<' '<<p[1]<<endl; //5 3
  return 0;
}

//output:
second.top()=60
third.top()=10
sixth.top()=60
seventh.top()=10
5 3

1 comment: