函数对象之find_if

示例代码:

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

//是否大于5
bool greater5(int n)
{
    return n > 5;
}

//by zhaocl
int main()
{
    vector<int> vi;
    vi.push_back(3);
    vi.push_back(6);
    vi.push_back(9);
    
    //返回第一个大于5的元素地址
    vector<int>::iterator it = find_if(vi.begin(),vi.end(),greater5);
    cout<<"the first greater number than 5 is "<< *it <<endl;
    system("pause");
    return 0;
}

说明:

在这里greater5只是一个函数的对象,然后作为find_if的一个参数。

find_if函数是一个在指定范围内查找满足特定条件的元素的算法函数。它可以用于查找容器(如vector、list等)中的元素,也可以用于查找数组中的元素。 find_if函数的用法如下: ```cpp template<class InputIterator, class UnaryPredicate> InputIterator find_if(InputIterator first, InputIterator last, UnaryPredicate pred); ``` 参数说明: - `first` 和 `last` 是表示要搜索的范围的迭代器。范围是[first, last),包含first但不包含last。 - `pred` 是一个一元谓词(Unary Predicate)函数函数对象,用于对范围内的元素进行判断。 调用该函数后,它会在指定范围内依次检查每个元素,直到找到第一个满足谓词条件的元素。如果找到了符合条件的元素,则返回该元素的迭代器;否则,返回last。 下面是一个示例,展示了如何使用find_if函数来查找一个vector中大于10的第一个元素: ```cpp #include <iostream> #include <vector> #include <algorithm> bool isGreaterThan10(int num) { return num > 10; } int main() { std::vector<int> nums = {5, 8, 12, 15, 20}; auto it = std::find_if(nums.begin(), nums.end(), isGreaterThan10); if (it != nums.end()) { std::cout << "The first element greater than 10 is: " << *it << std::endl; } else { std::cout << "No element greater than 10 found!" << std::endl; } return 0; } ``` 运行这段代码,输出结果为: ``` The first element greater than 10 is: 12 ``` 这里我们定义了一个名为`isGreaterThan10`的谓词函数,用于判断一个数是否大于10。在`main`函数中,我们使用`std::find_if`函数来查找第一个大于10的元素,并输出结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值