在範圍[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 <iostream> #include <algorithm> 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 <algorithm> #include <iostream> #include <vector> int main() { std::vector<int> 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<int>::iterator it; // Iterating from 0 to range1, // till we get a decreasing element 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; } // Iterating from 0 to range2, // till we get a decreasing element 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; } }
輸出:
Sorted in the range:5 Not sorted in the range:9
相關用法
注:本文由純淨天空篩選整理自 std::adjacent_find in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。