This C++ program demonstrates first occurence of an element using lower_bound algorithm. The program takes an element from the input and the is passed to the lower_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 first occurence of an element using lower_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 first cccurance of an element using lower_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 = lower_bound(v.begin(), v.end(), find);
if(it != v.end())
{
std::cout << "\nFirst 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 7 Last position of 7 = 8
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
- Check C++ Books
- Apply for Computer Science Internship
- Practice Computer Science MCQs
- Check Computer Science Books