priority_queue 模拟实现

namespace bit

{

//函数对象 less

template

struct less

{

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

{ 

  return left < right; 

}

};

//函数对象 greater

template

struct greater

{

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

{ 

  return left > right; 

}

};

namespace bit

{

//函数对象 less

template

struct less

{

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

{ 

  return left < right; 

}

};

//函数对象 greater

template

struct greater

{

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

{ 

  return left > right; 

}

};

template <class T, class Container = std::vector, class Compare = less >

class priority_queue

{

public:

//创建空的优先级队列

priority_queue():c()

{}

template <class InputIterator>

priority_queue(InputIterator first, InputIterator last)

  :c(first, last)

{

  //将c中的元素调整为堆的结构,默认为大堆

  int count = c.size();

  int root = ((count - 2) >> 1);

  for (; root >= 0; root--)

   AdjustDown(root);

}

bool empty() const

{

  return c.empty();

}

size_t size() const

{

  return c.size();

}

// 堆顶元素不允许修改,因为:堆顶元素修改可以会破坏堆的特性

const T& top() const

{

  return c.front();

}

void push(const T& x)

{

  c.push_back(x);

  //push_heap(c.begin(), c.end(), comp);

  AdjustUp(c.size() - 1);

}

void pop()

{

  if (empty())

   return;

  std:swap(c.front(), c.back());

  c.pop_back();

  AdjustDown(0);

}

private:

//向上调整

void AdjustUp(int child)

{

  int parent = ((child - 1) >> 1);

  while (child)

  {

if (Com(c[parent], c[child]))

    {

      std::swap(c[child], c[parent]);

      child = parent;

      parent = ((child - 1) >> 1);

   }

    else

      return;

    

  }

}

 

//向下调整

void AdjustDown(int parent)

{

  int child = parent * 2 + 1;

  while (child < c.size())

  {

    // 找以parent为根的较大的孩子

    if (child + 1 < c.size() && Com(c[child], c[child+1]))

    child += 1;

    // 检测双亲是否满足情况

    if (Com(c[parent], c[child]))

    {

      std::swap(c[child], c[parent]);

      parent = child;

      child = parent * 2 + 1;

   }

   else

   return;

  }

}

private:

Container c;

Compare Com;

};

};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值