Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
multimap upper_bound() function in C++ STL
Next article icon

upper_bound() in C++

Last Updated : 28 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, upper_bound() is a built-in function used to find the first element in a sorted range that is strictly greater than a given value. It implements binary search algorithm so it requires that the range is either sorted or at least partitioned with respect to the given element.

Let’s take a look at an example:

C++
// C++ program to illustrate the use of std::upper_bound #include <bits/stdc++.h> using namespace std;  int main() {     vector<int> v = {10, 20, 30, 40, 50};      // Finding upper bound for value 30 in vector v     cout << *upper_bound(v.begin(), v.end(), 30);      return 0; } 

Output
40

Table of Content

  • Syntax of upper_bound()
  • Examples of upper_bound()
    • Find Upper Bound in an Array
    • Use upper_bound() with Custom Comparator
    • Check for an Element in a Sorted Vector
    • Count Elements Smaller and Larger than a Value
    • Finding Upper Bound in a Set

Syntax of upper_bound()

The upper_bound() function is defined inside the <algorithm> header file.

upper_bound (first, last, val, comp);

Parameters:

  • first: Iterator to the first element in the range.
  • last: Iterator to the theoretical element just after the last element in the range.
  • val: Value to be compared.
  • comp (optional): Binary function that accepts and compares val with an element in the range. By default, it returns true if the val is smaller than the element in the range, false otherwise.

Return Value:

  • Returns an iterator to the smallest number greater than val.
  • Returns iterator to the end of the range if all the elements are smaller than or equal to val.

Note: The behavior of the upper_bound() is undefined if the array is not sorted or at least partitioned with respect to the given value.

The upper_bound function is useful for finding elements in sorted ranges. The C++ Course offers detailed lessons on STL algorithms, including how to use upper_bound effectively in your projects.

Examples of upper_bound()

The upper_bound() function is an interesting function that can be used for number of applications. The below examples demonstrate some of its common uses.

Find Upper Bound in an Array

C++
// C++ program to find the lower bound of a value in a // vector using std::upper_bound() #include <bits/stdc++.h> using namespace std;  int main() {     int arr[5] = {10, 20, 30, 40, 50};     int n = sizeof(arr)/sizeof(arr[0]);      // Finding upper bound for value 30 in array arr     cout << *upper_bound(arr, arr + n, 30);      return 0; } 

Output
40

Time Complexity: O(log n), where n is the number of elements in the array.
Auxiliary Space: O(1).

Use upper_bound() with Custom Comparator

C++
// C++ program to illustrate how to use custom // comparator with std::upper_bound() function #include <bits/stdc++.h> using namespace std;  bool comp(const string &a, const string &b) {     return lexicographical_compare(a.begin(), a.end(),            b.begin(), b.end(), [](char c1, char c2) {         return tolower(c1) < tolower(c2);     }); }  int main() {     vector<string> v = {"Apple", "banana", "Cherry",                         "date", "Elderberry"};      // Finding upper bound of "Avocado"     auto ub = upper_bound(v.begin(), v.end(), "Avocado",                           comp);      if (ub != v.end())         cout << *ub;     else         cout << "Upper bound not found!";      return 0; } 

Output
banana

Time Complexity: O(log n), where n is the number of elements in the vector.
Auxiliary Space: O(1)

Explanation: We need to use the custom comparator function to perform the case insensitive search as the default comparator treats the uppercase and lowercase differently.

Check for an Element in a Sorted Vector

C++
// C++ Program to check if the element exists in a // vector using upper_bound() #include <bits/stdc++.h> using namespace std;  int main() {     vector<int> v = {10, 20, 30, 40, 50};     int val = 40;      // Finding the upper bound     auto it = upper_bound(v.begin(), v.end(), val);      	// Chekcing if val exists or not     if (it != v.begin() && *(--it) == val)         cout << val << " is found.";     else         cout << val << " is NOT found.";      return 0; } 

Output
40 is found.

Time Complexity: O(log n), where n is the number of elements in vector.
Auxiliary Space: O(1)

Explanation: Unlike lower_bound() function, the upper_bound() function never returns the iterator to the matching value if found, it always returns the iterator to the value just after the matching value if it exists. So, to check if the given value exists, we need to decrement the iterator return by the upper_bound() and then compare.

Count Elements Smaller and Larger than a Value

C++
// C++ Program to count the elements smaller and larger // than a value in a vector using upper_bound() #include <bits/stdc++.h> using namespace std;  int main() {     vector<int> v = {10, 20, 30, 40, 50};     int val = 30;      // Finding the upper bound of val in v     auto ub = upper_bound(v.begin(), v.end(), val);      // Finding the number of smaller elements     cout << "No. of Smaller Elements: " << ub - v.begin()       << endl;      // Finding the number of larger elements     cout << "No. of Larger Elements: " << v.end() - ub;      return 0; } 

Output
No. of Smaller Elements: 3 No. of Larger Elements: 2

Time Complexity: O(log n), where n is the number of elements in vector.
Auxiliary Space: O(1)

Explanation: Counts elements based on the position returned by upper_bound().

Finding Upper Bound in a Set

C++
// C++ program to find the upper bound of a value in // a set using std::upper_bound() #include <bits/stdc++.h> using namespace std;  int main() {     set<int> s = {10, 20, 30, 40, 50};      // Finding upper bound for value 30 in set s     auto it = upper_bound(s.begin(), s.end(), 30);     cout << *it;      return 0; } 

Output
40

Time Complexity: O(n)
Space Complexity: O(1)

Explanation: The time complexity is O(n) for the set is because it doesn’t provide random access to its elements. So, the upper_bound() function have to increment it sequentially to find the middle element (part of binary search algorithm) each time leading to increased time complexity. However, set have their own specialized version named as set::upper_bound() method.



Next Article
multimap upper_bound() function in C++ STL
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • C++
  • cpp-algorithm-library
  • CPP-Functions
  • STL
Practice Tags :
  • CPP
  • STL

Similar Reads

  • 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: [GFGTABS] C++ #include
    3 min read
  • std::lower_bound in C++
    In C++, the std::lower_bound() is a built-in function used to find the position of an element in a sorted range that has a value not less than the given value. It is defined inside the <algorithm> header file. In this article, we will learn about std::lower_bound() function in C++. Example: [G
    7 min read
  • map::lower_bound() in C++ STL
    In C++, std::map::lower_bound() is a built-in method used to find the first element in the map whose key is either equal to or greater than the given key. In this article, we will learn about std::map::lower_bound() function in C++. Example: [GFGTABS] C++ // C++ Program to illustrate the use of // s
    4 min read
  • map upper_bound() function in C++ STL
    The map::upper_bound() is a built-in function in C++ STL which returns an iterator pointing to the immediate next element just greater than k. If the key passed in the parameter exceeds the maximum key in the container, then the iterator returned points to the number of elements in the map container
    2 min read
  • multimap upper_bound() function in C++ STL
    The multimap::upper_bound(k) is a built-in function in C++ STL which returns an iterator pointing to the immediate next element which is just greater than k. If the key passed in the parameter exceeds the maximum key in the container, then the iterator returned points to key+1 and element=0. Syntax:
    2 min read
  • Binders in C++ STL
    In the C++ Standard Template Library (STL), binders are a type of functors that bind or associate some of the arguments of a function to a fixed value. This fixed value is stored inside the functor and the rest of the arguments can be passed dynamically at the time of calling the functor. The most c
    4 min read
  • multiset upper_bound() in C++ STL with Examples
    The multiset::upper_bound() is a built-in function in C++ STL that returns an iterator pointing to the immediate next element which is just greater than k. If the key passed in the parameter exceeds the maximum key in the container, then the iterator returned points an element which points to the po
    3 min read
  • set::lower_bound() Function in C++ STL
    The std::set::lower_bound() method is used to find the first element in the set that is equal to or greater than the given value. It is a member function of std::set class and is defined inside <set> header file. In this article, we will learn about std::set::lower_bound() function in C++. Exa
    3 min read
  • Bitwise Operators in C++
    In C+, Bitwise Operators are the operators that are used to perform bit-level operations on the integers. While performing these operations, integers are considered as sequences of binary digits. These operators are useful for low-level programming, system programming, and optimizing performance. C+
    6 min read
  • isgreater() in C/C++
    In C++, isgreater() is a predefined function used for mathematical calculations. math.h is the header file required for various mathematical functions.isgreater() function used to check whether the 1st argument given to the function is greater than the 2nd argument given to the function or not. Mean
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences