STL adjacent_find()

本文内容来自C++Plus,本文只是本人的总结和翻译而已。本人只是C++的搬运工。

原文传送门:http://www.cplusplus.com/reference/algorithm/adjacent_find/


adjacent_find()算法:查找相邻且相等的元素。

作用:查找一个区间[First,Last)之间是否有相邻且相等的元素。若果有就返回这两个元素中的第一个元素的迭代器对象并且返回,如果一直没有找到就返回last。

template <class ForwardIterator>
   ForwardIterator adjacent_find (ForwardIterator first, ForwardIterator last)
{
  if (first != last)
  {
    ForwardIterator next=first; ++next;
    while (next != last) {
      if (*first == *next)     // or: if (pred(*first,*next)), for version (2)
        return first;
      ++first; ++next;
    }
  }
  return last;
}


#include <iostream>     // std::cout
#include <algorithm>    // std::adjacent_find
#include <vector>       // std::vector

bool myfunction (int i, int j) {
  return (i==j);
}

int main () {
  int myints[] = {5,20,5,30,30,20,10,10,20};
  std::vector<int> myvector (myints,myints+8);
  std::vector<int>::iterator it;

  // using default comparison:
  it = std::adjacent_find (myvector.begin(), myvector.end());

  if (it!=myvector.end())
    std::cout << "the first pair of repeated elements are: " << *it << '\n';

  //using predicate comparison:
  it = std::adjacent_find (++it, myvector.end(), myfunction);

  if (it!=myvector.end())
    std::cout << "the second pair of repeated elements are: " << *it << '\n';

  return 0;
}


注意点:

1. pred可以添加一个进行比较的条件,当调用这个bool函数的时候,就会按照里面设置好的条件查找,比如,查找两个相邻且相等都为奇数的数。

2. adjacent_find()算法如果不传递 perd 进去的话就只是一个在区间内查找相邻相等数的算法。

3.每次查找只会返回第一次找到的符合条件的两个相邻数,如果想在同一个空间内多次查找,只能拿着上次返回处的迭代器继续查找。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值