answer by 42 对两个向量的排序过程的运行时间为 O(n*log(n))(其中n 是较大向量的大小)。如果这是一个问题,您还可以创建一个unordered_set 并用一个向量的元素填充它,然后使用copy_if 仅保留另一个向量中也包含在set 中的元素,结果在 O(n) 的运行时间内。
struct pairhash {
template <typename T, typename U>
std::size_t operator()(const std::pair<T, U>& p) const {
return std::hash<T>()(p.first) ^ std::hash<U>()(p.second);
}
};
struct pairequal {
template <typename T, typename U>
bool operator()(const std::pair<T, U>& p0, const std::pair<T, U>& p1) const {
return (p0.first == p1.first) && (p0.second == p1.second);
}
};
void findEqualPairs() {
std::vector<std::pair<int, int>> vec1{ { 1, 2 }, { 1, 9 }, { 2, 13 }, { 3, 5 } };
std::vector<std::pair<int, int>> vec2{ { 8, 7 }, { 4, 2 }, { 2, 10 }, { 1, 9 } };
std::unordered_set<std::pair<int, int>, pairhash, pairequal> set2(
vec2.begin(), vec2.end());
std::vector<std::pair<int, int>> intersection;
std::copy_if(vec1.begin(), vec1.end(),
std::back_inserter(intersection),
[&](const std::pair<int, int>& p) {
return set2.find(p) != set2.end(); });
std::cout << "intersection:" << std::endl;
for (auto it : intersection) {
std::cout << it.first << ", " << it.second << std::endl;
}
}
(pairhash 取自 this answer)