如何更改 std::priority_queue top() 的值?

2022-01-24 00:00:00 constants priority-queue c++ c++11 stl

When using std::priority_queue top() it returns a constant reference. So is there a way I can both take advantage of std::priority_queue and change the value of top()?

解决方案

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.

相关文章