Cpp std vector find

Cpp std vector find

Функция std::find() ищет на определенном диапазоне элементов определенное значение. Для сравнения значений применяется операция сравнения ==. Рассмотрим одну из версий функции:

std::find(start_iterator, end_iterator, value)

Для установки диапазона в функцию передаются итератор на начало и конец диапазона и значение, которое надо найти. Результат функции — итератор на найденное значение. Если же значение не найдено, то возвращаемый итератор указывает на конец диапазона. Например, попробуем найти в векторе чисел некоторые числа

#include #include #include void findValue (const std::vector& data, int value) < auto result< std::find(begin(data), end(data), value) >; if (result == end(data)) std::cout int main() < std::vectornumbers < 1, 2, 3, 4, 5, 6, 7, 8>; findValue(numbers, 4); // Value found at position 3 findValue(numbers, 12); // Value not found >

В данном случае поиск вынесен в отдельную функцию — findValue. В ней ищем в векторе чисел некоторое число. В качестве начала и конца диапазона для поиска в функцию std::find() передаются итераторы на начало и конец вектор:

Если число не найдено, то полученный итератор равен итератору на конец вектора:

Если же число найдено, то вычитая из полученного итератора итератор на начало вектора, мы можем получить индекс числа в векторе:

Поиск по условию

Ряд дополнительных функций возвращают итератор на значение в зависимости от некоторого условия. Функция std::find_if() возвращает итератор на первый элемент диапазона, который удовлетворяет некоторому условию. А функция std::find_if_not() , наоброт, возвращает итератор на первый элемент диапазона, который НЕ удовлетворяет некоторому условиЮ. Посмотрим на примере функции std::find_if() :

#include #include #include // если число четное bool is_even(int n) < return n % 2 == 0;>// если число положительное bool is_positive(int n) < return n >0;> // если число больше 10 bool is_greater10(int n) < return n >10;> template void findValue (const std::vector& data, bool(*condition)(T)) < auto result< std::find_if(begin(data), end(data), condition) >; if (result == end(data)) std::cout int main() < std::vectornumbers < -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5>; findValue(numbers, is_even); // Value found at position 1 findValue(numbers, is_positive); // Value found at position 6 findValue(numbers, is_greater10); // Value not found >

Функция std::find_if() также получает итераторы на начало и конец дипазона для поиска, а третий параметр представляет условие, которому должны удовлетворять значения:

std::find_if(begin(data), end(data), condition)

Условие представляет функцию, которая принимает некоторое значение произвольного типа и возвращает значение типа bool — true , если значение соответствует условию, и false , если не соответствует. Фактически условие можно описать указателем на функцию bool(*condition)(T) , где T- произвольный тип.

Читайте также:  Ним2 пасьянс python задача

Для теста здесь определены три функции, которые представляют условия: is_even() (проверяет, является ли число четным), is_positive() (если число положительное) и is_greater10() (если число больше 10).

Функция std::find_if() возвращает итератор на первое найденное значение, которое удовлетворяет условию. Если таких значений не найдено, то итератор указывает на конец диапазона.

Принцип работы std::find_if_not() будет аналогичен.

Источник

std:: find

Returns an iterator to the first element in the range [first,last) that compares equal to val . If no such element is found, the function returns last .

The function uses operator== to compare the individual elements to val .

The behavior of this function template is equivalent to:

templateclass InputIterator, class T> InputIterator find (InputIterator first, InputIterator last, const T& val) < while (first!=last) < if (*first==val) return first; ++first; > return last; >

Parameters

first, last Input iterators to the initial and final positions in a sequence. The range searched is [first,last) , which contains all the elements between first and last , including the element pointed by first but not the element pointed by last . val Value to search for in the range.
T shall be a type supporting comparisons with the elements pointed by InputIterator using operator== (with the elements as left-hand side operands, and val as right-hand side).

Return value

An iterator to the first element in the range that compares equal to val .
If no elements match, the function returns last .

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// find example // std::cout // std::find // std::vector int main () < // using std::find with array and pointer: int myints[] = < 10, 20, 30, 40 >; int * p; p = std::find (myints, myints+4, 30); if (p != myints+4) std::cout "Element found in myints: " << *p '\n'; else std::cout "Element not found in myints\n"; // using std::find with vector and iterator: std::vectorint> myvector (myints,myints+4); std::vectorint>::iterator it; it = find (myvector.begin(), myvector.end(), 30); if (it != myvector.end()) std::cout "Element found in myvector: " << *it '\n'; else std::cout "Element not found in myvector\n"; return 0; >
Element found in myints: 30 Element found in myvector: 30 

Complexity

Data races

Exceptions

Throws if either an element comparison or an operation on an iterator throws.
Note that invalid arguments cause undefined behavior.

See also

search Search range for subsequence (function template) binary_search Test if value exists in sorted sequence (function template) for_each Apply function to range (function template)

Источник

std:: find, std:: find_if, std:: find_if_not

Returns an iterator to the first element in the range [ first , last ) that satisfies specific criteria (or last if there is no such iterator):

2,4,6) Same as (1,3,5) , but executed according to policy . These overloads do not participate in overload resolution unless

Contents

[edit] Parameters

first, last the range of elements to examine
value value to compare the elements to
policy the execution policy to use. See execution policy for details.
p unary predicate which returns ​ true for the required element.

The expression p ( v ) must be convertible to bool for every argument v of type (possibly const) VT , where VT is the value type of InputIt , regardless of value category, and must not modify v . Thus, a parameter type of VT & is not allowed , nor is VT unless for VT a move is equivalent to a copy (since C++11) . ​

The expression q ( v ) must be convertible to bool for every argument v of type (possibly const) VT , where VT is the value type of InputIt , regardless of value category, and must not modify v . Thus, a parameter type of VT & is not allowed , nor is VT unless for VT a move is equivalent to a copy (since C++11) . ​

[edit] Return value

The first iterator it in the range [ first , last ) satisfying the following condition or last if there is no such iterator:

[edit] Complexity

[edit] Exceptions

The overloads with a template parameter named ExecutionPolicy report errors as follows:

  • If execution of a function invoked as part of the algorithm throws an exception and ExecutionPolicy is one of the standard policies, std::terminate is called. For any other ExecutionPolicy , the behavior is implementation-defined.
  • If the algorithm fails to allocate memory, std::bad_alloc is thrown.

[edit] Possible implementation

templateclass InputIt, class T> constexpr InputIt find(InputIt first, InputIt last, const T& value) { for (; first != last; ++first) if (*first == value) return first; return last; }
templateclass InputIt, class UnaryPredicate> constexpr InputIt find_if(InputIt first, InputIt last, UnaryPredicate p) { for (; first != last; ++first) if (p(*first)) return first; return last; }
templateclass InputIt, class UnaryPredicate> constexpr InputIt find_if_not(InputIt first, InputIt last, UnaryPredicate q) { for (; first != last; ++first) if (!q(*first)) return first; return last; }

[edit] Notes

If you do not have C++11, an equivalent to std::find_if_not is to use std::find_if with the negated predicate.

[edit] Example

The following example finds integers in given std::vector .

#include #include #include int main() { const auto v = {1, 2, 3, 4}; for (int n : {3, 5}) (std::find(v.begin(), v.end(), n) == std::end(v)) ? std::cout  "v does not contain "  n  '\n' : std::cout  "v contains "  n  '\n'; auto is_even = [](int i) { return i % 2 == 0; }; for (auto const& w : {std::array{3, 1, 4}, {1, 3, 5}}) if (auto it = std::find_if(begin(w), end(w), is_even); it != std::end(w)) std::cout  "w contains an even number "  *it  '\n'; else std::cout  "w does not contain even numbers\n"; }
v contains 3 v does not contain 5 w contains an even number 4 w does not contain even numbers

[edit] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
LWG 283 C++98 T was required to be EqualityComparable , but
the value type of InputIt is not always T
removed the requirement

Источник

std:: find

Returns an iterator to the first element in the range [first,last) that compares equal to val . If no such element is found, the function returns last .

The function uses operator== to compare the individual elements to val .

The behavior of this function template is equivalent to:

templateclass InputIterator, class T> InputIterator find (InputIterator first, InputIterator last, const T& val) < while (first!=last) < if (*first==val) return first; ++first; > return last; >

Parameters

first, last Input iterators to the initial and final positions in a sequence. The range searched is [first,last) , which contains all the elements between first and last , including the element pointed by first but not the element pointed by last . val Value to search for in the range.
T shall be a type supporting comparisons with the elements pointed by InputIterator using operator== (with the elements as left-hand side operands, and val as right-hand side).

Return value

An iterator to the first element in the range that compares equal to val .
If no elements match, the function returns last .

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// find example // std::cout // std::find // std::vector int main () < // using std::find with array and pointer: int myints[] = < 10, 20, 30, 40 >; int * p; p = std::find (myints, myints+4, 30); if (p != myints+4) std::cout "Element found in myints: " << *p '\n'; else std::cout "Element not found in myints\n"; // using std::find with vector and iterator: std::vectorint> myvector (myints,myints+4); std::vectorint>::iterator it; it = find (myvector.begin(), myvector.end(), 30); if (it != myvector.end()) std::cout "Element found in myvector: " << *it '\n'; else std::cout "Element not found in myvector\n"; return 0; >
Element found in myints: 30 Element found in myvector: 30 

Complexity

Data races

Exceptions

Throws if either an element comparison or an operation on an iterator throws.
Note that invalid arguments cause undefined behavior.

See also

search Search range for subsequence (function template) binary_search Test if value exists in sorted sequence (function template) for_each Apply function to range (function template)

Источник

Оцените статью