2017-06-25 39 views
1

爲什麼std::priority_queue首先返回最大元素(即,是最大優先級隊列),即使它使用std::less作爲比較類型?爲什麼std :: priority_queue首先返回最大元素,但使用std :: less?

當我想創建一個最小隊列時,這會特別困惑,這將由std::priority_queue<T, std::vector<T>, std::greater<T>>完成。

優先級隊列的作用與sort()相反,使事情不太一致。如果使用greater比較器sort() a vector,則該向量的front()是您的最大值。如果使用greater創建優先級隊列,則front是最小值。我意識到優先級隊列使用堆,但我覺得這有一個很好的理由。

+3

如果相反,它可能會混淆別人。 – juanchopanza

+1

因此,您的自定義類型只需提供更少的內容,並且可以將其用於其他容器,甚至可以實現更大的容量。 –

回答

1

因爲編碼時很自然,所以在使用堆的方法時?

檢查(簡體)可能的實現:

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

public: 
    explicit priority_queue(const Container& c_ = Container(), 
          const Compare& comp_ = Compare()) 
     : c(c_), comp(comp_) 
    { 
     std::make_heap(c.begin(), c.end(), comp); 
    } 

    void push(const T& x) 
    { 
     c.push_back(x); 
     std::push_heap(c.begin(), c.end(), comp); 
    } 

    void pop() 
    { 
     std::pop_heap(c.begin(), c.end(), comp); 
     c.pop_back(); 
    } 
}; 

我明白你說什麼,但作爲juanchopanza說:「如果它是周圍的其他方法,它可能會迷惑別人」。

3

這樣做是爲了與歷史實現保持一致:許多類(例如std::map)和算法(如std::sort)在標準模板庫的開始處使用小於關係作爲排序功能,後者成爲C++標準庫。

保持跨多個類和模板的一致性非常重要,因爲庫用戶不需要記住哪個容器或算法的默認比較。

+0

在我看來,優先級隊列的作用與sort()相反。如果你給排序更大,那麼front()是最大的值。如果你給優先級隊列更大(),那麼front是最小的值。 –

相關問題