c++ std標準庫 演算法<algorithm> 在指定範圍內查詢 2 個連續相等的元素 adjacent_find()
阿新 • • 發佈:2020-12-19
技術標籤:# 4.1 C++c++adjacent_find
std::adjacent_find
簡介:
在指定範圍內查詢 2 個連續相等的元素。
函式原型
equality (1) template <class ForwardIterator>
ForwardIterator adjacent_find (ForwardIterator first, ForwardIterator last);
predicate (2) template <class ForwardIterator, class BinaryPredicate>
ForwardIterator adjacent_find ( ForwardIterator first, ForwardIterator last, BinaryPredicate pred);
官方手冊
http://www.cplusplus.com/reference/algorithm/adjacent_find/
使用示例:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
void print(int& Ele)
{
cout << Ele << ", " ;
}
bool doubleS(int ele1, int ele2)
{
return ele1 * 2 == ele2;
}
void main()
{
vector<int> v1;
vector<int>::iterator it;
v1.push_back(1);
v1.push_back(3);
v1.push_back(3);
v1.push_back(2);
v1.push_back(4);
v1.push_back(5);
v1.push_back(5);
v1.push_back(0);
for_each(v1.begin (), v1.end(), print);
cout << endl;
it = adjacent_find(v1.begin(), v1.end());
if (it != v1.end())
{
cout << "查詢連續相等的位置:" << distance(v1.begin(), it) + 1 << endl;
}
it = adjacent_find(v1.begin(), v1.end(), doubleS);
if (it != v1.end())
{
cout << "查詢第1個是下一個1/2的位置:" << distance(v1.begin(), it) + 1 << endl;
}
}