gpt4 book ai didi

c++ - 重载 make_heap?

转载 作者:行者123 更新时间:2023-11-28 02:36:21 25 4
gpt4 key购买 nike

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

我想做make_heap(v.begin(), v.end())pop_head(v.begin(), v.end())但我在控制台上遇到了很多错误。我想这是因为我传递了一个 t_mont 类型的 vector .

我要make_heap关于变量的值 valv .

我必须做什么来编译我?我必须重载 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());
}

最佳答案

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());

关于c++ - 重载 make_heap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27298021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com