定义于头文件 < 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";
}
}