如何更改 std::priority_queue top() 的值? [英] how to change the value of std::priority_queue top()?

查看:44
本文介绍了如何更改 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()?

解决方案

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.

这篇关于如何更改 std::priority_queue top() 的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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