You can use lower_bound and upper_bound together. Your example of testing elements from 3 to 5 inclusive can be written as follows:
bool contains_elements_in_range = s.lower_bound(3) != s.upper_bound(5);
You can make the range inclusive or exclusive from either end by switching the function you use ( upper_bound or lower_bound ):
s.upper_bound(2) != s.upper_bound(5); // Tests (2, 5] s.lower_bound(3) != s.lower_bound(6); // Tests [3, 6) s.upper_bound(2) != s.lower_bound(6); // Tests (2, 6)
Logarithmic time is the best you can achieve for this, since the set is sorted, and you need to find the element in a sorted range that requires a dichotomous search.
source share