std::find_first_of
Определено в заголовке <algorithm> | ||
|---|---|---|
| (1) | ||
template< class InputIt, class ForwardIt >
InputIt find_first_of( InputIt first, InputIt last,
ForwardIt s_first, ForwardIt s_last ); | (до C++20) | |
template< class InputIt, class ForwardIt >
constexpr InputIt find_first_of( InputIt first, InputIt last,
ForwardIt s_first, ForwardIt s_last );
| (с C++20) | |
template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 >
ForwardIt1 find_first_of( ExecutionPolicy&& policy,
ForwardIt1 first, ForwardIt1 last,
ForwardIt2 s_first, ForwardIt2 s_last );
| (2) | (с C++17) |
| (3) | ||
template< class InputIt, class ForwardIt, class BinaryPredicate >
InputIt find_first_of( InputIt first, InputIt last,
ForwardIt s_first, ForwardIt s_last,
BinaryPredicate p ); | (до C++20) | |
template< class InputIt, class ForwardIt, class BinaryPredicate >
constexpr InputIt find_first_of( InputIt first, InputIt last,
ForwardIt s_first, ForwardIt s_last,
BinaryPredicate p );
| (с C++20) | |
template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2,
class BinaryPredicate >
ForwardIt1 find_first_of( ExecutionPolicy&& policy,
ForwardIt1 first, ForwardIt last,
ForwardIt2 s_first, ForwardIt2 s_last,
BinaryPredicate p );
| (4) | (с C++17) |
Ищет в диапазоне [first, last) любой из элементов в диапазоне [s_first, s_last).
operator==.p.policy. Эти перегрузки не участвуют в разрешении перегрузки, если |
| (до C++20) |
|
| (с C++20) |
Параметры
| first, last | - | диапазон элементов для проверки |
| s_first, s_last | - | диапазон элементов для поиска |
| policy | - | политика выполнения. Подробнее см. в политике выполнения. |
| p | - | бинарный предикат, возвращающий true , если элементы следует считать равными. Подпись предикатной функции должна быть эквивалентна следующей:
Хотя подпись не обязательно должна содержать |
| Требования к типу | ||
-InputIt должно удовлетворять требованиям LegacyInputIterator. |
||
-ForwardIt должно удовлетворять требованиям LegacyForwardIterator. |
||
-ForwardIt1 должно удовлетворять требованиям LegacyForwardIterator. |
||
-ForwardIt2 должно удовлетворять требованиям LegacyForwardIterator. |
||
-BinaryPredicate должно удовлетворять требованиям BinaryPredicate. |
||
Возвращаемое значение
Итератор на первый элемент в диапазоне [first, last) , который равен элементу из диапазона [s_first, s_last).
Если [s_first, s_last) пуст или такой элемент не найден, возвращается last.
Сложность
Пусть \(\scriptsize N\)N обозначает std::distance(first, last) и \(\scriptsize S\)S обозначает std::distance(s_first, s_last):
operator==.p.Исключения
Перегрузки с параметром шаблона по имени ExecutionPolicy сообщают об ошибках следующим образом:
- Если выполнение функции, вызываемой как часть алгоритма, вызывает исключение, и
ExecutionPolicyявляется одной из стандартных политик, вызываетсяstd::terminate. Для любой другойExecutionPolicy, поведение является реализационно-зависимым. - Если алгоритм не может выделить память, выбрасывается
std::bad_alloc.
Возможная реализация
| find_first_of (1) |
|---|
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;
} |
| find_first_of (3) |
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>
auto print_sequence = [](auto const id, auto const& seq, int pos = -1)
{
std::cout << id << "{ ";
for (int i{}; auto const& e : seq)
{
const bool mark{i == pos};
std::cout << (i++ ? ", " : "");
std::cout << (mark ? "[ " : "") << e << (mark ? " ]" : "");
}
std::cout << " }\n";
};
int main()
{
const std::vector<int> v{0, 2, 3, 25, 5};
const auto t1 = {19, 10, 3, 4};
const auto t2 = {1, 6, 7, 9};
auto find_any_of = [](const auto& v, const auto& t)
{
const auto result = std::find_first_of(v.begin(), v.end(),
t.begin(), t.end());
if (result == v.end())
{
std::cout << "No elements of v are equal to any element of ";
print_sequence("t = ", t);
print_sequence("v = ", v);
}
else
{
const auto pos = std::distance(v.begin(), result);
std::cout << "Found a match (" << *result << ") at position " << pos;
print_sequence(", where t = ", t);
print_sequence("v = ", v, pos);
}
};
find_any_of(v, t1);
find_any_of(v, t2);
}Вывод:
Found a match (3) at position 2, where t = { 19, 10, 3, 4 }
v = { 0, 2, [ 3 ], 25, 5 }
No elements of v are equal to any element of t = { 1, 6, 7, 9 }
v = { 0, 2, 3, 25, 5 }Отчеты об ошибках
Следующие отчеты об ошибках, изменяющие поведение, были применены ретроактивно к ранее опубликованным стандартам C++.
| DR | Применён к | Поведение, опубликованное | Корректное поведение |
|---|---|---|---|
| LWG 576 | C++98 |
first и last должны были быть LegacyForwardIterators | им необходимо быть только LegacyInputIterators |
| LWG 1205 | C++98 | значение возврата было неясным, если [s_first, s_last) пусто | в этом случае возвращается last |
См. также
|
(C++11) | находит первый элемент, удовлетворяющий определённым критериям (шаблон функции) |
|
(C++20) | ищет любой из набора элементов (niebloid) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/algorithm/find_first_of