whenever possible one should use the standard library tools provided. std::mismatch() returns a pair of iterators to the first mismatch. examples of this are abundant on the WWW but i wanted to find all the mismatches and could not find an example online, hence this post. i don’t think the code is elegant so please let me know better versions of my code.
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<unsigned> a = {1,2,3,4,5,6};
std::vector<unsigned> b = {1,2,33,4,55,66};
// find the first mismatch
auto p = std::mismatch(a.begin(), a.end(), b.begin());
while(p.first != a.end())
{
std::cout << *p.first << std::endl;
std::cout << *p.second << std::endl;
p = std::mismatch(++p.first, a.end(), ++p.second);
}
return 0;
}
havent’ tried the above on list container but i believe list iterators support the increment operator.
don’t forget to compile the above using -std=c++0x
Advertisement