简体   繁体   English

priority_queue 的底层容器是否应该被视为完整的二叉树?

[英]Should the underlying container of a priority_queue be considered a complete binary tree?

Say I'm using a std::vector as the underlying container of a std::priority_queue .假设我使用std::vector作为std::priority_queue的底层容器。

Should I consider this vector as a representation of a binary heap (Becz., a priority_queue is similar to a heap (Am I right in this assumption? An awful lot of sources on the web use these 2 terms interchangeably)? or is it just a normal vector?我是否应该将此向量视为二进制堆的表示(Becz.,priority_queue 类似于堆(我的假设是否正确?web 上的大量资源可互换使用这两个术语)?还是只是法向量?

By "representation of a binary heap" I mean -> 0th element of the vector is the root of the bin. “二进制堆的表示”是指 -> 向量的第 0 个元素是 bin 的根。 heap, 1st element is the left child of the root, 2nd element is the right child & so on.堆,第一个元素是根的左孩子,第二个元素是右孩子等等。

Yes, the standard mandates that the member functions of priority_queue have the same effect as applying the relevant heap operation to the underlying container:是的,标准要求priority_queue的成员函数与将相关堆操作应用于底层容器具有相同的效果:

void push(const value_type& x);

Effects: As if by:效果:如同通过:

 c.push_back(x); push_heap(c.begin(), c.end(), comp);

void push(value_type&& x);

Effects: As if by:效果:如同通过:

 c.push_back(std::move(x)); push_heap(c.begin(), c.end(), comp);

template<container-compatible-range<T> R> void push_range(R&& rg);

Effects: Insert all elements of rg in c.作用:在c中插入rg的所有元素。

Postconditions: is_heap(c.begin(), c.end(), comp) is true.后置条件: is_heap(c.begin(), c.end(), comp)为真。

template<class... Args> void emplace(Args&&... args);

Effects: As if by:效果:如同通过:

 c.emplace_back(std::forward<Args>(args)...); push_heap(c.begin(), c.end(), comp);

void pop();

Effects: As if by:效果:如同通过:

 pop_heap(c.begin(), c.end(), comp); c.pop_back();

priqueue.members priqueue.members 成员

Because the underlying container is a protected member, and access controls apply to naming the member, you can get at any priority_queue s data, even if it isn't a base-subobject of a class you've defined.因为底层容器是受保护的成员,并且访问控制适用于命名成员,所以您可以获得任何priority_queue的数据,即使它不是您定义的 class 的基础子对象。

template <typename T, typename Container, typename Comp>
const Container & get_container(const std::priority_queue<T, Container, Comp> & queue) {
    struct access_t : std::priority_queue<T, Container, Comp> {
        auto member_ptr() { return &access_t::c; }
    } access;
    auto ptr = access.member_ptr();
    return queue.*ptr;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM