Search code examples
c++heapstdvector

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?


Solution

  • std::make_heap takes three arguments: two iterators denoting a random access range, and a comparison function. Simply provide your custom comparison function as 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;
    });