#include <iostream> #include <functional> #include <queue> int main(int argc, char *argv[]) { std::priority_queue<int> q;//use the default underlying structure q.push(1); q.push(2); std::cout<<"Top: "<<q.top()<<std::endl;//2 std::priority_queue<int, std::vector<int>, std::less<int>> q2; q2.push(3); q2.push(4); std::cout<<"Top: "<<q2.top()<<std::endl;//4 return 0; }
//Rectangle.h #ifndef RECTANGLE_H #define RECTANGLE_H class Rectangle { private: double width; double length; public: //constructor Rectangle(){} Rectangle(double w, double l):width(w), length(l){} //accessor double getWidth() const; double getLength() const; double getArea() const; //mutator void setWidth(double w); void setLength(double l); //operator bool operator<(const Rectangle &right) const { if(getArea() < right.getArea()) return true; else return false; } }; #endif //Rectangle.cpp #include "Rectangle.h" double Rectangle::getWidth() const { return width; } double Rectangle::getLength() const { return length; } double Rectangle::getArea() const { return width*length; } void Rectangle::setWidth(double w) { width = w; } void Rectangle::setLength(double l) { length = l; } //main.cpp #include <iostream> #include <functional> #include <queue> #include "Rectangle.h" int main(int argc, char *argv[]) { std::priority_queue<Rectangle> q;//use the default underlying structure q.push(Rectangle(1, 2)); q.push(Rectangle(2, 3)); std::cout<<q.top().getArea()<<std::endl;//6 return 0; }
//Rectangle.h #ifndef RECTANGLE_H #define RECTANGLE_H class Rectangle { private: double width; double length; public: //constructor Rectangle(){} Rectangle(double w, double l):width(w), length(l){} //accessor double getWidth() const; double getLength() const; double getArea() const; //mutator void setWidth(double w); void setLength(double l); }; #endif //Rectangle.cpp #include "Rectangle.h" double Rectangle::getWidth() const { return width; } double Rectangle::getLength() const { return length; } double Rectangle::getArea() const { return width*length; } void Rectangle::setWidth(double w) { width = w; } void Rectangle::setLength(double l) { length = l; } //main.cpp #include <iostream> #include <functional> #include <queue> #include <vector> #include "Rectangle.h" struct Comparison { bool operator()(const Rectangle &a, const Rectangle &b) const { return (a.getArea() < b.getArea()); } }; int main(int argc, char *argv[]) { std::priority_queue<Rectangle, std::vector<Rectangle>, Comparison> q;//use the default underlying structure q.push(Rectangle(1, 2)); q.push(Rectangle(2, 3)); std::cout<<q.top().getArea()<<std::endl;//6 return 0; }