【问题标题】:STL Priority queue of struct not correctly working结构的 STL 优先级队列无法正常工作
【发布时间】:2016-10-31 12:09:43
【问题描述】:

我在尝试将结构放入优先级队列时遇到问题,如下图所示,它没有按分数正确组织,它应该按最大的数字组织。

最少的代码:

Class foo{
        public:
        foo();
        // this is in the .h file
        struct individuo{
            individuo(){}
            individuo(QColor cor): gene(cor){}
            QColor gene;
            int score;
            int probabilidade;
            int epoca;
        };

        // this is in the .h file
        struct Comparador{
          bool operator()(const individuo* arg1,const individuo* arg2) const {
            return arg1->score < arg2->score;
          }
        };
        void function();
        priority_queue<individuo *,vector<individuo *>, Comparador> individuos;
};

    void foo::function(){
            individuo *a = new individuo(QColor(r,g,b));
            a->score = rand() % 255;
            individuos.push(a);
    }

这是它在内存中的组织方式:

可能会看到结构没有按其分数正确组织,为什么?

【问题讨论】:

  • 您的示例肯定是最小的,但它远非完整,并且无法验证。请编辑您的问题并添加minimal reproducible example
  • priority_queue 不会保持容器排序。它只保证最前面的元素是最大的。
  • @SamVarshavchik 我很快修复了代码

标签: c++ struct stl priority-queue


【解决方案1】:

优先级队列没有接口来迭代元素是有原因的,它与它提供的核心服务无关。并且屏蔽实现允许更有效的选择。

std::priority_queue 只暴露了push/pop/top,因此可以用堆来实现它。它可以很容易地用std::push_heapstd::pop_heap 重写std::vector,并且不需要维护一个完全有序的元素列表来提供服务。

【讨论】:

    【解决方案2】:

    如果您只想按分数对individuo struct 进行排序,请使用以分数为键的std::map。 priority_queue 用于不同的目的。

    优先级队列是一个容器适配器,它提供对最大(默认)元素的恒定时间查找,代价是对数插入和提取。

    编辑:或者,只需将结构放入 std::vectorstd::array 并在其上使用 std::sort

    【讨论】:

    • 另一个同样有用的选项是std::set,如果您不想使用键值对。
    • map 和 set 需要唯一的值,不能使用 multimap,但是谢谢
    • 那么std::multiset 怎么样?
    猜你喜欢
    • 2016-04-13
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    相关资源
    最近更新 更多