模拟STL实现priority_ququ 仿函数

#include<iostream>
#include<vector>
#include<list>
using namespace std;
namespace king {
    template<class T>
    class Less {
    public:
        bool operator()(T& x,T& y) {//仿函数
            return x < y;
        }
    };
    template<class T,class Container=vector<T>,class Comapre=Less<T>>
    class priority_queue {
        public:
            Comapre com;
        void AdjustDown(int parent) {
            int child = parent * 2 + 1;
            while (child < _con.size()) {
                if (child + 1 < _con.size() &&com(_con[child],_con[child+1])) 
                {
                    child++;
                }
                if (com(_con[parent],_con[child])) {
                    swap(_con[child], _con[parent]);
                    parent = child;
                    child = child * 2 + 1;
                }
                else {
                    break;
                }
            }
        }
        template<class InputIterator>
        priority_queue(InputIterator first,InputIterator last){
            while (first != last) {
                _con.push_back(*first);
                first++;
            }
            for (int i = (_con.size() - 2) / 2; i >= 0; i--) {
                AdjustDown(i);
            }
        }
        T& top(){
            return _con[0];
        }
        void pop() {
            swap(_con[0], _con[_con.size()-1]);
            _con.pop_back();
            AdjustDown(0);
        }
        bool empty() {
            return _con.empty();
        }
    private:
        Container _con;
    };
}
int main() {
    vector<int> v{1,2,3,4,5};
    king::priority_queue<int, vector<int> > q(v.begin(), v.end());
    while (!q.empty()) {
        cout << q.top();
        q.pop();
    }
    
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值