All Ordered Bound Operations
All Ordered Bound Operations
A compact scan page for lower_bound, upper_bound, equal_range, and related ordered-lookup operations across sorted ranges and ordered containers.
All Ordered Bound Operations
A compact scan page for lower_bound, upper_bound, equal_range, and related ordered-lookup operations across sorted ranges and ordered containers.
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
lower_boundupper_boundequal_rangebinary_searchmap and set<algorithm> sorted-range algorithmslower_bound: first element not less than the keyupper_bound: first element greater than the keyequal_range: pair of lower/upper bounds for equivalent valuesequal_range is often the clearest choice.#include <algorithm>
#include <vector>
int main() {
std::vector<int> values{1, 3, 3, 5, 8};
auto first = std::lower_bound(values.begin(), values.end(), 3);
auto last = std::upper_bound(values.begin(), values.end(), 3);
return static_cast<int>(last - first);
}
The result is the count of matching 3 values. That is why bound operations are often more useful than a plain boolean membership check: they tell you where a key belongs and how wide the matching range is.
binary_search when you only need a yes-or-no membership checklower_bound when you need the insertion position or first matching elementupper_bound when you need the end of an equivalent rangeequal_range when duplicates matter and you want both bounds at once#include <map>
#include <string>
int main() {
std::map<std::string, int> counts{std::pair{"Ada", 1}, std::pair{"Bjarne", 2}};
auto [it, inserted] = counts.insert({"Grace", 3});
return inserted ? it->second : 1;
}