[关闭]
@iStarLee 2019-08-13T17:14:01.000000Z 字数 887 阅读 406

priority_queue

algorithm


image_1di54167v6g91e4m18ga1lc1tjf9.png-40.3kB

  1. // constructing priority queues
  2. #include <iostream> // std::cout
  3. #include <queue> // std::priority_queue
  4. #include <vector> // std::vector
  5. #include <functional> // std::greater
  6. using namespace std;
  7. class mycomparison {
  8. bool reverse;
  9. public:
  10. mycomparison(const bool &revparam = false)
  11. { reverse = revparam; }
  12. bool operator()(const int &lhs, const int &rhs) const
  13. {
  14. if (reverse) return (lhs > rhs);
  15. else return (lhs < rhs);
  16. }
  17. };
  18. template <typename T>
  19. void PrintQueue(T& q)
  20. {
  21. while (!q.empty())
  22. {
  23. cout << q.top()<< " ";
  24. q.pop();
  25. }
  26. cout << "\n";
  27. }
  28. int main()
  29. {
  30. int myints[] = {10, 60, 50, 20};
  31. std::priority_queue<int> second(myints, myints + 4);
  32. std::priority_queue<int, std::vector<int>, std::greater<int> > third(myints, myints + 4);
  33. // using mycomparison:
  34. typedef std::priority_queue<int, std::vector<int>, mycomparison> mypq_type;
  35. mypq_type fifth(mycomparison(true)); // greater-than comparison
  36. PrintQueue(second);
  37. PrintQueue(third);
  38. PrintQueue(fifth);
  39. return 0;
  40. }

output:

  1. 60 50 20 10
  2. 10 20 50 60
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注