C++ map upper_bound() Function
Example
Find the first element with a key that is greater than "Bo":
map<string, int> people = {{"John", 32}, {"Adele", 45}, {"Bo", 29}};
auto it = people.upper_bound("Bo");
cout << it->first << " is: " << it->second;
Definition and Usage
The upper_bound() function returns an iterator (a pointer-like object that points to an element) to the first element with a key that is greater than the given key. An element with the same key is not included.
For string keys, greater means later in alphabetical order. If there is no such element, it returns end().
The upper_bound function is defined in the <map> header file.
Tip: Use lower_bound() to also include an element with the same key.
Syntax
map.upper_bound(keyType key)
keyType is the type of the keys in the map, like string in the example.
Parameter Values
| Parameter | Description |
|---|---|
| key | Required. The key to compare with. |
Technical Details
| Returns: | An iterator pointing to the first element with a key that is greater than key. If there is no such element, it returns map.end(). |
|---|
Related Pages
Read more about maps in our Maps Tutorial.