【问题标题】:std::make_heap with pairsstd::make_heap 成对
【发布时间】:2010-11-09 16:10:53
【问题描述】:

是否可以使用向量中的一对来做make_heap()

我正在使用:

 std::vector< std::pair < int , tablero& > > lista_abierta_;

我使用对象函数按第一个成员对这对进行排序,但它崩溃了。

代码是:

#include <iostream>
#include <vector>
#include <map>
#include <cmath>
#include <algorithm>
#include <functional>
#include "8_puzzle.h"
#include "tablero.h"

using namespace std;

class comp {
public:
    bool operator()(pair < int, tablero&> a, pair < int, tablero&> b) const {
        return a.first > b.first;
    }
};

pair < int, tablero& > puzzle::A_estrella::tope()
{
    pair < int, tablero& > l=lista_abierta_.front();

    pop_heap(lista_abierta_.begin(),lista_abierta_.end());
    lista_abierta_.pop_back();

    return l;
}

[取自here]

【问题讨论】:

  • 嗨,nsb,欢迎来到堆栈溢出。请尝试根据formatting guide 格式化您的帖子。谢谢。
  • 您不能在标准容器中拥有包含 referencepair,对吗?
  • @K-ballo 我在参考时遇到了同样的问题。 pair > 将修复一些关于 pop_heap/make_heap 中的复制的问题。

标签: c++ data-structures std-pair


【解决方案1】:

只要std::pair&lt;T, U&gt;提供operator&lt;(意思是:TU提供operator&lt;),我看不出使用make_heap有什么问题。

【讨论】:

    【解决方案2】:

    您可以调用std::make_heap&lt;T&gt;,只要T 提供bool operator&lt;(const T &amp;, const T &amp;) 或者您明确传递比较器。

    您必须将第 23 行从

    pop_heap(lista_abierta_.begin(),lista_abierta_.end());
    

    pop_heap(lista_abierta_.begin(),lista_abierta_.end(), comp());
    

    【讨论】:

      【解决方案3】:

      问题是在 make_heap/pop_heap 内部复制的情况下,pair &lt; int, tablero&amp; &gt; 之类的引用将不起作用。为了解决这个问题,我们需要pair&lt;int, std::reference_wrapper&lt;tablero&gt; &gt;comp 和其他实现需要相应地更改。

      class comp {
      public:
          bool operator()(pair < int, std::reference_wrapper<tablero> > a, pair < int, std::reference_wrapper<tablero> > b) const {
              return a.first > b.first;
          }
      };
      

      heap_popmake_heap 将需要Compare 的对象。

      comp mycomp;
      pop_heap(lista_abierta_.begin(),lista_abierta_.end(),mycomp);
      

      【讨论】:

        猜你喜欢
        • 2016-10-15
        • 2021-02-18
        • 2014-08-19
        • 2012-04-27
        • 2011-09-12
        • 2018-03-09
        • 1970-01-01
        • 2019-05-20
        • 2013-11-28
        相关资源
        最近更新 更多