Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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()?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...