std::adjacent_find
出自cppreference.com
| 在標頭 <algorithm> 定義
|
||
| (1) | (C++20 起為 constexpr) |
|
| |
(2) | (C++17 起) |
| (3) | (C++20 起為 constexpr) |
|
| |
(4) | (C++17 起) |
在範圍 [first, last) 中搜索兩個連續的相等元素。
1) 用
operator== 比較元素。3) 用給定的二元謂詞
p 比較元素。2,4) 同 (1,3),但按照
policy 執行。 這些重載只有在滿足以下所有條件時才會參與重載決議:
|
|
(C++20 前) |
|
|
(C++20 起) |
參數
| first, last | - | 要檢驗的元素範圍的迭代器對 |
| policy | - | 所用的執行策略 |
| p | - | 若元素應被當做相等則返回 true 的二元謂詞謂詞函數的簽名應等價於如下:
雖然簽名不必有 |
| 類型要求 | ||
-ForwardIt 必須滿足老式向前迭代器 (LegacyForwardIterator) 。
| ||
-BinaryPred 必須滿足二元謂詞 (BinaryPredicate) 。
| ||
返回值
指向首對等同元素的首個元素的迭代器,即首個滿足 *it == *(it + 1)(版本 (1,2))或 p(*it, *(it + 1)) != false(版本 (3,4))的迭代器 it。
如果找不到這種元素,那麼返回 last。
複雜度
給定 result 為 adjacent_find 的返回值,M 為 std::distance(first, result),N 為 std::distance(first, last):
1) 應用 min(M+1,N-1) 次
operator== 進行比較。2) 應用 O(N) 次
operator== 進行比較。3) 應用 min(M+1,N-1) 次謂詞
p。4) 應用 O(N) 次謂詞
p。異常
擁有名為 ExecutionPolicy 的模板形參的重載按下列方式報告錯誤:
- 如果作為算法一部分調用的函數的執行拋出異常,且
ExecutionPolicy是標準策略之一,那麼調用 std::terminate。對於任何其他ExecutionPolicy,行為由實現定義。 - 如果算法無法分配內存,那麼拋出 std::bad_alloc。
可能的實現
| adjacent_find (1) |
|---|
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;
}
|
| adjacent_find (3) |
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;
}
|
示例
運行此代碼
#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v1{0, 1, 2, 3, 40, 40, 41, 41, 5};
auto i1 = std::adjacent_find(v1.begin(), v1.end());
if (i1 == v1.end())
std::cout << "没有匹配的相邻元素\n";
else
std::cout << "第一对相等的相邻元素位于 "
<< std::distance(v1.begin(), i1) << ",*i1 = "
<< *i1 << '\n';
auto i2 = std::adjacent_find(v1.begin(), v1.end(), std::greater<int>());
if (i2 == v1.end())
std::cout << "整个 vector 已经是升序的\n";
else
std::cout << "非降序子序列中最后的元素位于 "
<< std::distance(v1.begin(), i2) << ",*i2 = " << *i2 << '\n';
}
輸出:
第一对相等的相邻元素位于 4,*i1 = 40
非降序子序列中最后的元素位于 7,*i2 = 41
缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
| 缺陷報告 | 應用於 | 出版時的行為 | 正確行為 |
|---|---|---|---|
| LWG 240 | C++98 | (1,3) 中謂詞會應用 std::find(first, last,value) - first 次,但 value 沒有定義
|
應用 std::min((result - first)+ 1, (last - first) - 1) 次
|
參閱
| 移除範圍中連續重複元素 (函數模板) | |
(C++20) |
查找首對相同(或滿足給定謂詞)的相鄰元素 (算法函數對象) |