當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ adjacent_find()用法及代碼示例

C++ 算法 adjacent_find() 函數在範圍 [first, last] 上對兩個連續匹配元素的第一次出現執行搜索操作。如果找到這樣的元素,則返回指向兩個元素中第一個元素的迭代器。否則,返回最後一個元素。

用法

template<class ForwardIterator>
ForwardIterator adjacent_find(ForwardIterator first, ForwardIterator last);

template<class ForwardIterator, class BinaryPredicate>
ForwardIterator adjacent_find(ForwardIterator first,ForwardIterator last BinaryPredicate pred);

參數

first: 它是指向範圍內第一個元素的前向迭代器。

last: 它是到範圍內最後一個元素的前向迭代器。

pred: 它是一個二元函數,它接受兩個元素作為參數並執行函數設計的任務。

返回值

如果找到兩個連續的匹配元素,則該函數返回指向範圍 [first,last) 的第一個元素的迭代器,否則返回最後一個元素。

例子1

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
bool myfunc(int j, int k)
{
    return(j==k);
}


int main()
{
    int newints[]={5,20,5,50,50,20,60,60,20};
    std::vector<int> newvector(newints, newints+8);
    std::vector<int>::iterator ti;
    ti=std::adjacent_find(newvector.begin(),newvector.end());
    if(ti!=newvector.end())
    std::cout<<"In the given range the first pair of sequence that is repeated is:"<<*ti<<"\n";
    ti=std::adjacent_find(++ti,newvector.end(),myfunc);
    if(ti!=newvector.end())
    std::cout<<"In the given range the second pair of sequence 	that is repeated is:"<<*ti<<"\n";
    return 0;
}

輸出:

In the given range the first pair of sequence that is repeated are:50
In the given range the second pair of sequence that is repeated are:60

例子2

#include<iostream>
#include<algorithm>
int main()
{
    int A[]={12,14,17,17,19};
    int n=sizeof(A)/sizeof(A[0]);
    int* ti=std::adjacent_find(A,A+n);
    std::cout<<*ti;
}

輸出:

17

複雜度

函數的複雜度是線性的,直到第一個和最後一個元素之間的距離。

數據競爭

訪問範圍的部分或全部元素。

異常

如果任何參數拋出異常,該函數將拋出異常。






相關用法


注:本文由純淨天空篩選整理自 C++ Algorithm Function adjacent_find()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。