find_first_of() Function in C++

«
»
This C++ program demonstrates the find_first_of() algorithm. The function find_first_of() finds the first element from first container which exists in second container. The function takes four iterators – iterators to the beginning and end to the sequence containers.

Here is the source code of the C++ program which demonstrates the find_first_of() 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 demonstrate find_first_of algorithm
  3.  */
  4. #include <iostream>
  5. #include <string>
  6. #include <vector>
  7. #include <algorithm>
  8. #include <functional>
  9. #include <iomanip>
  10. using namespace std;
  11.  
  12. void print(char a[], int N)
  13. {
  14.     for(int i = 0; i < N; i++)
  15.     {
  16.         cout << setw(2) << a[i] << " ";
  17.     }
  18.     cout << endl;
  19. }
  20.  
  21. int main()
  22. {
  23.     char a[] = {'a', 'e', 'i', 'o', 'u'};
  24.     char b[] = {'z', 'y', 'd', 'e', 'f'};
  25.     int alen = sizeof(a) / sizeof(char), blen = sizeof(b) / sizeof(char);
  26.     char * i;
  27.  
  28.     cout << "Array a : ";
  29.     print(a, alen);
  30.     cout << "Array b : ";
  31.     print(b, blen);
  32.     // Without any predicate
  33.     i = find_first_of(a, a + alen, b, b + blen);
  34.     cout << "Iterator to first matching sequence : " << *i
  35.          << endl;
  36.     // With predicate less
  37.     i = find_first_of(b, b + blen, a, a + alen, less<char>());
  38.     cout << "Iterator to first character in b less than character in a : "
  39.          << *i << endl;
  40. }

$ a.out
Array a :  a  e  i  o  u 
Array b :  z  y  d  e  f 
Iterator to first matching sequence : e
Iterator to first character in b less than character in a : d

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

Note: Join free Sanfoundry classes at Telegram or Youtube
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

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 & technical discussions at Telegram SanfoundryClasses.