std(19)内置算法find find_if

1.find的用法

用于查找容器某个元素

(1)内置类型不需要重载“==”,直接使用

#include <iostream>
#include <vector>
#include <algorithm>
int main(){
    std::vector<int> vec;
    for(int i = 0;i<10;i++){
        vec.push_back(i);
    }
    std::vector<int>::iterator it = std::find(vec.begin(),vec.end(),5);//如果找到等于5的元素则返回该元素的迭代器,没找到则返回vec.end()
    if(it!=vec.end()){
        std::cout<<*it<<std::endl;
    }
    return 0;
}
(2)自定义的类型需要在类型内部重载"==",编译器才知道如果对两个元素进行比对
#include <iostream>
#include <vector>
#include <algorithm>
class Person{
    public:
    std::string Name;
    int Age;
    Person(std::string name,int age){
        this->Name = name;
        this->Age = age;
    }
    bool operator==(const Person &p){//这里需要重载"==",然后在里面写上如何比较对象相等的逻辑
        return this->Name == p.Name &&this->Age == p.Age;
    }
};
int main(){
    std::vector<Person> vec;
    Person p0("a",10);
    Person p1("b",20);
    Person p2("c",30);
    Person p3("d",40);
    vec.push_back(p0);
    vec.push_back(p1);
    vec.push_back(p2);
    vec.push_back(p3);
    std::vector<Person>::iterator it = std::find(vec.begin(),vec.end(),p1);
    if(it!=vec.end()){
        std::cout<<(*it).Name<<std::endl;
    }
    return 0;
}
 
2.find_if的用法
用于条件查找容器中第一个满足自己定义的条件的元素
#include <iostream>
#include <vector>
#include <algorithm>
bool graterThan5(int i){
    return i>5;
}
int main(){
    std::vector<int> vec;
    for(int i = 0;i<10;i++){
        vec.push_back(i);
    }
    std::vector<int>::iterator it = find_if(vec.begin(),vec.end(),[](int i)->int{return i>5;});//这里使用lambda表达式写的回调函数,相当于上面的graterThan5,括号中的int表示传入参数类型,箭头后面的int表示返回值的类型
    if(it!=vec.end()){
        std::cout<<*it<<std::endl;//这里打印的是6,因为查找的是第一个大于5的元素,自然就是6了
    }
    return 0;
}
posted @ 2021-02-28 14:39  maycpou  阅读(1530)  评论(0编辑  收藏  举报