C++ Program using upper_bound() method in Vector STL
In this tutorial, we will learn about the working of the upper_bound() method in STL and its implementation using Vector, in the C++ programming language.
What are Vectors?
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted. This makes them more advanatageous over the ordinary Arrays which are of fixed size and are static in nature.
To learn more about Vectors in CPP, we will recommend you to visit C++ STL Vector
upper_bound() method an iterator pointing to the first element which has a value greater than the given value.
For better understanding, refer to the well-commented C++ code given below.
using namespace std;
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " ===== Program to demonstrate the working of upper_bound() method of STL, in CPP ===== \n\n";
cout << "\n\nDeclaring a Vector and Filling it with integers.\n\n";
//create an empty vector
//insert elements into the vector
//prining the vector
cout << "The elements of the Vector are: ";
//Printing the elements using an iterator
for (it = v.begin(); it != v.end(); it++)
cout << *it << " ";
//Sorting the vector in ascending order
//prining the Sorted vector
cout << "\n\nThe elements of the Vector after Sorting are: ";
//Another way of printing the elements of a vector
for (int i : v)
cout << i << " ";
up = upper_bound(v.begin(), v.end(), 35);
cout << "\n\nupper_bound returns an iterator pointing to the first element which has a value greater than the given value.";
cout << "\n\nThe index (starting from 0) of the upper_bound of 35 is: " << (up - v.begin()) << '\n';
cout << "\n\nNote that as per the definition, it only considers the numbers greater than it and not itself.\n";
cout << "\n\n\n";
We hope that this post helped you develop a better understanding of the concept of
upper_bound() method and its implementation in C++. For any query, feel free to reach out to us via the comments section down below.
Keep Learning : )