为什么STL中的priority_queue不遵循严格的弱排序?

Aru*_*rup 0 c++ stl priority-queue 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Tem*_*Rex 6

问题是你strict_weak_order(使用>)的否定是<=,这不是一个严格的弱秩序.严格的弱势秩序R必须满足x R x == false所有人x.但是,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);
    }
};
Run Code Online (Sandbox Code Playgroud)

但请注意,a std::priority_queue有一个std::less默认比较器,但是它给出了一个最大堆(即[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';
}
Run Code Online (Sandbox Code Playgroud)

实例