[英]std::make_heap with pairs
Is it possible to do make_heap()
with a pair in a vector? 是否可以对向量中的对进行
make_heap()
?
I'm using: 我正在使用:
std::vector< std::pair < int , tablero& > > lista_abierta_;
I use the object function to order the pair by the first member, but it crashes. 我使用对象函数按第一个成员的顺序对,但是它崩溃了。
The code is: 代码是:
#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;
}
只要std::pair<T, U>
提供operator<
(意思是: T
和U
提供operator<
),我就不会在使用make_heap时遇到任何问题。
You can call std::make_heap<T>
as long as T
provides bool operator<(const T &, const T &)
or you explicitly pass comparer. 只要
T
提供bool operator<(const T &, const T &)
或者您显式传递比较器bool operator<(const T &, const T &)
就可以调用std::make_heap<T>
。
You have to change line 23 from 您必须将第23行从
pop_heap(lista_abierta_.begin(),lista_abierta_.end());
to 至
pop_heap(lista_abierta_.begin(),lista_abierta_.end(), comp());
The issue is reference like pair < int, tablero& >
won't work in case of copy inside make_heap
/ pop_heap
. 问题是像
pair < int, tablero& >
类的引用在make_heap
/ pop_heap
进行复制时将pop_heap
。 To fix that we need pair<int, std::reference_wrapper<tablero> >
. 为了解决这个问题,我们需要
pair<int, std::reference_wrapper<tablero> >
。 The comp
and other implementations need to be changed accordingly. 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;
}
};
And heap_pop
and make_heap
will require an object of Compare
. 而且
heap_pop
和make_heap
将需要一个Compare
对象。
comp mycomp;
pop_heap(lista_abierta_.begin(),lista_abierta_.end(),mycomp);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.