priority_queue模拟实现

#pragma once
#include<iostream>
#include<vector>
#include<stdbool.h>
using namespace std;
namespace bit
{
    template<class T>
    struct less
    {
        bool operator()(T& a,T& b)
        {
            return a < b;
        }
    };
    template<class T>
    struct greater
    {
        bool operator()(T& a, T& b)
        {
            return a > b;
        }
    };
    template <class T, class Container = vector<T>, class Compare = less<T> >
    class priority_queue
    {
    public:
        priority_queue()
        {}
        template <class InputIterator>
        priority_queue(InputIterator first, InputIterator last)
        {
            while (first != last)
            {
                c.push(*first);
                first++;
            }
        }
        bool empty() 
        {
            return c.empty();
        }
       
        size_t size() const
        {
            return c.size();
        }
        T top() const
        {
            return c[0];
        }
        void AdjustUp(int child)
        {
            int parent = (child - 1) / 2;
            while (child > 0)
            {
                parent = (child - 1) / 2;
                if (comp(c[parent], c[child]))
                {
                    swap(c[parent], c[child]);
                    child = parent;
                }
                else
                {
                    break;
                }
            }
        }
        void push(const T& x)
        {
            c.push_back(x);
            AdjustUp(c.size() - 1);
        }
        void AdjustDown(size_t parent)
        {
            int child = parent * 2 + 1;

            while (child < c.size())
            {
                if (child + 1 < c.size() && comp(c[child], c[child + 1]))
                    child++;
                if (comp(c[parent], c[child]))
                {
                    swap(c[parent], c[child]);
                    parent = child;
                }
                else
                {
                    break;
                }
            }
        }
        void pop()
        {
            swap(c[0], c[c.size() - 1]);
            c.pop_back();
            AdjustDown(0);
        }
    private:
        Container c;
        Compare comp;

    };

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值