Tried to use stl lower_bound and upper_bound today and noticed that I didn’t quite understand them correctly before.
The corresponding leetcode problem
Some notes on these:
For std::lower_bound(T k), it returns the first element that is greater or equal to k.
For std::upper_bound(T k), it returns the first element that is greater than k.
For example:
1 |
|
If we want to find a value in std::map that is strictly less than a given key k, we can do the following:
1 | auto it = hm.lower_bound(k); |
Note that if we provide custom comparator to std::map for example, we need to make sure that the comparator returns true only for the cases where lhs < rhs for std::lower_bound to work correctly. This is the same for std::upper_bound. ref