priority_queue
- 前置知识:仿函数
- priority_queue的模拟实现
前置知识:仿函数
template<class T>
struct Less
{
bool operator()(const T& x, const T& y) //
{
return x < y;
}
};
priority_queue的模拟实现
通过对priority_queue的底层结构就是堆,因此此处只需对对进行通用的封装即可
template<class T>
struct Less
{
bool operator()(const T& x, const T& y) //
{
return x < y;
}
};
// 构造器
template<class T, class Container = vector<T>,class compare = Less<T>>
class priority
{
Container container;
compare com;
public:
void adjust_up(size_t child)
{
while (child > 0)
{
size_t parent = (child - 1) / 2;
//if (container[parent] < container[child])
if(com(container[parent],container[child]))
{
std::swap(container[parent], container[child]);
child = parent;
parent = (child - 1) / 2;
}
else
{
break;
}
}
}
void push(const T& x)
{
container.push_back(x);
adjust_up(container.size() - 1);
}
T top()
{
return container[0];
}
void adjust_down(size_t parent)
{
size_t child = parent * 2 + 1;
int n = container.size();
while (child < n)
{
//if (child + 1 < n && container[child + 1] > container[child]) child++;
// if (child + 1 < n && container[child] < container[child + 1]) child++;
if (child + 1 < n && com(container[child], container[child + 1])) child++;
//if (container[parent] < container[child])
if(com(container[parent], container[child]))
{
std::swap(container[parent], container[child]);
parent = child;
child = parent * 2 + 1;
}
else
{
break;
}
}
}
void pop()
{
std::swap(container[0], container[container.size() - 1]);
container.pop_back();
adjust_down(0);
}
bool empty()
{
return container.empty();
}
};