Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparator with capture

Tags:

c++

comparator

I want to create a boost::binomial_heap with a comparator that uses external data, something like

bool compare(int a1, int a2) 
{
  return price[a1] < price[a2];
}

(here price, for example, is a vector of doubles.)

How to declare the compare function that captures price?

like image 821
danatel Avatar asked Jul 30 '26 03:07

danatel


1 Answers

The following C++11 code shows how to do so:

#include <vector>
#include <map>
int main()
{   
    std::vector<double> price{0.3, 0.2, 0.1};
    auto cmp = [&price](int i, int j){return price[i] < price[j];};
    std::map<int, float, decltype(cmp)> m(cmp);
    m[2] = 'b';
    m[1] = 'c';
}   

The line

    std::vector<double> price{0.3, 0.2, 0.1};

defines the vector price.

The line

    auto cmp = [&price](int i, int j){return price[i] < price[j];};

creates a lambda function that captures price by reference.

The line

    std::map<int, float, decltype(cmp)> m(cmp);

creates a container (in this case std::map) parameterized by this type, and taking an object as the comparator. Using this with a different container will be similar.

like image 133
Ami Tavory Avatar answered Aug 01 '26 16:08

Ami Tavory



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!