How to find the first smaller element than an integer X in a vector ? (c++)

cppreference informs me that std::lower_bound

Returns an iterator pointing to the first element in the range [first, last) that is not less than value

and std::upper_bound

Returns an iterator pointing to the first element in the range [first, last) that is greater than value

In this case, given a vector containing 10 10 10 20 20 20 30 30 I would expect both functions to point at the first 20, which sits at position 3 in the vector and is indeed the result you got both times. If you had instead asked for 20, std::lower_bound would return an iterator pointing to the first 20 in the vector (position 3)... the first number not less than 20 and the same result you'd get when asking for 11. In this case though, std::upper_bound would return an iterator pointing at the first 30 (position 6), which is the first value greater than 20.

Just move the iterator back one to get the last value less than your target number, std::prev is one way to do that.


Well, upper_bound returns the first item that is greater than the test item, so the one before that (if it exists) will be the one you want?