找公共元素c语言,c – 查找多个向量之间的公共元素(无整数元素)

你可以把它们变成哈希表并计算出来.一旦你再次找到它们,就碰撞反击.如果特定项目的计数器与向量的数量相同,那么你就得到了一个交集.无需预先对对矢量进行排序,定义弱或字符串排序等.

沿线:

#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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值