This C++ program demonstrates last occurence of an element using upper_bound algorithm. The program takes an element from the input and the is passed to the upper_bound() function alongwith the iterators to the beginning and end of the vector. The function returns an iterator to the first occurence of the element.
Here is the source code of the C++ program which demonstrates last occurence of an element using upper_bound algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to determine last occurence of an element using upper_bound() algorithm
*/
#include <iostream>
#include <vector>
#include <algorithm>
void print(const std::vector <int>& v)
{
std::vector <int>::const_iterator i;
for(i = v.begin(); i != v.end(); i++)
{
std::cout << *i << " ";
}
std::cout << std::endl;
}
int main()
{
int arr[] = {1, 2, 2, 2, 3, 3, 5, 6, 7, 7, 8, 9};
std::vector <int> v(arr, arr + sizeof(arr) / sizeof(int));
std::vector <int>::const_iterator it;
int find;
std::cout << "Vector : ";
print(v);
std::cout << "Enter the element ";
std::cin >> find;
it = upper_bound(v.begin(), v.end(), find);
if(it != v.end())
{
std::cout << "\nLast position of "<< find << " = "
<< (it - v.begin()) << std::endl;
}
else
std::cout << "Element not found" << std::endl;
return 0;
}
$ a.out Vector : 1 2 2 2 3 3 5 6 7 7 8 9 Enter the element 5 Last position of 5 = 7
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Related Posts:
- Apply for C++ Internship
- Practice Computer Science MCQs
- Practice Programming MCQs
- Check Computer Science Books
- Check Programming Books