lower_bound of vector of pairs with lambda

Shibli picture Shibli · Jul 18, 2013 · Viewed 19.3k times · Source

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?

Answer

Borgleader picture Borgleader · Jul 18, 2013

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.