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

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest 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
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.