C++ 将优先级队列更改为字母顺序?

C++ change priority queue to alphabetical order?

提问人:YWH 提问时间:8/18/2023 最后编辑:YWH 更新时间:8/18/2023 访问量:62

问:

我正在尝试创建一个具有书名(字符串)和长度(int)的对的优先级队列。 我希望优先级队列的顶部有最早的标题。

默认情况下,优先级队列是反向字母顺序,返回我

(This Book, 100)
(A Book, 200)

当我希望他们反过来时。

我理解 ints 等的情况。我会使用说明符,但在这种情况下我应该使用什么?谢谢!std::greater<int>

#include <iostream>
#include <queue>
#include <utility>
#include <string>
using namespace std;

int main(void){
    pair <string, int> tPair;
    priority_queue <pair <string, int>> pq;
    
    pq.emplace("A Book", 200);
    pq.emplace("This Book", 100);
    
    while(pq.size() != 0){
        tPair = pq.top();
        cout << "(" << tPair.first << ", " << tPair.second << ")\n";
        pq.pop();       
    }
    
    return 0;
}
C++ 优先级队列 字符串比较

评论

0赞 πάντα ῥεῖ 8/18/2023
参考示例中所示,您可以传递 的自定义比较器。std::pair<std::string,int>
0赞 HolyBlackCat 8/18/2023
您可以在标准比较器中省略类型:、.std::less<>std::greater<>

答:

3赞 Yksisarvinen 8/18/2023 #1

std::p air 具有比较第一个成员和第二个成员的运算符>,因此您可以简单地将 std::greater 作为比较器传递给您的队列(请注意,您还需要作为模板参数传递,因为是最后一个模板参数):ContainerComparator

using QueueType = std::pair<std::string, int>;
priority_queue <QueueType, std::vector<QueueType>, std::greater<>> pq;

在线查看