Set upper_bound() in C++ STL
In C++, the set upper_bound() is a built-in method used to find the first element in the set that is just greater than the given value. In this article, we will learn about set upper_bound() function in C++.
Let’s take a quick look at a simple illustration of the function:
#include <bits/stdc++.h>
using namespace std;
int main() {
set<int> s = {1, 3, 5, 6, 7};
// Finding upper bound of 3
cout << *s.upper_bound(3);
return 0;
}
Output
5
Explanation: In the above code, we found the upper bound 5 which is just greater than 3 in the given set s.
This article covers the syntax, usage, and common examples of set upper_bound() method in C++:
Table of Content
Syntax of set upper_bound()
The set upper_bound() is the member method of std::set class defined inside <set> header file.
s.upper_bound(k);
Parameters
- k: Value whose upper bound is to be searched.
Return Value
- Returns an iterator to the first element that is just greater than the given value.
- If all the elements are less than or equal to the given value, returns iterator to the end.
Examples of upper_bound()
The following examples demonstrate the use of set upper_bound() function in different cases.
Find Upper Bound in Set of Strings
#include <bits/stdc++.h>
using namespace std;
int main() {
set<string> s = {"hello", "geeks",
"welcome"};
// Finding upper bound of string "hello"
cout << *s.upper_bound("hello");
return 0;
}
Output
welcome
Find Not Existing Upper Bound
#include <bits/stdc++.h>
using namespace std;
int main() {
set<int> s = {1, 5, 3, 7, 6};
// Finding upper bound of 7 in s
auto it = s.upper_bound(7);
if (it != s.end())
cout << *it;
else
cout << "Upper Bound Not Exists.";
return 0;
}
Output
Upper Bound Not Exists.
Explanation: In the above code, we are trying to find the upper bound of 7 and all the elements are less than or equal to the 7 in the set container. Hence the upper bound of 7 does not exist in the given set container.
Check if an Element Exists in the Set
#include <bits/stdc++.h>
using namespace std;
int main() {
set<int> s = {1, 5, 3, 7, 6};
// Finding upper bound of 7 in s
auto it = --s.upper_bound(7);
if (*it == 7)
cout << "Exists.";
else
cout << "Not Exists.";
return 0;
}
Output
Exists.
Explanation: As set is sorted, if the given value exists in the set, the set upper_bound() will return the iterator to the element next to the given element. This iterator can be decremented to point to the given element in the set.