描述
C++ 函數std::algorithm::adjacent_find()查找兩個相同的連續元素的第一次出現,如果相同元素連續存在,則返回指向第一個元素的迭代器,否則返回指向最後一個元素的迭代器。
聲明
以下是 std::algorithm::adjacent_find() 函數形式 std::algorithm 頭文件的聲明。
template <class ForwardIterator, class BinaryPredicate>
ForwardIterator adjacent_find(ForwardIterator first, ForwardIterator last, BinaryPredicate pred);
參數
first- 將迭代器轉發到搜索序列的初始位置。
last- 將迭代器轉發到搜索序列的最終位置。
pred- 這是一個接受兩個參數並返回的函數布爾。
返回值
如果相同元素連續存在,則返回指向第一個元素的迭代器,否則返回指向最後一個元素的迭代器。
異常
如果任何元素比較對象拋出異常,則拋出異常。
請注意,無效的參數會導致未定義的行為。
時間複雜度
之間的距離呈線性第一的和最後的。
示例
下麵的例子展示了 std::algorithm::adjacent_find() 函數的用法。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool predicate(int a, int b) {
return (a == b);
}
int main(void) {
vector<int> v = {1, 2, 3, 3, 4, 5, 5};
auto it = adjacent_find(v.begin(), v.end());
if (it != v.end())
cout << "First occurrence of consecutive identical element = "
<< *it << endl;
it = adjacent_find(++it, v.end(), predicate);
if (it != v.end())
cout << "Second occurrence of consecutive identical element = "
<< *it << endl;
return 0;
}
讓我們編譯並運行上麵的程序,這將產生以下結果 -
First occurrence of consecutive identical element = 3 Second occurrence of consecutive identical element = 5
相關用法
- C++ Algorithm any_of()用法及代碼示例
- C++ Algorithm all_of()用法及代碼示例
- C++ Algorithm copy()用法及代碼示例
- C++ Algorithm remove_if()用法及代碼示例
- C++ Algorithm remove()用法及代碼示例
- C++ Algorithm max_element()用法及代碼示例
- C++ Algorithm equal()用法及代碼示例
- C++ Algorithm set_union()用法及代碼示例
- C++ Algorithm next_permutation()用法及代碼示例
- C++ Algorithm upper_bound()用法及代碼示例
- C++ Algorithm minmax()用法及代碼示例
- C++ Algorithm remove_copy_if()用法及代碼示例
- C++ Algorithm find_if_not()用法及代碼示例
- C++ Algorithm for_each()用法及代碼示例
- C++ Algorithm pop_heap()用法及代碼示例
- C++ Algorithm replace_if()用法及代碼示例
- C++ Algorithm replace()用法及代碼示例
- C++ Algorithm set_intersection()用法及代碼示例
- C++ Algorithm transform()用法及代碼示例
- C++ Algorithm set_difference()用法及代碼示例
注:本文由純淨天空篩選整理自 C++ Algorithm Library - adjacent_find() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。