是否有一个C函数可以找到多个向量之间的共同元素?向量元素不是整数(在我的例子中,元素是QPair类型). 该函数理想地具有一组向量作为参数(要比较的向量的数量可以变化)并返回向量的
该函数理想地具有一组向量作为参数(要比较的向量的数量可以变化)并返回向量的公共值.我确保每个向量中没有重复,但可能没有共同的元素.
例:
vec 1 [a,b] vec 2 [c,d,a,e,h] vec 3 [i,j,a]
回报的共同价值:
a你可以把它们变成哈希表并计算出来.一旦你再次找到它们,就碰撞反击.如果特定项目的计数器与向量的数量相同,那么你就得到了一个交集.无需预先对对矢量进行排序,定义弱或字符串排序等.
沿线:
#include <iostream>
#include <vector>
#include <list>
#include <unordered_map>
using Qpair = uint32_t; // should be std::pair<int, int> or similar
using Qpairs = std::vector<Qpair>;
int intersections(const std::list<Qpairs>& allpairs) {
std::unordered_map<Qpair, int> 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<Qpairs> l{ v1, v2, v3 };
auto q = intersections(l);
std::cout << q << '\n';
return 0;
}
