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

std::

mismatch

函数模板  <algorithm>
equality (1)
template <class InputIterator1, class InputIterator2>
  pair<InputIterator1, InputIterator2>
    mismatch (InputIterator1 first1, InputIterator1 last1,
              InputIterator2 first2);
predicate(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迭代器,指向每个范围中不匹配的第一个元素。

这个函数模板的行为相当于:
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], 它包含first1和last1之间的所有元素,包括first1指向的元素,但不包括last1指向的元素。
first2
指向第二个序列的初始位置的输入迭代器。函数最多可以访问[first1,last1]范围内的元素。
pred
接受两个元素(每个序列一个元素,顺序相同)作为参数并返回可转换为bool的值的二元函数。 返回值指示元素在此函数当前环境中是否被认为匹配。
函数不能修改它的任何参数。
它可以是函数指针,也可以是函数对象。

☉  返回值



一个pair,它的成员first和second指向两个序列中不比较的第一个元素,它们有相同相对位置。
如果两个序列中比较的元素都匹配,则函数返回一个pair,first被设置为last1, second被设置为第二个序列中相同相对位置的元素。
如果没有匹配,则返回make_pair(first1,first2)。

☣  示例



// 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;
}

输出:
the first pair of repeated elements are: 30
the second pair of repeated elements are: 10

✥ 复杂度



在first1 和last1之间的distance达到线性:比较元素,直到找到不匹配。

⇄ 数据竞争


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

☂ 异常安全性



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

🍄  另请参阅



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

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