函式模板
<algorithm>

std::search_n

相等 (1)
template <class ForwardIterator, class Size, class T>   ForwardIterator search_n (ForwardIterator first, ForwardIterator last,                             Size count, const T& val);
謂詞 (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

此函式模板的行為等同於
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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;
}

引數

first, last
指向被搜尋序列的初始和末尾位置的正向迭代器。使用的範圍是 [first,last),它包含 firstlast 之間的所有元素,包括 first 指向的元素,但不包括 last 指向的元素。
count
要匹配的連續元素的最小數量。
Size 必須是(可轉換為)整數型別。
val
要比較的單個值,或用作 pred 的引數(在第二個版本中)。
對於第一個版本,T 必須是支援與 InputIterator 所指向元素進行比較的型別,使用 operator==(其中序列中的元素是左側運算元,val 是右側運算元)。
pred
二元函式,接受兩個引數(序列中的一個元素作為第一個引數,val 作為第二個引數),並返回一個可轉換為 bool 的值。返回值指示該元素在此函式上下文中是否被視為匹配。
該函式不得修改其任何引數。
這可以是一個函式指標或一個函式物件。

返回值

指向序列第一個元素的迭代器。
如果未找到這樣的序列,函式將返回 last

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// 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



複雜度

最多線性於 firstlast 之間的 距離:比較元素直到找到匹配的子序列。

資料競爭

範圍 [first,last) 中的一些(或全部)物件被訪問(最多一次)。

異常

如果任何元素比較(或 pred)丟擲異常,或者任何迭代器操作丟擲異常,則丟擲異常。
請注意,無效的引數會導致 *未定義行為*。

另見