你可以把它们变成哈希表并计算出来.一旦你再次找到它们,就碰撞反击.如果特定项目的计数器与向量的数量相同,那么你就得到了一个交集.无需预先对对矢量进行排序,定义弱或字符串排序等.
沿线:
#include
#include
#include
#include
using Qpair = uint32_t; // should be std::pair or similar
using Qpairs = std::vector;
int intersections(const std::list& allpairs) {
std::unordered_map m; // element vs counter
auto count = allpairs.size(); // number of vectors to scan
for(const auto& pairs: allpairs) { // loop over all vectors
for (const auto& p : pairs) { // loop over elements in particular vector
m[p] += 1; // and count them
}
}
int total_count = 0; // how many common elements are here
for (const auto& e : m) {
if (e.second == count) {
++total_count;
// you could add e.first to output vector as well
}
}
return total_count;
}
int main() {
Qpairs v1{ 4, 2, 6, 8, 9 };
Qpairs v2{ 1, 3, 8, 9, 4 };
Qpairs v3{ 2, 8, 9, 5, 0 };
std::list l{ v1, v2, v3 };
auto q = intersections(l);
std::cout << q << '\n';
return 0;
}