【转载】priority_queue用法

#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自定义标准后变成小根堆

return 0;
}

initialize (1)

priority_queue (const Compare& comp, const Container& ctnr);

range (2)

template <class InputIterator>
priority_queue (InputIterator first, InputIterator last,
const Compare& comp, const Container& ctnr);

move-initialize (3)

explicit priority_queue (const Compare& comp = Compare(),
Container&& ctnr = Container());

move-range (4)

template <class InputIterator>
priority_queue (InputIterator first, InputIterator last,
const Compare& comp, Container&& ctnr = Container());

allocator versions (5)

template <class Alloc> explicit priority_queue (const Alloc& alloc);
template <class Alloc> priority_queue (const Compare& comp, const Alloc& alloc);
template <class Alloc> priority_queue (const Compare& comp, const Container& ctnr, const Alloc& alloc);
template <class Alloc> priority_queue (const Compare& comp, Container&& ctnr, const Alloc& alloc);
template <class Alloc> priority_queue (const priority_queue& x, const Alloc& alloc);
template <class Alloc> priority_queue (priority_queue&& x, const Alloc& alloc);

   

priority_queue 中存放pair时,自定义排序的写法

注意这其中第三个参数是类或结构体,库中给的有less<template T>和greater<template T>分别对应大根堆和小根堆,默认为大根堆less<template T>

struct cmp

{template <typename T, typename U>

bool operator()(T const &left, U const &right)

{

// second 比较。输出结果为 Second 较大的在前 Second 相同时,先进入队列的元素在前。

if (left.second < right.second)

return true;

return false;

}

};

// new.

priority_queue<pair<int, int>, vector<pair<int, int>>, cmp> pq;

posted @ 2020-02-16 17:22  拓海藤原  阅读(264)  评论(0编辑  收藏  举报