在范围[first,last)中搜索匹配的两个连续元素的第一个匹配项,然后将迭代器返回到这两个元素中的第一个,如果没有找到这样的对,则返回last。使用给定的二进制谓词p或使用==比较元素。
有下面给出的函数的两种可能的实现:
- 没有二进制谓词:
ForwardIt adjacent_find( ForwardIt first, ForwardIt last ); first, last : the range of elements to examine
例子 :
给定n个元素的排序数组,其中包含除一个之外的所有唯一元素,任务是在数组中找到重复元素。
例子:Input : arr[] = { 1, 2, 3, 4, 4} Output : 4 Input : arr[] = { 1, 1, 2, 3, 4} Output : 1
我们已经在这里与其他方法讨论了这个问题。
// CPP Program to find the only // repeating element in sorted array // using std :: adjacent_find // without predicate #include
#include int main() { // Sorted Array with a repeated element int A[] = { 10, 13, 16, 16, 18 }; // Size of the array int n = sizeof(A) / sizeof(A[0]); // Iterator pointer which points to the address of the repeted element int* it = std::adjacent_find(A, A + n); // Printing the result std::cout << *it; } 输出:
16
- 使用二进制谓词:
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.
例子:
给定一个大小为n且范围在[0…n]之间的容器,编写一个程序来检查它是否按升序排序。数组中允许相等的值,并且认为两个连续的相等值已排序。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.
// CPP program to illustrate // std :: adjacent_find' // with binary predicate #include
#include #include int main() { std::vector vec{ 0, 1, 2, 5, 40, 40, 41, 41, 5 }; // Index 0 to 4 int range1 = 5; // Index 0 to 8 int range2 = 9; std::vector ::iterator it; // Iterating from 0 to range1, // till we get a decreasing element it = std::adjacent_find(vec.begin(), vec.begin() + range1, std::greater ()); 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; } // Iterating from 0 to range2, // till we get a decreasing element it = std::adjacent_find(vec.begin(), vec.begin() + range2, std::greater ()); 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; } } 输出:
Sorted in the range : 5 Not sorted in the range : 9
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。