std::adjacent_find in C++
Last Updated :
20 Aug, 2021
Searches the range [first, last) for the first occurrence of two consecutive elements that match, and returns an iterator to the first of these two elements, or last if no such pair is found. Elements are compared using the given binary predicate p or using ==.
There are two possible implementations of the function as given below:
1. Without binary predicate:
ForwardIt adjacent_find( ForwardIt first, ForwardIt last );
first, last : the range of elements to examine
Example :
Given a sorted array of n elements containing all unique elements but one, the task is to find the repeating element in the array.
Examples:
Input : arr[] = { 1, 2, 3, 4, 4}
Output : 4
Input : arr[] = { 1, 1, 2, 3, 4}
Output : 1
We have discussed this problem with other approaches here.
C++
#include <iostream>
#include <algorithm>
int main()
{
int A[] = { 10, 13, 16, 16, 18 };
int n = sizeof (A) / sizeof (A[0]);
int * it = std::adjacent_find(A, A + n);
std::cout << *it;
}
|
Output:
16
2. With binary predicate:
ForwardIt adjacent_find( ForwardIt first, ForwardIt last, BinaryPredicate p );
first, last : the range of elements to examine
p : binary predicate which returns true
if the elements should be treated as equal.
Return value :
An iterator to the first of the first pair of identical elements, '
that is, the first iterator it such that *it == *(it+1) for the first
version or p(*it, *(it + 1)) != false for the second version.
If no such elements are found, last is returned.
Example:
Given a container of size n, and a range between [0 … n], write a program to check if it is sorted in ascending order or not. Equal values are allowed in array and two consecutive equal values are considered sorted.
Input : 2 5 9 4 // Range = 3
Output : Sorted in given range.
Input : 3 5 1 9 // Range = 3
Output : Not sorted in given range.
C++
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
std::vector< int > vec{ 0, 1, 2, 5, 40, 40, 41, 41, 5 };
int range1 = 5;
int range2 = 9;
std::vector< int >::iterator it;
it = std::adjacent_find(vec.begin(),
vec.begin() + range1, std::greater< int >());
if (it == vec.begin() + range1)
{
std::cout << "Sorted in the range : " << range1 << std::endl;
}
else
{
std::cout << "Not sorted in the range : " << range1 << std::endl;
}
it = std::adjacent_find(vec.begin(),
vec.begin() + range2, std::greater< int >());
if (it == vec.begin() + range2)
{
std::cout << "Sorted in the range : " << range2 << std::endl;
}
else
{
std::cout << "Not sorted in the range : " << range2 << std::endl;
}
}
|
Output:
Sorted in the range : 5
Not sorted in the range : 9
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...