简体   繁体   中英

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. 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:

[](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. 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. Is there any solution if I don't want to use the lambda function?

std::make_heap takes three arguments: two iterators denoting a random access range, and a comparison function. Simply provide your custom comparison function are the third argument.

#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;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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