标准库里的mismatch()函数

使用一个东西,不明白它的道理,不高明
——侯捷老师

mismatch()函数
返回两个序列第一组不相同的迭代器组成的pair结构

一、函数声明

// default (1)
template 
  pair
    mismatch (InputIterator1 first1, InputIterator1 last1,
              InputIterator2 first2);
// predicate (2)    
template 
  pair
    mismatch (InputIterator1 first1, InputIterator1 last1,
              InputIterator2 first2, BinaryPredicate pred);

二、等价实现

template
  pair
    mismatch(InputIterator1 first1, InputIterator1 last1, 
             InputIterator2 first2) {
  while ((first! != last1) && (*first1 == *first2)) { // or pred(*fist1, *first2), for version 2
    ++first1;
    ++first2;
  }
  return std::make_pair(first1, first2);
}

三、示例程式

bool mypredicate (int i, int j) {
        return (i == j);
    }
    void test_mismatch() {
        std::vector 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::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';
    }

输出结果:


image.png

四、参考链接

http://www.cplusplus.com/reference/algorithm/mismatch/

你可能感兴趣的:(标准库里的mismatch()函数)