gpt4 book ai didi

c++ - 如何根据条件对优先级队列使用不同的比较器

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:52:35 25 4
gpt4 key购买 nike

我正在处理一个任务,我有一个优先级队列,我希望它像这样工作:

if(field == '0')
priority_queue<record_t*,vector<record_t*>, CompareRecordID > pq;
else if(field == '1')
priority_queue<record_t*,vector<record_t*>, CompareRecordNum > pq;
else if(field == '2')
priority_queue<record_t*,vector<record_t*>, CompareRecordStr > pq;
else if(field == '3')
priority_queue<record_t*,vector<record_t*>, CompareRecordNumStr > pq;

record_t 在哪里:

typedef struct {
unsigned int recid;
unsigned int num;
char str[STR_LENGTH];
bool valid; // if set, then this record is valid
int blockID; //The block the record belongs too -> Used only for minheap
} record_t;

这意味着,根据函数参数字段,队列将“排序”record_t 的不同字段。但是,我不能在 if 语句中声明队列,因为它显然会给我一个错误“pq 未在此范围内声明”。我能做什么?

最佳答案

您可以使用将比较器对象作为参数的std::priority_queue 构造函数。然后你可以像这样给它一个可配置的比较器:

#include <vector>
#include <queue>
#include <cstring>
#include <iostream>

const int STR_LENGTH = 20;

struct record_t
{
unsigned int recid;
unsigned int num;
char str[STR_LENGTH];
bool valid; // if set, then this record is valid
int blockID; //The block the record belongs too -> Used only for minheap
};

// switchable priority comparator
struct CompareRecord
{
int field;

CompareRecord(int field = 0): field(field) {}

bool operator() (const record_t* lhs, const record_t* rhs) const
{
switch(field)
{
case 0: return lhs->recid < rhs->recid;
case 1: return lhs->num < rhs->num;
case 2: return std::strcmp(lhs->str, rhs->str) < 0;
}
return true;
}
};

int main()
{
// physical records
std::vector<record_t> records;

record_t r;

r.recid = 1;
r.num = 1;
std::strcpy(r.str, "banana");

records.push_back(r);

r.recid = 2;
r.num = 4;
std::strcpy(r.str, "orange");

records.push_back(r);

r.recid = 3;
r.num = 2;
std::strcpy(r.str, "apple");

records.push_back(r);

// input priority type: 0, 1 or 2

int field;

std::cout << "Sort type [0, 1, 2]: " << std::flush;
std::cin >> field;
std::cout << '\n';

// build priority view

CompareRecord cmp(field);
std::priority_queue<record_t*, std::vector<record_t*>, CompareRecord> pq(cmp);

for(auto& r: records)
pq.push(&r);

while(!pq.empty())
{
std::cout << "rec: " << pq.top()->recid << '\n';
std::cout << "num: " << pq.top()->num << '\n';
std::cout << "str: " << pq.top()->str << '\n';
std::cout << '\n';
pq.pop();
}
}

输出:

Sort type [0, 1, 2]: 0

rec: 3
num: 2
str: apple

rec: 2
num: 4
str: orange

rec: 1
num: 1
str: banana

关于c++ - 如何根据条件对优先级队列使用不同的比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30411790/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com