bosthhe1 / cpushpush

0 stars 0 forks source link

仿函数初识&&priority_queue #19

Open bosthhe1 opened 1 year ago

bosthhe1 commented 1 year ago

对于目前来说,我所接触的仿函数是最基本的仿函数,虽然是最基本的仿函数,也需要有很多细节需要注意,仿函数听名字就知道是模仿函数,仿函数本质其实是一个类,所以在调用的方法上,与普通函数不太相同,因为仿函数是一个类,所以调用的时候,要么实例化,要么使用匿名调用,一定要注意,仿函数是operator重载了()

bosthhe1 commented 1 year ago
namespace hxh
{
    template<class T>
    struct less
    {
        bool operator()(const T& a, const T& b)//这里重载了()
        {
            return a < b;
        }
    };
}
int main()
{
    int a = 10;
    int b = 20;
    hxh::less<int> less1;//实例化调用
    less1.operator()(a, b);//
    less1(a, b);//这样写更接近函数的写法,但是底层编译器会替换成上面这个
    hxh::less<int>()(a, b);//匿名调用,需要注意的是,这里的匿名对象调用的格式
}
bosthhe1 commented 1 year ago
#include<iostream>
#include<queue>
using namespace std;
template<class T>
struct less
{
    bool operator()(const T& a, const T& b)
    {
        return a < b;
    }
};
template<class T>
struct greater
{
    bool operator()(const T& a, const T& b)
    {
        return a > b;
    }
};
namespace hxh
{

    template<class T,class Container = vector<T>,class cmp = less<T>>
    class priority_queue
    {
    public:

        priority_queue()
        {}
        void adjust_up(size_t child)
        {
            size_t parent = (child - 1) / 2;
            while (child > 0)
            {
                if (cmp()(_con[parent], _con[child]))
                {
                    swap(_con[child], _con[parent]);
                    child = parent;
                    parent = (child - 1) / 2;
                }
                else
                {
                    break;
                }
            }
        }
        void adjust_down(size_t parent)
        {
            size_t child = parent * 2 + 1;
            while (child < size())
            {
                if (child + 1 < size() && cmp()(_con[child] , _con[child + 1]))
                {
                    child++;
                }
                if (cmp()(_con[parent], _con[child]))
                {
                    swap(_con[child], _con[parent]);
                    parent = child;
                    child = parent * 2 + 1;
                }
                else
                {
                    break;
                }
            }
        }
        void push(const T& val)
        {
            _con.push_back(val);
            adjust_up(_con.size());
        }
        void pop()
        {
            swap(_con[0], _con[size() - 1]);
            _con.pop_back();
            adjust_down(0);
        }
        T& top()
        {
            return _con[0];
        }
        size_t size()
        {
            return _con.size();
        }
        bool empty()
        {
            return _con.empty();
        }
    private:
        Container _con;
    };
}
bosthhe1 commented 1 year ago

优先级队列默认是建立大根堆,排序从小到大