STL mismatch演算法
阿新 • • 發佈:2021-02-02
技術標籤:C++
一、介紹
mismatch演算法:
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); }
mismatch演算法會拿著 [frist1,last1) 中的值和[first2,last2)中的元素進行比較,並且返回第一個找到的兩個區間中不相等的值,並且返回指向這兩個不相等元素的 std::pair。
二、用法
例項1:尋找兩個陣列中,第一個相等的元素和第一個不相等的元素
// not2 example #include <iostream> // std::cout #include <functional> // std::not2, std::equal_to #include <algorithm> // std::mismatch #include <utility> // std::pair int main () { int foo[] = {10,20,30,40,50}; int bar[] = {0,15,30,45,60}; std::pair<int*,int*> firstmatch; std::pair<int*,int*> firstmismatch; firstmismatch = std::mismatch (foo, foo+5, bar, std::equal_to<int>()); firstmatch = std::mismatch (foo, foo+5, bar, std::not2(std::equal_to<int>())); std::cout << "First mismatch in bar is " << *firstmismatch.second << '\n'; std::cout << "First match in bar is " << *firstmatch.second << '\n'; return 0; }
例項2
#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; }
參考: