I'm trying to figure out the following problem.
Suppose I have the following container in C++:
std::set<std::pair<int, int> > my_container;
This set (dictionary) is sorted with respect to the order <
on std::pair<int, int>
, which is the lexicographic order. My task is to find any element in my_container
that has the first coordinate equal to, say x
, and return the iterator to it. Obviously, I don't want to use find_if
, because I need to solve this in logarithmic time.
I would appreciate any advice on how this can be done
You can use
lower_bound
for this:This will give you an iterator to the first element
e
for whiche < std::pair(x, -LIMIT)
does not hold.Such an element either has its first component >
x
(in which case there's nox
in the set), or has the first component equal tox
and is the first such. (Note that all second components are greater than or equal tostd::numeric_limits<int>::min()
by definition).You could use std::set::lower_bound to get the lower and upper limits of the range like this:
Output: