使用一个东西,不明白它的道理,不高明
——侯捷老师
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';
}
输出结果: