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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
STL(标准模板库)提供了许多算法函数来处理容器。要检查容器中是否存在相同项,可以使用 `std::adjacent_find` 算法函数。 `std::adjacent_find` 函数接受两个迭代器作为参数,并在区间内查找相邻元素相等的第一个位置。如果找到相同项,则返回指向该位置的迭代器;否则,返回指向区间末尾的迭代器。 以下是使用 `std::adjacent_find` 函数检查容器中是否存在相同项的示例代码: ```cpp #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 11}; auto it = std::adjacent_find(numbers.begin(), numbers.end()); if (it != numbers.end()) { std::cout << "Found a pair of adjacent elements with the same value: " << *it << std::endl; } else { std::cout << "No adjacent elements with the same value found." << std::endl; } return 0; } ``` 上述代码中,我们创建了一个 `std::vector` 容器 `numbers`,其中包含了一些整数。然后,我们使用 `std::adjacent_find` 函数来查找相邻元素相等的第一个位置。如果找到了相同项,我们输出该值;否则,输出未找到相同项的消息。 注意:`std::adjacent_find` 函数默认使用 `operator==` 进行元素比较,因此容器中的元素类型需要支持相等比较运算符(`==`)。如果需要使用自定义的比较函数,可以提供一个谓词作为额外的参数给 `std::adjacent_find` 函数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值