upper_bound in C++ - GeeksforGeeks (2024)

Last Updated : 11 Jul, 2024

Comments

Improve

upper_bound() is a standard library function in C++ defined in the header. It returns an iterator pointing to the first element in the range [first, last] that is greater than value, or last if no such element is found. The elements in the range shall already be sorted or at least partitioned with respect to val.

Syntax of upper_bound()

The upper bound function have multiple signatures to fulfil the programmer’s requirements:

upper_bound (first, last, val);
upper_bound (first, last, val, comp);

Parameters

  • first, last: The range used is [first, last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
  • val: Value of the upper bound to search for in the range.
  • comp: Binary function that accepts two arguments (the first of the type pointed by ForwardIterator, and the second, always val), and returns a value convertible to bool. The function shall not modify any of its arguments. This can either be a function pointer or a function object.

Return Value

An iterator to the upper bound of val in the range. If all the element in the range compare less than val, the function returns last.

Examples of upper_bound()

Input:
10 20 30 30 40 50
Output:
upper_bound for element 30 is at index 4

Input:
10 20 30 40 50
Output:
upper_bound for element 45 is at index 4

Input:
10 20 30 40 50
Output:
upper_bound for element 60 is at index 5

Below are some C++ programs to illustrate the use of std::upper_bound:

Example 1: Program to demonstrate the basic use of std::upper_bound.

CPP
// CPP program to illustrate using// std :: upper_bound with vectors#include <bits/stdc++.h>using namespace std;// Driver codeint main(){ vector<int> v{ 10, 20, 30, 40, 50 }; // Print vector cout << "Vector contains :"; for (int i = 0; i < v.size(); i++) cout << " " << v[i]; cout << "\n"; vector<int>::iterator upper1, upper2; // std :: upper_bound upper1 = upper_bound(v.begin(), v.end(), 35); upper2 = upper_bound(v.begin(), v.end(), 45); cout << "\nupper_bound for element 35 is at position : " << (upper1 - v.begin()); cout << "\nupper_bound for element 45 is at position : " << (upper2 - v.begin()); return 0;}

Output

Vector contains : 10 20 30 40 50upper_bound for element 35 is at position : 3upper_bound for element 45 is at position : 4

Example 2: Program to show the working of std::upper_bound with Arrays

CPP
// CPP program to illustrate using// std :: upper_bound with arrays#include <bits/stdc++.h>using namespace std;// Main Functionint main(){ int arr[] = { 10, 20, 30, 40, 50 }; // Print elements of array cout << "Array contains :"; for (int i = 0; i < 5; i++) cout << " " << arr[i]; cout << "\n"; // using upper_bound int upper1 = upper_bound(arr, arr + 5, 35) - arr; int upper2 = upper_bound(arr, arr + 5, 45) - arr; cout << "\nupper_bound for element 35 is at position : " << (upper1); cout << "\nupper_bound for element 45 is at position : " << (upper2); return 0;}

Output

Array contains : 10 20 30 40 50upper_bound for element 35 is at position : 3upper_bound for element 45 is at position : 4

Time Complexity: O (log2(last – first)), as the number of comparisons performed is logarithmic in the distance between first and last.
Auxiliary Space: O(1)

How upper_bound Works?

The upper_bound function uses a binary search algorithm to find the first element that is greater than the given value. Here’s a simplified version of how it works:

  1. The range [first, last) is divided in half.
  2. The middle element is compared to the value.
  3. If the middle element is less than or equal to value, the search continues in the right half.
  4. If the middle element is greater than value, the search continues in the left half.
  5. The process repeats until the range is empty.

Frequently Asked Questions (FAQs) on C++ upper_bound()

1. What is the difference between upper_bound and lower_bound?

  • upper_bound returns an iterator to the first element greater than the given value.
  • lower_bound returns an iterator to the first element not less than (i.e., greater than or equal to) the given value.

2. Can upper_bound be used with non-sorted ranges?

No, upper_bound requires the range to be sorted. Using it on non-sorted ranges results in undefined behavior.

3. How does upper_bound handle duplicates?

upper_bound returns an iterator to the first element that is greater than the given value, skipping over any duplicates.



upper_bound in C++ - GeeksforGeeks (1)

GeeksforGeeks

Improve

Next Article

lower_bound in C++

Please Login to comment...

upper_bound in C++ - GeeksforGeeks (2024)

References

Top Articles
Osrs Tokkul Calculator
Common questions about metoprolol
9Anime Keeps Buffering
Get maximum control with JCB LiveLink | JCB.com
Amerideck Motorcycle Lift Cost
Myra's Floral Princeton Wv
Forum Phun Extra
Tyrones Unblocked Games Basketball Stars
Cbs Week 10 Trade Value Chart
Nazir Afzal on the BBC: ‘Powerful predators were allowed to behave terribly on an industrial level’
D Drive Not Showing Up—10 Ways To Fix It
Tamilyogi Download 2021
Stadium Seats Near Me
Localhotguy
35Mmx45Mm In Inches
Elisabeth Fuchs, Conductor : Magazine : salzburg.info
Learning The Hard Way Chapter 4
Becker County Jail Inmate List
Where Is The Nearest Five Below
Corporate Clash Group Tracker
Army Dlc 1 Cheat
Robert Rushing Net Worth, Daughter, Age, and Wikipedia
Evil Dead Rise Showtimes Near Cinemark Movies 10
Sufficient Velocity Quests
Devon Lannigan Obituary
Hope for recovery emerges for a Ukrainian soldier who suffered a severe brain injury 2 years ago
Dr. Nicole Arcy Dvm Married To Husband
Horseware Deken Amigo Bravo 100gr Donkerblauw - 130/183 | bol
Is Costco Gas Good? Quality, Cost & Benefits | Ridester
More on this Day - March, 7
Rolling-Embers Reviews
Doculivery Cch
Lily Spa Roanoke Rapids Reviews
Bdo Passion Of Valtarra
Harleyxwest Of Leaks
Franco Loja Net Worth
No Good Dirty Scoundrel Crossword
Sirius Satellite Radio Sports Schedule
John Deere Z355R Parts Diagram
Snapcamms
How Much Does Costco Gas Cost Today? Snapshot of Prices Across the U.S. | CostContessa
October 31St Weather
Ucla Outlook Web Access
Houses For Sale 180 000
Niw 一亩三分地
The Complete History Of The Yahoo Logo - Hatchwise
University Of Oregon Id
Chase Bank Time Hours
Remembering the life of Jeff Hewson.
Mets vs. Reds: Injury Report, Updates & Probable Starters – Sept. 7 - Bleacher Nation
Clarakitty 2022
Latest Posts
Article information

Author: Nathanial Hackett

Last Updated:

Views: 6550

Rating: 4.1 / 5 (52 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Nathanial Hackett

Birthday: 1997-10-09

Address: Apt. 935 264 Abshire Canyon, South Nerissachester, NM 01800

Phone: +9752624861224

Job: Forward Technology Assistant

Hobby: Listening to music, Shopping, Vacation, Baton twirling, Flower arranging, Blacksmithing, Do it yourself

Introduction: My name is Nathanial Hackett, I am a lovely, curious, smiling, lively, thoughtful, courageous, lively person who loves writing and wants to share my knowledge and understanding with you.