优先队列中的结构比较

Struct comparison in a priority queue

本文关键字:比较 结构 优先队列      更新时间:2023-10-16

我想在我的应用程序中获得最优先的"数据包"。数据包是一个仅包含两个字段的基本结构:std ::字符串称为名称和整数作为优先级。我的代码如下:

#include <iostream>
#include <queue>
using namespace std;
typedef struct packet {
    int priority;
    std::string name;
    friend bool operator<(const packet& a, const packet& b) {
        return a.priority > b.priority;
    }
}
packet;
int main() {
    std::priority_queue<packet*> packets; //I must use packet* as pointer (restriction).
    packet* p1 = new packet();
    packet* p2 = new packet();
    packet* p3 = new packet();
    p1->priority = 200;
    p2->priority = 20;
    p3->priority = 89;
    p1->name= "test";
    p2->name = "test2";
    p3->name = "test3";
    packets.push(p1);
    packets.push(p2);
    packets.push(p3);
    std::cout << "first: " << packets.top()->name;
    packets.pop();
    std::cout << "second: " << packets.top()->name;
    packets.pop();
    std::cout << "third: " << packets.top()->name;
    packets.pop();
    return 0;
}

输出:首先:test3第二:test2第三:test1

,但我想先获得最优先的数据包。我该如何解决这个问题?谢谢!

#include <iostream>
#include <queue>
using namespace std;
typedef struct packet {
    int priority;
    std::string name;
    friend bool operator<(const packet& a, const packet& b) {
        return a.priority > b.priority;
    }
}
packet;
struct comparator
{
    bool operator()(const packet * a, const packet *b)
    {
        return a->priority > b->priority;
    }
};
//comparator f; edit - no need for this forgot to comment oops
int main() {
    std::priority_queue<packet*,vector<packet*>,comparator> packets; // i add comparator and vector<packet*> here
    packet* p1 = new packet();
    packet* p2 = new packet();
    packet* p3 = new packet();
    p1->priority = 200;
    p2->priority = 20;
    p3->priority = 89;
    p1->name= "test";
    p2->name = "test2";
    p3->name = "test3";
    packets.push(p1);
    packets.push(p2);
    packets.push(p3);
    std::cout << "first: " << packets.top()->name;
    packets.pop();
    std::cout << "second: " << packets.top()->name;
    packets.pop();
    std::cout << "third: " << packets.top()->name;
    packets.pop();
    return 0;
}

在您的std::priority_queue中,您需要提供比较元素并确定优先级的comparator

我使用struct comparator使用bool operator()(packet * a, packet *b)进行此操作,这使您可以使用2 packet* s调用比较对象(),然后返回true/false(如果首先的优先级为>或&lt;第二个))

i还将vector<packet*>容器类型添加到std::priority_queue中,以使该容器(构建堆在其上)。更多信息在这里:http://en.cppreference.com/w/cpp/container/priority_queue