C/C++编程:find_first_of

1059 篇文章 280 订阅

定义于头文件 < algorithm>
算法库提供大量用途的函数(例如查找、排序、计数、操作),它们在元素范围上操作。注意范围定义为 [first, last) ,其中 last 指代要查询或修改的最后元素的后一个元素。

可能的实现

版本一

template<class InputIt, class ForwardIt>
InputIt find_first_of(InputIt first, InputIt last,
                      ForwardIt s_first, ForwardIt s_last)
{
    for (; first != last; ++first) {
        for (ForwardIt it = s_first; it != s_last; ++it) {
            if (*first == *it) {
                return first;
            }
        }
    }
    return last;
}

版本二

template<class InputIt, class ForwardIt, class BinaryPredicate>
InputIt find_first_of(InputIt first, InputIt last,
                      ForwardIt s_first, ForwardIt s_last,
                      BinaryPredicate p)
{
    for (; first != last; ++first) {
        for (ForwardIt it = s_first; it != s_last; ++it) {
            if (p(*first, *it)) {
                return first;
            }
        }
    }
    return last;
}

调用示例

#include <algorithm>
#include <iostream>
#include <vector>
 
int main()
{
    std::vector<int> v{0, 2, 3, 25, 5};
    std::vector<int> t{3, 19, 10, 2};
 
    auto result = std::find_first_of(v.begin(), v.end(), t.begin(), t.end());
 
    if (result == v.end())
    {
        std::cout << "no elements of v were equal to 3, 19, 10 or 2\n";
    }
    else
    {
        std::cout << "found a match at "
                  << std::distance(v.begin(), result) << "\n\n";
    }
 
    auto func = [](int a, int b)
    {
        return a + 2 == b;
    };
 
    result = std::find_first_of(v.begin(), v.end(), t.begin(), t.end(), func);
 
    if (result == v.end())
    {
        std::cout << "no elements of v+2 were equal to 3, 19, 10 or 2\n";
    }
    else
    {
        std::cout << "found a match at "
                  << std::distance(v.begin(), result) << "\n\n";
    }
 
    auto func1 = [](int a, int b)
    {
        return a + 100 == b;
    };
 
    result = std::find_first_of(v.begin(), v.end(), t.begin(), t.end(), func1);
 
    if (result == v.end())
    {
        std::cout << "no elements of v+100 were equal to 3, 19, 10 or 2\n";
    }
    else
    {
        std::cout << "found a match at "
                  << std::distance(v.begin(), result) << "\n";
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值