优先队列中的结构比较
Struct comparison in a priority queue
我想在我的应用程序中获得最优先的"数据包"。数据包是一个仅包含两个字段的基本结构: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
相关文章:
- 如何将字符串与结构(也包括字符串)进行比较?
- 用户定义的结构是否有默认C++比较器?
- Qsort() 比较结构体整数的总和
- gcc 是否在 2 条短裤的过度对齐结构的比较中错过了优化机会?
- 高效简单的结构比较运算符
- 如何将字符串字符与结构数组进行比较?
- 为什么在类或结构中传递自定义比较器函数?
- 如何实现 Boost.Hana 结构的相等比较运算符?
- 如何在单个 SET 中比较结构的两个属性?
- 如何使用用户定义的比较结构重置C 图
- 使用带有比较结构的lower_bound将对象插入矢量
- C++:比较结构中的数据
- 奇怪的用户定义的比较结构错误,用于C++中的priority_queue
- 使用依赖于 "this" C++ 的比较结构初始化集合
- 如何比较结构中不同索引的元素
- std::priority_queue参数化比较结构
- 如何比较结构
- 使用std::tie来比较结构
- 如何使用迭代器比较结构体列表
- 设置<Pointer>比较结构