Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lower_bound of vector of pairs with lambda

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?
like image 797
Shibli Avatar asked Jul 17 '13 22:07

Shibli


People also ask

What does lower_bound return?

The lower_bound() method in C++ is used to return an iterator pointing to the first element in the range [first, last) which has a value not less than val. This means that the function returns an iterator pointing to the next smallest number just greater than or equal to that number.

Can we apply lower bound on vector of pairs?

Lower bound for vector pairs(a,b) will return an iterator whose first element will be greater or equal to a and second value b is greater than or equal to b. If the case is not fulfilled iterator will return a value whose pairs are not present in the pairs of vectors.

What is the complexity of lower_bound?

set::lower_bound() function in C++ STL If the key passed in the parameter exceeds the maximum value in the container, then the iterator returned points to the element beyond last element in the set container. Time Complexity of set::lower_bound() is O(logn), where n is the size of the set.

What does lower_bound return if not found?

lower_bound in c++ stl returns an iterator even when the element is not present.


1 Answers

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.

like image 152
Borgleader Avatar answered Sep 19 '22 09:09

Borgleader