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.
/*
* C++ Program to demonstrate find_if() on string vector
*/
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
bool fun(std::string s)
{
if(s[0] == 'P')
return true;
else
return false;
}
int main()
{
std::vector <std::string>::iterator i;
std::vector <std::string> v;
v.push_back("Apple");
v.push_back("Apricot");
v.push_back("Kiwi");
v.push_back("Orange");
v.push_back("Peach");
v.push_back("Pineapple");
i = find_if(v.begin(), v.end(), fun);
if (i != v.end())
{
std::cout << "String at position " << (i - v.begin() + 1)
<< " starts with P" << std::endl;
std::cout << "The string is : \"" << *i
<< "\"" << std::endl;
}
return 0;
}
$ 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.
Next Steps:
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Buy C++ Books
- Practice Computer Science MCQs
- Apply for Computer Science Internship
- Apply for Information Technology Internship
- Apply for C++ Internship