C++ STL adjacent_find 用法与实现
一:功能
在一个容器中查找相邻元素对,比如查找出相等的两个相邻元素,或查找满足给定条件的两个相邻元素。
二:用法
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> data = { 1, 2, 3, 4, 4, 5, 6, 7, 7, 8, 9 };
auto it1 = std::adjacent_find(data.begin(), data.end());
std::cout << "*it1 == " << *it1 << ", *std::next(it1) == " << *std::next(it1) << "\n";
auto it2 = std::adjacent_find(data.begin(), data.end(),
[](int l, int r) { return l + r > 10; });
std::cout << "*it2 == " << *it2 << ", *std::next(it2) == " << *std::next(it2) << "\n";
}
三:实现
template<class ForwardIt>
ForwardIt adjacent_find(ForwardIt first, ForwardIt last)
{
if (first == last)
return last;
ForwardIt next = first;
++next;
for (; next != last; ++next, ++first)
if (*first == *next)
return first;
return last;
}
template<class ForwardIt, class BinaryPred>
ForwardIt adjacent_find(ForwardIt first, ForwardIt last, BinaryPred p)
{
if (first == last)
return last;
ForwardIt next = first;
++next;
for (; next != last; ++next, ++first)
if (p(*first, *next))
return first;
return last;
}