std::adjacent_find

From Cppreference

Jump to: navigation, search
Defined in header <algorithm>

template< class ForwardIterator >
ForwardIterator adjacent_find( ForwardIterator first, ForwardIterator last );
(1)
template< class ForwardIterator, BinaryPredicate p >
ForwardIterator adjacent_find( ForwardIterator first, ForwardIterator last, BinaryPredicate p );
(2)

Searches the range [first, last) for two consecutive identical elements. The first version uses operator== to compare the elements, the second version uses the given binary predicate p.

Contents

[edit] Parameters

first, last - the range of elements to examine
p - binary predicate which returns ​true if the elements should be treated as equal.

The signature of the predicate function should be equivalent to the following:

bool pred(const Type1 &a, const Type2 &b);

The signature does not need to have const &, but the function must not modify the objects passed to it.
The types Type1 and Type2 must be such that an object of type ForwardIterator can be dereferenced and then implicitly converted to both of them.

[edit] Return value

an iterator to the first of the identical elements. If no such elements are found, last is returned

[edit] Complexity

Exactly the smaller of (result - first) + 1 and (last - first) - 1 applications of the predicate where result is the return value.

[edit] Equivalent function

[edit] Example

The following code finds a pair of equivalent integers in an array of intergers.

#include <algorithm>
#include <iostream>
 
int main()
{
    std::vector<int> v1{0, 1, 2, 3, 4, 4, 5};
 
    std::vector<int>::iterator result;
    result = std::adjacent_find(v1.begin(), v1.end());
 
    if (result == v1.end()) {
        std::cout << "no matching adjacent elements";
    } else {
        std::cout << "match at: " << std::distance(v1.begin(), result);
    }
}

Output:

match at: 7

[edit] See also

unique
removes consecutive duplicate elements in a range
(function template)