Question

I want to find the std::lower_bound of the a std::vector of std::pair's according to the second element with lambda.

std::vector < std::pair <int, double> > vec;
vec.resize(5);

auto it = std::lower_bound(vec.begin(), vec.end(), lambda);
// what is that lambda here?
Was it helpful?

Solution

You're missing an argument here, std::lower_bound takes a begin and end iterator, a value (this is what you missed) and finally can take a lambda.

#include <algorithm>
#include <vector>

int main()
{
    typedef std::pair<int, double> myPair; // typedef to shorten the type name
    std::vector <myPair> vec(5);

    myPair low_val; // reference value (set this up as you want)
    auto it = std::lower_bound(vec.begin(), vec.end(), low_val, 
        [](myPair lhs, myPair rhs) -> bool { return lhs.second < rhs.second; });
}

Reference page for lower_bound is here.

OTHER TIPS

The purpose of lower_bound is to find the position where an element would go. So you have to specify that element. If you only want to sort by the second partner, then you just need to specify a value for that:

std::vector<std::pair<int, double>> vec = /* populate */ ; // must be sorted!

double target = 1.3;

auto it = std::lower_bound(vec.begin(), vec.end(), target,
          [](std::pair<int, double> const & x, double d)
          { return x.second < d; });

Note that the vector must be sorted according to the same predicate, though, so you might want to store the predicates more permanently:

auto lb_cmp =   [](std::pair<int, double> const & x, double d) -> bool
                { return x.second < d; };

auto sort_cmp = [](std::pair<int, double> const & x,
                   std::pair<int, double> const & y) -> bool
                { return x.second < y.second; };

std::sort(vec.begin(), vec.end(), sort_cmp);

auto it = std::lower_bound(vec.begin(), vec.end(), target, lb_cmp);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top