本文內容來自C++Plus,本文只是本人的總結和翻譯而已。本人只是C++的搬運工。
原文傳送門:http://www.cplusplus.com/reference/algorithm/adjacent_find/
adjacent_find()算法:查找相鄰且相等的元素。
作用:查找一個區間[First,Last)之間是否有相鄰且相等的元素。若果有就返回這兩個元素中的第一個元素的迭代器對象並且返回,如果一直沒有找到就返回last。
template <class ForwardIterator>
ForwardIterator adjacent_find (ForwardIterator first, ForwardIterator last)
{
if (first != last)
{
ForwardIterator next=first; ++next;
while (next != last) {
if (*first == *next) // or: if (pred(*first,*next)), for version (2)
return first;
++first; ++next;
}
}
return last;
}
#include <iostream> // std::cout
#include <algorithm> // std::adjacent_find
#include <vector> // std::vector
bool myfunction (int i, int j) {
return (i==j);
}
int main () {
int myints[] = {5,20,5,30,30,20,10,10,20};
std::vector<int> myvector (myints,myints+8);
std::vector<int>::iterator it;
// using default comparison:
it = std::adjacent_find (myvector.begin(), myvector.end());
if (it!=myvector.end())
std::cout << "the first pair of repeated elements are: " << *it << '\n';
//using predicate comparison:
it = std::adjacent_find (++it, myvector.end(), myfunction);
if (it!=myvector.end())
std::cout << "the second pair of repeated elements are: " << *it << '\n';
return 0;
}
注意點:
1. pred可以添加一個進行比較的條件,當調用這個bool函數的時候,就會按照裏面設置好的條件查找,比如,查找兩個相鄰且相等都爲奇數的數。
2. adjacent_find()算法如果不傳遞 perd 進去的話就只是一個在區間內查找相鄰相等數的算法。
3.每次查找只會返回第一次找到的符合條件的兩個相鄰數,如果想在同一個空間內多次查找,只能拿着上次返回處的迭代器繼續查找。