[英]Why does priority_queue in STL not follow strict weak ordering?
我一直在使用STL容器及其支持的比較功能/函數,但是我發現priority_queue沒有遵循通常的嚴格弱排序,我試圖了解可能是什么原因,但無法弄清楚指針會有所幫助。
在此博客中還提到了priority_queue不遵循嚴格的弱排序。 在此處輸入鏈接說明
#include "STL.h"
#include "queue"
#include "vector"
#include "iostream"
#include "functional"
using namespace std;
typedef bool(*func)(const int& val1 , const int& val2);
bool strict_weak_order_function(const int& val1 , const int& val2){
return val1 > val2;
}
bool comparer_function(const int& val1 , const int& val2){
return !strict_weak_order_function(val1 , val2);
}
struct Compaper_functor{
bool operator()(const int& val1 , const int& val2){
return !strict_weak_order_function(val1 , val2);
}
};
void runPriorityQueue(void){
//priority_queue<int , vector<int> , func > pq(comparer_function);
priority_queue<int , vector<int> , Compaper_functor > pq;
int size;
cin >> size;
while(size--){
int val;
cin >> val;
pq.push(val);
}
while(!pq.empty()){
cout <<'\n'<< pq.top() << '\n';
pq.pop();
}
}
問題是您的strict_weak_order
(使用>
)的取反是<=
,並且不是嚴格的弱階。 對於所有x
嚴格的弱階R
必須滿足x R x == false
。 但是, R
等於<=
產生(x <= x) == true
。
您需要取反參數的順序(對應於<
)。
bool comparer_function(const int& val1 , const int& val2){
return strict_weak_order_function(val2 , val1);
}
struct Compaper_functor{
bool operator()(const int& val1 , const int& val2){
return strict_weak_order_function(val2 , val1);
}
};
但是請注意, std::priority_queue
具有std::less
作為默認比較器,但是它提供了一個最大堆 (即[5, 4, 3, 2, 1]
從同一輸入輸出[5, 4, 3, 2, 1]
5,4,3,2,1 [5, 4, 3, 2, 1]
),以便獲得最小值-heap(即輸入[1, 2, 3, 4, 5]
5、4、3、2、1 [1, 2, 3, 4, 5]
的輸出[5, 4, 3, 2, 1]
),您需要傳遞std::greater
,請參見例如:
#include <queue>
#include <iostream>
int main()
{
auto const v = std::vector<int> { 5, 4, 3, 2, 1 };
// prints 5 through 1
for (auto p = std::priority_queue<int> { v.begin(), v.end() }; !p.empty(); p.pop())
std::cout << p.top() << ',';
std::cout << '\n';
// prints 1 through 5
for (auto p = std::priority_queue<int, std::vector<int>, std::greater<int>> { v.begin(), v.end() }; !p.empty(); p.pop())
std::cout << p.top() << ',';
std::cout << '\n';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.