函式模板
<algorithm>

std::mismatch

相等 (1)
template <class InputIterator1, class InputIterator2>  pair<InputIterator1, InputIterator2>    mismatch (InputIterator1 first1, InputIterator1 last1,              InputIterator2 first2);
謂詞 (2)
template <class InputIterator1, class InputIterator2, class BinaryPredicate>  pair<InputIterator1, InputIterator2>    mismatch (InputIterator1 first1, InputIterator1 last1,              InputIterator2 first2, BinaryPredicate pred);
返回兩個範圍不匹配的第一個位置
將範圍 [first1,last1)中的元素與從first2開始的範圍中的元素進行比較,並返回兩個序列中第一個不匹配的元素。

元素使用operator==(或版本(2)中的pred)進行比較。

該函式返回一個指向兩個序列中第一個不匹配元素的pair迭代器。

此函式模板的行為等同於
1
2
3
4
5
6
7
8
template <class InputIterator1, class InputIterator2>
  pair<InputIterator1, InputIterator2>
    mismatch (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2 )
{
  while ( (first1!=last1) && (*first1==*first2) )  // or: pred(*first1,*first2), for version 2
  { ++first1; ++first2; }
  return std::make_pair(first1,first2);
}

引數

first1, last1
輸入迭代器,指向第一個序列的起始和結束位置。使用的範圍是[first1,last1),它包含first1last1之間的所有元素,包括first1指向的元素,但不包括last1指向的元素。
first2
輸入迭代器,指向第二個序列的起始位置。該函式最多可以訪問與範圍[first1,last1)相同數量的元素。
pred
二元函式,接受兩個元素作為引數(分別來自兩個序列中的一個,順序相同),並返回一個可轉換為bool的值。返回值表示在函式上下文中元素是否被視為匹配。
該函式不得修改其任何引數。
這可以是函式指標或函式物件。

返回值

一個pair,其成員firstsecond指向兩個序列中第一個互不相等的元素。
如果兩個序列中比較的元素都匹配,則函式返回一個pair,其中first設定為last1second設定為第二個序列中相同相對位置的元素。
如果沒有匹配項,則返回make_pair(first1,first2)

示例

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
// mismatch algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::mismatch
#include <vector>       // std::vector
#include <utility>      // std::pair

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

int main () {
  std::vector<int> myvector;
  for (int i=1; i<6; i++) myvector.push_back (i*10); // myvector: 10 20 30 40 50

  int myints[] = {10,20,80,320,1024};                //   myints: 10 20 80 320 1024

  std::pair<std::vector<int>::iterator,int*> mypair;

  // using default comparison:
  mypair = std::mismatch (myvector.begin(), myvector.end(), myints);
  std::cout << "First mismatching elements: " << *mypair.first;
  std::cout << " and " << *mypair.second << '\n';

  ++mypair.first; ++mypair.second;

  // using predicate comparison:
  mypair = std::mismatch (mypair.first, myvector.end(), mypair.second, mypredicate);
  std::cout << "Second mismatching elements: " << *mypair.first;
  std::cout << " and " << *mypair.second << '\n';

  return 0;
}

輸出
First mismatching elements: 30 and 80
Second mismatching elements: 40 and 320


複雜度

最多線性於first1last1之間的距離:比較元素直到找到不匹配項。

資料競爭

兩個範圍中的一些(或全部)物件被訪問(最多一次)。

異常

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

另見