lower_bound() Algorithm in C++

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.

  1. /*
  2.  * C++ Program to determine first cccurance of an element using lower_bound() algorithm
  3.  */
  4. #include <iostream>
  5. #include <vector>
  6. #include <algorithm>
  7.  
  8. void print(const std::vector <int>& v)
  9. {
  10.     std::vector <int>::const_iterator i;
  11.     for(i = v.begin(); i != v.end(); i++)
  12.     {
  13.         std::cout << *i << " ";
  14.     }
  15.     std::cout << std::endl;
  16. }
  17.  
  18. int main()
  19. {
  20.     int arr[] = {1, 2, 2, 2, 3, 3, 5, 6, 7, 7, 8, 9};
  21.     std::vector <int> v(arr, arr + sizeof(arr) / sizeof(int));
  22.     std::vector <int>::const_iterator it;
  23.     int find;
  24.  
  25.     std::cout << "Vector : ";
  26.     print(v);
  27.     std::cout << "Enter the element ";
  28.     std::cin >> find;
  29.     it = lower_bound(v.begin(), v.end(), find);
  30.     if(it != v.end())
  31.     {    
  32.         std::cout << "\nFirst position of "<< find << " = "
  33.                   << (it - v.begin()) << std::endl;
  34.     }
  35.     else
  36.         std::cout << "Element not found" << std::endl;
  37.     return 0;
  38. }

$ 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
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.