O (n) :
#include <vector>
#include <algorithm>
#include <iostream>
#include <boost/function_output_iterator.hpp>
template <typename T>
T xorfunc(const T& a, const T& b) {
return a^b;
}
template <typename T>
bool compare(const std::vector<T>& v1, const std::vector<T>& v2) {
if (v1.size() != v2.size())
return false;
T result = 0;
std::transform(v1.begin(), v1.end(), v2.begin(), boost::make_function_output_iterator([&result](const T& r) { result ^= r; }), std::ptr_fun(&xorfunc<T>));
return !result;
}
, a ^ b ^ c ^ d == 0 . , , O (n) /. , , . , :
int main() {
std::vector<int> v1, v2, v3, v4, v5, v6, v7, v8;
v1.push_back(1);
v1.push_back(3);
v1.push_back(5);
v2.push_back(2);
v2.push_back(3);
v2.push_back(8);
std::cout << compare(v1, v2) << " (false)" << std::endl;
v3.push_back(3);
v3.push_back(1);
v3.push_back(7);
v4.push_back(7);
v4.push_back(3);
v4.push_back(1);
std::cout << compare(v3, v4) << " (true)" << std::endl;
v5.push_back(3);
v5.push_back(1);
v5.push_back(7);
v6.push_back(7);
v6.push_back(3);
v6.push_back(1);
v6.push_back(18);
v6.push_back(51);
std::cout << compare(v5, v6) << " false" << std::endl;
std::cout << compare(v7, v8) << " true" << std::endl;
}
:
0 (false)
1 (true)
0 false
1 true