本文介绍了如何改变std :: priority_queue的值()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用std :: priority_queue top()时,它返回一个常量引用。所以有一种方法我可以利用std :: priority_queue和更改top()的值?

解决方案

不得不先关于关联容器的一点,但现在我'



在修改作为关联容器的一部分的对象的键时的基本策略已经在注释中列出从@Xymostech。您复制/检索元素,将其从容器中删除,修改它,然后将其重新插入容器。



您的问题和您的想法从关于使用指针表明复制对象可能很昂贵,因此您还应该知道您可以使用指针来提高效率,但您仍将 需要应用基本方案

 模板<类型名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;

现在如果您要修改 MyClass ,仍需要

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

但如果 MyClass 使用 std :: shared_ptr 和自定义比较器可能有助于加快速度。


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的值()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 18:30