Home C&C++函数库 c++ 语法 程序源码 Linux C库

std::

search_n

函数模板  <algorithm>
equality (1)
template <class ForwardIterator, class Size, class T>
   ForwardIterator search_n (ForwardIterator first, ForwardIterator last,
                             Size count, const T& val);
predicate(2)
template <class ForwardIterator, class Size, class T, class BinaryPredicate>
   ForwardIterator search_n ( ForwardIterator first, ForwardIterator last,
                              Size count, const T& val, BinaryPredicate pred );

搜索范围的部分元素

在范围[first,last)中搜索count个元素序列,每个比较值都等于val(或者pred返回true)。

该函数返回此元素序列的第一个迭代器,如果没有找到此元素序列,则返回last。

这个函数模板的行为相当于:
template<class ForwardIterator, class Size, class T>
  ForwardIterator search_n (ForwardIterator first, ForwardIterator last,
                            Size count, const T& val)
{
  ForwardIterator it, limit;
  Size i;

  limit=first; std::advance(limit,std::distance(first,last)-count);

  while (first!=limit)
  {
    it = first; i=0;
    while (*it==val)       // or: while (pred(*it,val)) for the pred version
      { ++it; if (++i==count) return first; }
    ++first;
  }
  return last;
}

☲  参数


first1, last1
指向一个序列初始和最终位置的前向迭代器。使用的范围是[first1,last1), 它包含first1和last1之间的所有元素,包括first1指向的元素,但不包括last1指向的元素。
count
要匹配的最小连续元素个数。Size 应为(可转换为)整型。
val
要比较的单个值,或用作pred的参数(在第二个版本中)。
对于第一个版本,T应该是一种支持与前向迭代器使用operator==所指向的元素进行比较的类型(这些元素作为左侧大小的操作数,val作为右侧)。
pred
接受两个元素(序列中的一个元素作为第一个参数,val作为第二个参数)作为参数并返回可转换为bool的值的二元函数。 返回值指示元素在此函数当前环境中是否被认为匹配。
函数不能修改它的任何参数。
它可以是函数指针,也可以是函数对象。

☉  返回值



指向元素序列第一个元素的迭代器。
如果没有找到这样的元素序列,函数最后返回。

☣  示例



// search_n example
#include <iostream>     // std::cout
#include <algorithm>    // std::search_n
#include <vector>       // std::vector

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

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

  std::vector<int>::iterator it;

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

  if (it!=myvector.end())
    std::cout << "two 30s found at position " << (it-myvector.begin()) << '\n';
  else
    std::cout << "match not found\n";

  // using predicate comparison:
  it = std::search_n (myvector.begin(), myvector.end(), 2, 10, mypredicate);

  if (it!=myvector.end())
    std::cout << "two 10s found at position " << int(it-myvector.begin()) << '\n';
  else
    std::cout << "match not found\n";

  return 0;
}

输出:
Two 30s found at position 2
Two 10s found at position 5

✥ 复杂度



在first and last中接近线性(其中countX是firstX和lastX之间的距离):比较元素直到找到匹配的子序列。

⇄ 数据竞争


两个范围内的部分(或全部)对象被访问(最多一次)。

☂ 异常安全性



如果任何元素比较(或pred)或迭代器上的任何操作抛出,则抛出。
注意,无效的参数会导致未定义的行为。

🍄  另请参阅



equal 测试两个范围内的元素是否相等(函数模板)
find 在范围内查找值(函数模板)
find_first_of 从设置的范围查找元素(函数模板)
search 搜索范围的子序列(函数模板)

联系我们 免责声明 关于CandCplus 网站地图