how to change the value of std::priority_queue top()?

耗尽温柔 提交于 2019-12-01 10:52:33
Daniel Frey

I had to clarify one point about associative containers first, but now I'm finally able to write my answer to this question.

The basic strategy when modifying the key of an object that is part of an associave container has already been outlined in the comment from @Xymostech. You copy/retrieve the element, remove it from the container, modify it and finally re-insert it to the container.

Your question and your idea from the comment about using a pointer suggests that copying the object might be expensive, so you should also know that you can use a pointer to improve efficiency, but you will still need to apply the basic scheme from above.

Consider:

template< typename T >
struct deref_less
{
  typedef std::shared_ptr<T> P;
  bool operator()( const P& lhs, const P& rhs ) { return *lhs < *rhs; }
};

std::priority_queue< std::shared_ptr< MyClass >,
                     std::vector< MyClass >,
                     deref_less< MyClass > > pq;

now if you want to modify an object of MyClass, you still need

auto e = pq.top();
pq.pop();
e->modify( 42 );
pq.push(e);

but if MyClass is expensive to copy, using std::shared_ptr and a custom comparator might help to make it faster.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!