mismatchは、2つの要素を比較して違いがあれば、
その最初の位置を調べる関数です。
template<class InputIterator1, class InputIterator2>
pair<InputIterator1, InputIterator2> mismatch(
InputIterator1 _First1,
InputIterator1 _Last1,
InputIterator2 _First2
);
template<class InputIterator1, class InputIterator2, class BinaryPredicate>
pair<InputIterator1, InputIterator2> mismatch(
InputIterator1 _First1,
InputIterator1 _Last1,
InputIterator2 _First2
BinaryPredicate _Comp
);
2つのバージョンがありますが、今回は最初のやつを使ってみます。結果はpairとして返されます。
簡単な例を見てみます。
// mismatch01.cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector <int> v1, v2;
pair<vector<int>::iterator, vector<int>::iterator> v;
v1.push_back(2);
v1.push_back(4);
v1.push_back(6);
v1.push_back(9);
v2.push_back(2);
v2.push_back(5);
v2.push_back(6);
v2.push_back(11);
v = mismatch(v1.begin(), v1.end(), v2.begin());
if (v.first == v1.end()) {
cout << "v1, v1に違いはありません" << endl;
} else {
cout << *(v.first) << "," << *(v.second) << endl;
}
return 0;
}
v1とv2の最初の違いは、2番目の要素の4と5です。これが、vに格納されたわけです。2つの要素に違いがない場合、v.firstにv1.end()が格納されます。
比較するものは、必ずしも同じクラスのオブジェクトでなくてもよいです。
// mismatch02.cpp
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
using namespace std;
int main()
{
vector<int> v1;
list<int> l1;
pair<vector<int>::iterator, list<int>::iterator> x;
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
v1.push_back(4);
l1.push_back(1);
l1.push_back(2);
l1.push_back(3);
l1.push_back(4);
x = mismatch(v1.begin(), v1.end(), l1.begin());
if (x.first == v1.end()) {
cout << "v1, l1に違いはありません" << endl;
} else {
cout << *(x.first) << "," << *(x.second) << endl;
}
return 0;
}
今回も簡単でした。第2のバージョンのmismatch関数も使ってみてください。
Update Aug/06/2005 By Y.Kumei