find_if函数,要包含头文件<algorithm>,下面是函数原型
template <class InputIterator, class UnaryPredicate>
InputIterator
find_if (InputIterator first, InputIterator last, UnaryPredicate pred);
该函数,用来在容器中查找符合条件的元素,第三个参数pred,是函数指针,或是函数对象,pred为一元函数(单参函数),以容器范围内的元素为参数,返回值表示是否与函数中的值相符,第三个参数pred,用一般单参函数,函数对象,lambda表达式来实现查询:
一、一般单参函数compare
#include <iostream>
#include <string>
#include <vector>
#include <algorithm> //find_if
struct A { //容器元素类型
std::string name;
int age;
};
std::vector<A> va; //容器
std::string NameToFind; //全局变量
bool compare(const A& a){ //一般单参函数compare
return a.name == NameToFind;
}
void printFind()
{
std::cout << "input NameToFind:\n";
std::cin >> NameToFind;
auto it = va.begin();
bool isFind = false;
while( it != va.end() )
{
std:: cout << "-------------------\n";
it = std::find_if(it, va.end(), compare );//查找
if (it != va.end() ){
isFind = true;
std:: cout << it->name << "\n";
std:: cout << it->age << "\n";
it++;
}
}
if ( !isFind ){
std::cout << "notFind" << "\n";
}
}
int main()
{
A t1;
t1.name = "Hello";
t1.age = 11;
va.push_back(t1);
A t2;
t2.name = "Hello";
t2.age = 22;
va.push_back(t2);
printFind();
return 0;
}
二、lambda表达式
#include <iostream>
#include <string>
#include <vector>
#include <algorithm> //find_if
struct A { //容器元素类型
std::string name;
int age;
};
std::vector<A> va; //容器
void printFind()
{
std::string NameToFind;//局部变量
std::cout << "input NameToFind:\n";
std::cin >> NameToFind;
auto it = va.begin();
bool isFind = false;
while( it != va.end() )
{
std:: cout << "-------------------\n";
it = std::find_if(it, va.end(),
[NameToFind](const A& a){ return NameToFind == a.name; } );//lambda
if (it != va.end() ){
isFind = true;
std:: cout << it->name << "\n";
std:: cout << it->age << "\n";
it++;
}
}
if ( !isFind ){
std::cout << "notFind" << "\n";
}
}
int main()
{
A t1;
t1.name = "Hello";
t1.age = 11;
va.push_back(t1);
A t2;
t2.name = "Hello";
t2.age = 22;
va.push_back(t2);
printFind();
return 0;
}
三、函数对象
#include <iostream>
#include <string>
#include <vector>
#include <algorithm> //find_if
struct A { //容器元素类型
std::string name;
int age;
bool operator()(const A&a ) { return this->name == a.name; }
};
std::vector<A> va; //容器
void printFind()
{
std::string NameToFind;//局部变量
std::cout << "input NameToFind:\n";
std::cin >> NameToFind;
A t;
t.name = NameToFind;
auto it = va.begin();
bool isFind = false;
while( it != va.end() )
{
std:: cout << "-------------------\n";
it = std::find_if(it, va.end(), t );//函数对象
if (it != va.end() ){
isFind = true;
std:: cout << it->name << "\n";
std:: cout << it->age << "\n";
it++;
}
}
if ( !isFind ){
std::cout << "notFind" << "\n";
}
}
int main()
{
A t1;
t1.name = "Hello";
t1.age = 11;
va.push_back(t1);
A t2;
t2.name = "Hello";
t2.age = 22;
va.push_back(t2);
printFind();
return 0;
}