priority_queue的使用

今天刷剑指offer的时候看到了一个相关题目。于是研究下下priority_queue的API:

Priority queue is a container that allows for constant time maximum (or minimum, depending on Compare) extraction at the expense of logarithmic insertion. Working with a priority_queue is similar to managing a heap in some random access container, with the benefit of not being able to accidentally invalidate the heap.

APi中解释了priority_queue的原理。效率上是对数插入代价(猜测2分插入,有时间研究下源码),并且能够避免堆失效的问题。

现在我们研究下具体使用:

 1.int,float等基本数据类型:

     priority_queue<int,vector<int>,greater<int> >q;

    三个参数,int 表示数据类型,vector<int>表示底层的数据容器,greater<int>表示小数优先(less<int>表示大数优先)

2 自定义类数据:

   struct fruit{
        string name;
        int price;
    };
    struct cmp{
        bool operator() (fruit f1,fruit f2){
            return f1.price < f2.price;
        }
    }
priority_queue<fruit,vector<fruit>,cmp> q;

扫描二维码关注公众号,回复: 3945629 查看本文章

猜你喜欢

转载自blog.csdn.net/startliuhao/article/details/83617888