0

我一直在玩 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();
    }
}
4

1 回答 1

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);
    }
};

但是请注意, astd::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';
}

现场示例

于 2016-08-31T07:49:14.400 回答