c++ - 优先队列 : Using an object to compare instead of a class

标签 c++ priority-queue

priority_queue 开始,我遇到了这样的问题:我需要将元素存储在队列中,但是它们的排序标准不包含在元素本身中,而是包含在不同的地方,就像在 map 中一样:

std::map<element, value> element_values;
std::priority_queue<element> queue;

我现在需要的是这样的东西:

struct Comp
{
    std::map<...>& the_map;
    Cpmp(std::map<...> _map) : the_map(_map) {}

    bool operator() (element a, element b)
    {
        return the_map[a] < the_map[b];
    }
 }

 Comp comp(element_values);
 std::priority_queue<element, std::vector<element>, comp> queue; // does not work
 std::priority_queue<element, std::vector<element>, Comp> queue; // does work but I'd not be able to pass values to the constructor

元素本身没有内在顺序。一种解决方法是定义一个结构来包装这些东西,但也许有人知道更聪明的方法。我还考虑过提供一个只在我当前范围内有效的比较函数(它本身就是一个函数),但据我所知,C++ 不支持它,至少不支持像我需要的那样捕获局部变量。

最佳答案

std::priority_queue<T, Cont, Comp>将比较对象类型作为模板参数。要传递引用某物的对象,您需要将其作为构造函数参数传递:

std::priority_queue<element, std::vector<element>, Comp> queue(comp);

关于c++ - 优先队列 : Using an object to compare instead of a class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9201113/

相关文章:

c++ - 在opengl中删除纹理

c++ - 在条件语句前放置 "!"

android - 当 PriorityQueue.size() > 0 时,为什么 PriorityQueue.peek() 返回 null

Objective-c 优先级队列

C++ 链接器错误 iostream 重载

c++ - Gcc/G++ 编译成 NIOS 2 程序集

c++ - ponter 和不同大小的整数类型之间的 reinterpret_cast

java - Java 中的优先级队列

c++ - 使用堆的优先级队列

c++ - 对象指针的 priority_queue 上的运算符重载