.upper_bound()

Anonymous contributor's avatar
Anonymous contributor
Published Oct 28, 2024
Contribute to Docs

The .upper_bound() function in a map returns an iterator pointing to the first element whose key is greater than the given key. If no such key exists, the iterator points to the map’s .end().

Syntax

mapName.upper_bound(key);
  • key: The key whose upper bound is needed.

Example

The example below demonstrates using .upper_bound() to find the first student with a roll number greater than a specified value:

#include <iostream>
#include <map>
int main() {
// Map with roll numbers as keys and student names as values
std::map<int, std::string> students;
students[101] = "John";
students[103] = "Alice";
students[105] = "Bob";
// Find the first student with a roll number greater than 102
auto it = students.upper_bound(102);
if (it != students.end()) {
std::cout << "The student with roll number greater than 102 is: " << it->second << " (Roll No: " << it->first << ")" << std::endl;
} else {
std::cout << "No student found with roll number greater than 102." << std::endl;
}
return 0;
}

The code above produces the following output:

The student with a roll number greater than 102 is: Alice (Roll No: 103)

Codebyte Example

The following codebyte example demonstrates how .upper_bound() works by returning iterators to keys greater than 11, 13, and 17 in a map of integers:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn C++ on Codecademy