#include#include #include using namespace std; bool is_even(int n) { return n % 2 == 0; } int main() { vector nums = {1, 3, 5, 2, 4, 6}; auto it = find_if(nums.begin(), nums.end(), is_even); if (it != nums.end()) { cout << "Found the first even number: " << *it << endl; } else { cout << "No even number found." << endl; } return 0; }
Found the first even number: 2
#include#include #include using namespace std; bool starts_with(string s, string prefix) { return s.substr(0, prefix.size()) == prefix; } int main() { vector words = {"apple", "banana", "pear", "orange"}; string prefix = "p"; auto it = find_if(words.begin(), words.end(), [prefix](string s){ return starts_with(s, prefix); }); if (it != words.end()) { cout << "Found the first word starting with \"" << prefix << "\": " << *it << endl; } else { cout << "No word found starting with \"" << prefix << "\"." << endl; } return 0; }
Found the first word starting with "p": pearIn conclusion, std find_if is a useful function provided by the C++ STL's