如何从priority_queue与用户定义的对象获取非const顶层元素? [英] How to get a non-const top element from priority_queue with user-defined objects?

查看:188
本文介绍了如何从priority_queue与用户定义的对象获取非const顶层元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std :: priority_queue :: top 返回一个常数值。但是,我想从优先级队列中删除顶级元素,并且能够在其他位置修改它。

std::priority_queue::top returns a constant value. However, I would like to remove the top element from the priority queue and be able to modify it somewhere else.

priority_queue<SomeClass, vector<SomeClass>, SomeClassCompare > pQueue;
...
SomeClass *toBeModified = &(pQueue.top());
pQueue.pop();
toBeModified->setMember(3); // I would like to do this

有没有办法从优先级获取顶级元素

Is there a way I can grab the top element from a priority queue (and remove from the queue) and modify it as I wish?

推荐答案

标准容器和容器适配器具有值语义。当将一个元素推入队列时,将创建一个副本。从队列中删除对象时,该对象将被销毁。

Standard containers and container adapters have value semantics. When you push an element into the queue, a copy is created. When you remove an object from the queue, that object is destroyed.

即使 top()会返回一个非 - const ,那么当你从队列中删除元素时,引用就会变得悬空,并且取消引用将导致未定义的行为。

Even if top() would return you a reference to non-const, that reference would become dangling as soon as you remove the element from the queue, and dereferencing it would result in undefined behavior.

code> std :: priority_queue 返回你对 const 的引用,以防止你(有意或无意)排序 - 这就是为什么关联容器的键如 std :: map std :: set const

This said, std::priority_queue returns you a reference to const in order to prevent you from messing (intentionally or unintentionally) with its internal ordering - that's pretty much the same reason why the key of associative containers such as std::map and std::set is const.

你可以做的是构建一个 >的 top()返回的值,修改该副本,删除原始内容,并将副本推入队列:

What you can do, instead, is to construct a copy of the value returned by top(), modify that copy, remove the original, and push the copy into the queue:

SomeClass obj = pQueue.top();
pQueue.pop();
obj.setMember(42);
pQueue.push(std::move(obj)); // You can move obj into the queue if you no more need it

引用语义,另一方面,你必须将指针推入队列(可能是智能指针,具体取决于您的用例),并提供一个适当的自定义排序标准,

If you need reference semantics, on the other hand, then you will have to push pointers into the queue (possibly smart pointers, depending on your use case) and provide an appropriate custom ordering criterion that would order those pointers based on properties of the objects they point to.

在这种情况下,请注意不要在运行时修改这些属性,使它们的顺序不同。这将算作打乱容器的内部排序,并会导致未定义的行为。

In this case, be careful not to modify those properties at run-time in a way that would make their ordering different. That would count as "messing with the internal ordering of the container", and will result in undefined behavior.

这篇关于如何从priority_queue与用户定义的对象获取非const顶层元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆