[英]May I clear a priority_queue by clearing its underlying container?
[英]Should the underlying container of a priority_queue be considered a complete binary tree?
假設我使用std::vector
作為std::priority_queue
的底層容器。
我是否應該將此向量視為二進制堆的表示(Becz.,priority_queue 類似於堆(我的假設是否正確?web 上的大量資源可互換使用這兩個術語)?還是只是法向量?
“二進制堆的表示”是指 -> 向量的第 0 個元素是 bin 的根。 堆,第一個元素是根的左孩子,第二個元素是右孩子等等。
是的,標准要求priority_queue
的成員函數與將相關堆操作應用於底層容器具有相同的效果:
void push(const value_type& x);
效果:如同通過:
c.push_back(x); push_heap(c.begin(), c.end(), comp);
void push(value_type&& x);
效果:如同通過:
c.push_back(std::move(x)); push_heap(c.begin(), c.end(), comp);
template<container-compatible-range<T> R> void push_range(R&& rg);
作用:在c中插入rg的所有元素。
后置條件:
is_heap(c.begin(), c.end(), comp)
為真。
template<class... Args> void emplace(Args&&... args);
效果:如同通過:
c.emplace_back(std::forward<Args>(args)...); push_heap(c.begin(), c.end(), comp);
void pop();
效果:如同通過:
pop_heap(c.begin(), c.end(), comp); c.pop_back();
因為底層容器是受保護的成員,並且訪問控制適用於命名成員,所以您可以獲得任何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.