繁体   English   中英

重载make_heap?

[英]Overload make_heap?

我有一个std::vector<t_Mont> vt_Mont有{float val,int i and int j}

我想做make_heap(v.begin(), v.end())pop_head(v.begin(), v.end())但在控制台上出现很多错误。 我认为这是因为我正在传递t_mont类型的t_mont

我想对v的变量val的值进行make_heap

我需要做什么来编译我? 我必须重载make_heappop_head吗? 我该怎么做?

谢谢。

我的代码:

std::vector<t_Mont> v;
for (int i = 0; i < nCellsHeight; i++) {
    for (int j = 0; j < nCellsWidth; j++) {
        t_Mont aux;
        aux.i = i;
        aux.j = j;
        aux.val = cellValues[i][j];
        v.push_back(aux);
    }
}

std::make_heap(v.begin(), v.end());
while (v.begin() != v.end()) {
    std::cout << "Best of v = " << v[0].val << std::endl;
    std::pop_heap(v.begin(), v.end());
    v.pop_back();
    std::make_heap(v.begin(), v.end());
}

t_Mont必须与operator<相当,才能正常工作,或者您必须使用另一种形式的std::make_heap并在迭代器旁边传递一个比较函子(如果出于某种原因,您不希望t_Mont通常是可排序)。

也就是说,您必须定义

bool operator<(t_Mont const &lhs, t_Mont &rhs) {
  // return true if lhs is less than rhs, false otherwise.
}

这样就可以得到总订单(即a < b表示!(b < a)a < bb < c表示a < c!(a < a) ),或

struct t_Mont_compare {
  bool operator()(t_Mont const &lhs, t_Mont &rhs) const{
    // return true if lhs is less than rhs, false otherwise.
  }
}

在相同条件下。

默认情况下, make_heap和相关函数将使用<比较值。 您需要为您的类型提供该运算符的重载:

bool operator<(t_Mont const & lhs, t_Mont const & rhs) {
    return lhs.val < rhs.val;
}

或在调用函数时提供自定义比较器:

auto comp = [](t_Mont const & lhs, t_Mont const & rhs){return lhs.val < rhs.val;};
std::make_heap(v.begin(), v.end(), comp);

如果您使用古老的pre-lambda编译器,请完整定义一个函数类型:

struct Comp {
    bool operator()(t_Mont const & lhs, t_Mont const & rhs){return lhs.val < rhs.val;}
};

std::make_heap(v.begin(), v.end(), Comp());

您必须定义一个函数对象,以便在两个t_Monts之间进行比较。 make_heap的声明如下所示:

template <class RandomAccessIterator, class Compare> 
void make_heap (RandomAccessIterator first, RandomAccessIterator last, Compare comp );

或者只是创建一个像这样的函数:

bool comp_tmonts(const t_Mont& a, const t_Mont& b)
{
   /* Insert your comparison criteria for less than here.
      Return a boolean value corresponding to whether a is less than b */
}

然后将其作为第三个参数传递给make_heap函数:

make_heap(v1.begin(), v1.end(), comp_tmonts);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM