@iStarLee
2019-08-13T17:14:01.000000Z
字数 887
阅读 392
algorithm
// constructing priority queues
#include <iostream> // std::cout
#include <queue> // std::priority_queue
#include <vector> // std::vector
#include <functional> // std::greater
using namespace std;
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);
}
};
template <typename T>
void PrintQueue(T& q)
{
while (!q.empty())
{
cout << q.top()<< " ";
q.pop();
}
cout << "\n";
}
int main()
{
int myints[] = {10, 60, 50, 20};
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 fifth(mycomparison(true)); // greater-than comparison
PrintQueue(second);
PrintQueue(third);
PrintQueue(fifth);
return 0;
}
output:
60 50 20 10
10 20 50 60