find_if() Function in C++

This C++ program demonstrates the find_if algorithm on string vector. The find_if takes three arguments – of which the first two are iterators to the beginning and end of the container and the third argument is predicate. The predicate we are passing returns true on strings starting with ‘P’.

Here is the source code of the C++ program demonstrates the find_if algorithm on string vector. 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_if() on string vector
  3.  */
  4. #include <iostream>
  5. #include <algorithm>
  6. #include <string>
  7. #include <vector>
  8.  
  9. bool fun(std::string s)
  10. {
  11.     if(s[0] == 'P')
  12.         return true;
  13.     else 
  14.         return false;
  15. }
  16.  
  17. int main()  
  18. {
  19.     std::vector <std::string>::iterator i;
  20.     std::vector <std::string> v;
  21.     v.push_back("Apple");
  22.     v.push_back("Apricot");
  23.     v.push_back("Kiwi");
  24.     v.push_back("Orange");
  25.     v.push_back("Peach");
  26.     v.push_back("Pineapple");
  27.  
  28.     i = find_if(v.begin(), v.end(), fun);
  29.     if (i != v.end())
  30.     {
  31.         std::cout << "String at position " << (i - v.begin() + 1)
  32.                   << " starts with P" << std::endl;
  33.         std::cout << "The string is : \"" << *i
  34.                   << "\"" << std::endl;
  35.     }
  36.     return 0;
  37. }

$ a.out
String at position 5 starts with P
The string is : "Peach"

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.