无涯教程-C++ 算法 - find_if函数

52 阅读1分钟

C++算法find_if()函数返回pred值为true的参数内第一个元素的值,否则给出参数的最后一个元素。

find_if - 语法

template <class InputIterator, class UnaryPredicate>
InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred);

find_if - 参数

first - 它指定参数的第一个元素。

last  - 它指定参数的最后一个元素。

pred - 通常是一元函数,对其参数值进行检查以返回布尔值答案。

find_if - 返回值

该函数将迭代器返回到pred值为true的参数的第一个元素。如果找不到这样的元素,则该函数返回最后一个元素。

find_if - 例子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;
}

输出:

Out of the given elements, first odd element is 35

find_if - 例子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;

}

输出:

Out of the given elements, first odd element is 20

参考链接

www.learnfk.com/c++/cpp-alg…