C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C++ Algorithm Function find_if()C++ Algorithm find_if() function returns the value of the first element in the range for which the pred value is true otherwise the last element of the range is given. Syntaxtemplate <class InputIterator, class UnaryPredicate> InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred); Parameterfirst: It specifies the first element of the range. last: It specifies the last element of the range. pred: It is usually a unary function for which the range values are checked to return a boolean answer. Return valueThe function returns an iterator to the first element of the range for which the pred value is true. If no such element is found, then the function returns the last element. Example 1#include<iostream> #include<algorithm> #include<vector> using namespace std; bool isAnOdd(int i) { return((i%2)==1); } int main() { std::vector<int> newvector; newvector.push_back(20); newvector.push_back(35); newvector.push_back(50); newvector.push_back(65); std::vector<int>::iterator ti = std::find_if(newvector.begin(), newvector.end(),isAnOdd); std::cout<<"Out of the given elements, first odd element is "<<*ti<<"\n"; return 0; } Output: Out of the given elements, first odd element is 35 Example 2#include<iostream> #include<algorithm> #include<vector> bool isEven (int i) { return((i%2)==0); } int main() { std::vector<int> newvector {20, 35, 50, 65}; std::vector<int>::iterator ti; ti= std::find_if(newvector.begin(),newvector.end(),isEven); std::cout<<"Out of the given elements, first even element is "<<*ti<<"\n"; return 0; } Output: Out of the given elements, first odd element is 20 ComplexityThe function moves in a linear way, starting from the first element going towards the last one. For each element of the list value of 'pred' is checked. The search goes on until a mismatch for the 'pred' value is encountered. Data racesEither all the objects in the specified range or some of them are accessed by the function. ExceptionsThe function throws an exception if any of the argument throws one.
Next TopicC++ Algorithm find_if_not Function
|