简体   繁体   English

如何根据一些数据结构自定义std::make_heap比较function?

[英]How to customize std::make_heap comparison function based on some data structure?

I am trying to use std::make_heap which has most of the properties I need.我正在尝试使用具有我需要的大部分属性的 std::make_heap 。 I have a vector of ints which are just the indices of my data structure and I want the heap to be built upon some property of that data structure.我有一个整数向量,它们只是我的数据结构的索引,我希望堆建立在该数据结构的某些属性之上。 If I want to have a lambda function for comparison it would be simple:如果我想要一个 lambda function 进行比较,这很简单:

[](int x, int y){return elementList[x]->lnc > elementList[y]->lnc;}

The problem I am facing is the comparison function just take 2 inputs and I cannot pass elementList to it.我面临的问题是比较 function 只需要 2 个输入,我无法将elementList传递给它。 I have two solutions in my mind.我有两个解决方案。 First, to store the pointers in the vector I have.首先,将指针存储在我拥有的向量中。 Second is to implement the heap from scratch myself.二是自己从零开始实现堆。 Is there a simpler solution?有没有更简单的解决方案?

Update: The capture clause in lambda function (Brian mentioned) is a good way.更新:lambda function(Brian 提到)中的捕获子句是一个好方法。 Is there any solution if I don't want to use the lambda function?如果我不想使用 lambda function,有什么解决方案吗?

std::make_heap takes three arguments: two iterators denoting a random access range, and a comparison function. std::make_heap需要三个 arguments:两个表示随机访问范围的迭代器和一个比较 function。 Simply provide your custom comparison function are the third argument.只需提供您的自定义比较 function 是第三个参数。

#include <algorithm>
#include <vector>

// ...

std::vector<Foo> v{/* ... */};

std::make_heap(v.begin(), v.end(), [&elementList](auto lhs, auto rhs){ 
    return elementList[lhs]->lnc > elementList[rhs]->lnc;
});

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

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