C++算法find_if()函数返回pred值为true的参数内第一个元素的值,否则给出参数的最后一个元素。
template <class InputIterator, class UnaryPredicate> InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred);
first - 它指定参数的第一个元素。
last - 它指定参数的最后一个元素。
pred - 通常是一元函数,对其参数值进行检查以返回布尔值答案。
该函数将迭代器返回到pred值为true的参数的第一个元素。如果找不到这样的元素,则该函数返回最后一个元素。
#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; }
输出:
Out of the given elements, first odd element is 35
#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; }
输出:
Out of the given elements, first odd element is 20
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)