1.std::find
是C++标准库中的一个通用查找算法,用于在给定范围内查找指定元素。它接受两个迭代器作为参数,分别表示搜索范围的起始和结束位置。如果找到指定元素,则返回指向该元素的迭代器;否则,返回指向搜索范围末尾的迭代器。
// 原型
template< class InputIt, class T >
constexpr InputIt find( InputIt first, InputIt last, const T& value );
// 可能实现
template<class InputIt, class T>
InputIt find(InputIt first, InputIt last, const T& value)
{
for (; first != last; ++first)
if (*first == value)
return first
return last;
}
2.std::find_if
在一个给定的范围内查找第一个符合指定条件的元素。它接收一个范围和一个谓词(即一个判断条件的函数)作为参数,返回第一个满足该条件的元素的迭代器。如果在整个范围内都找不到满足条件的元素,则返回 last 参数指向的位置。
// 原型
template< class InputIt, class UnaryPredicate >
constexpr InputIt find_if( InputIt first, InputIt last, UnaryPredicate p );
//可能的实现
template<class InputIt, class UnaryPredicate>
InputIt find_if(InputIt first, InputIt last, UnaryPredicate p)
{
for (; first != last; ++first)
if (p(*first))
return first;
return last;
}
3.std::find_if_no
搜索谓词 q 对其返回 false 的元素,与find_if相反
//原型
template< class InputIt, class UnaryPredicate >
InputIt find_if_not( InputIt first, InputIt last, UnaryPredicate q );
//
template<class InputIt, class UnaryPredicate>
InputIt find_if_not(InputIt first, InputIt last, UnaryPredicate q)
{
for (; first != last; ++first)
if (!q(*first))
return first;
return last;
}
完整示例:
#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
int main()
{
int n1 = 3;
int n2 = 5;
std::vector<int> v{4, 1, 3, 2};
namespace ranges = std::ranges;
auto result1 = ranges::find(v, n1);
auto result2 = ranges::find(v.begin(), v.end(), n2);
if (result1 != v.end()) {
std::cout << "v contains: " << n1 << '\n';
} else {
std::cout << "v does not contain: " << n1 << '\n';
}
if (result2 != v.end()) {
std::cout << "v contains: " << n2 << '\n';
} else {
std::cout << "v does not contain: " << n2 << '\n';
}
auto is_even = [](int x) { return x % 2 == 0; };
auto divides_13 = [](int x) { return x % 13 == 0; };
auto result3 = ranges::find_if(v.begin(), v.end(), is_even);
auto result4 = ranges::find_if(v, divides_13);
if (result3 != v.end()) {
std::cout << "First even element in v: " << *result3 << '\n';
} else {
std::cout << "No even elements in v\n";
}
if (result4 != v.end()) {
std::cout << "First element divisible by 13 in v: " << *result4 << '\n';
} else {
std::cout << "No elements in v are divisible by 13\n";
}
auto result5 = ranges::find_if_not(v.begin(), v.end(), divides_13);
auto result6 = ranges::find_if_not(v, is_even);
if (result5 != v.end()) {
std::cout << "First element indivisible by 13 in v: " << *result5 << '\n';
} else {
std::cout << "No elements in v are divisible by 13\n";
}
if (result6 != v.end()) {
std::cout << "First odd element in v: " << *result6 << '\n';
} else {
std::cout << "No even elements in v\n";
}
}