STL mismatch函数

STL mismatch函数算法

STL 中的 equal() 算法可以告诉我们两个序列是否匹配。mismatch() 算法也可以告诉我们两个序列是否匹配,而且如果不匹配,它还能告诉我们不匹配的位置。

STL mismatch函数详解

头文件

#include <algorithm>

语法

template <class InputIterator1, class InputIterator2> pair<InputIterator1, InputIterator2> mismatch (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2 )

参数

参数 描述
first1 输入迭代器
last1 输入迭代器
first2 输入迭代器

说明

mismatch 算法会拿着 [Frist1,Last1) 中的值和 [first2,last2) 中的元素进行比较,并且返回第一个找到的两个区间中不匹配的值,并且返回。

案例

STL mismatch函数

使用 STL mismatch 函数比较集合

#include <iostream> #include <algorithm> #include <vector> #include <utility> bool mypredicate (int i, int j) { return (i == j); } int main() { std::cout << "嗨客网(www.haicoder.net)\n" << std::endl; std::vector<int> myvector; for (int i = 1; i < 6; i++) { myvector.push_back(i*10); } int myints[] = {10, 20, 80, 320, 1024}; std::pair<std::vector<int>::iterator,int*> mypair; 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; mypair = std::mismatch (mypair.first, myvector.end(), mypair.second, mypredicate); std::cout << "Second mismatching elements: " << *mypair.first; std::cout << " and " << *mypair.second << '\n'; }

我们在 Linux 下使用 g++ 进行编译,具体命令如下:

g++ mismatch.cpp -std=c++11

编译后,我们直接运行生成的二进制文件 a.out,如下图所示:

33_STL mismatch函数.png

我们使用了 mismatch 函数,对集合进行了对比。

STL mismatch函数总结

STL 中的 equal() 算法可以告诉我们两个序列是否匹配。mismatch() 算法也可以告诉我们两个序列是否匹配,而且如果不匹配,它还能告诉我们不匹配的位置。