标准库<algorithm>里的mismatch()函数

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

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

一、函数声明

// default (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);

二、等价实现

template<class InputIterator1, class InputIterator2>
  pair<InputIterator1, InputIterator2>
    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<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';
    }

输出结果:


image.png

四、参考链接

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。