C ++中的无序集合交集

编程入门 行业动态 更新时间:2024-10-26 13:35:02
本文介绍了C ++中的无序集合交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是我的代码,想知道有什么想法可以使它更快?我的实现是蛮力的,对于a中的任何元素,请尝试查找是否也在b中,如果是,则将其放入结果集c中.任何更聪明的想法都将受到赞赏.

Here is my code, wondering any ideas to make it faster? My implementation is brute force, which is for any elements in a, try to find if it also in b, if so, put in result set c. Any smarter ideas is appreciated.

#include <iostream> #include <unordered_set> int main() { std::unordered_set<int> a = {1,2,3,4,5}; std::unordered_set<int> b = {3,4,5,6,7}; std::unordered_set<int> c; for (auto i = a.begin(); i != a.end(); i++) { if (b.find(*i) != b.end()) c.insert(*i); } for (int v : c) { std::printf("%d \n", v); } }

推荐答案

渐近而言,您的算法已尽其所能.

Asymptotically, your algorithm is as good as it can get.

在实践中,我将添加一个检查以循环访问两组中较小的一组,并在较大的一组中进行查找.假设哈希值合理地均匀分布,则在 std :: unoredered_set 中进行查找需要花费固定的时间.这样,您将减少执行此类查找的次数.

In practice, I'd add a check to loop over the smaller of the two sets and do lookups in the larger one. Assuming reasonably evenly distributed hashes, a lookup in a std::unoredered_set takes constant time. So this way, you'll be performing fewer such lookups.

更多推荐

C ++中的无序集合交集

本文发布于:2023-11-29 18:33:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647253.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!