C++设置如何检查集合列表是否包含子集

发布于 2025-01-17 06:23:40 字数 414 浏览 2 评论 0原文

我有一个集合列表,现在列表是一个向量,但它不需要是。

vector<unordered_set<int>> setlist;

然后我用一些数据填充它,例如它看起来像这样:

[ {1, 2}, {2, 3}, {5, 9} ]

现在我有另一组,让我们说它是这样的: {1, 2, 3}

我想检查是否有列表中的这些集合是上述集合的子集。例如,setlist[0] 和 setlist[1] 都是子集,因此输出将为 true

我的想法是循环遍历整个向量并使用以下命令检查是否有任何索引是子集std::includes 函数,但我正在寻找一种更快的方法。这可能吗?

I have a list of sets, right now the list a vector but it does not need to be.

vector<unordered_set<int>> setlist;

then i am filling it with some data, lets just say for example it looks like this:

[ {1, 2}, {2, 3}, {5, 9} ]

Now i have another set, lets say its this: {1, 2, 3}

I want to check if any of these sets in the list is a subset of the above set. For example, setlist[0] and setlist[1] are both subsets, so the output would be true

My idea is to loop through the whole vector and check if any of the indexes are a subset using the std::includes function, but I am looking for a faster way. Is this possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北音执念 2025-01-24 06:23:40

考虑使用 set 列表代替。这允许您使用 std::include 。按集合中的元素数量(即从元素数量最少的集合到项目数量最多的集合)对向量进行排序后,对向量运行循环。内循环将从当前索引开始。这可以避免您检查较小集合中是否包含较大集合。

如果整数范围不太大,您可以考虑使用 < 来实现该集合code>std::bitset(如果包含 n,则位 n 为 true)。然后用非常快的逻辑运算完成包含测试(例如subset & large_set == subset)。您仍然可以按 count 对向量进行排序,但考虑到逻辑运算的速度,不确定是否需要这样做。

Consider using a list of set<int> instead. This allows you to use std::include. Run your loop on the vector after having sorted it by number of elements in the set (i.e. from the sets with the smallest number of elements, to the sets with the largest number of items). The inner loop will start at the current index. This avoids that you check inclusion of the larger sets in the smaller ones.

If the range of the integers is not too large, you could consider implementing the set with a std::bitset (bit n is true if n is included). The inclusion test is then done with very fast logical operation (e.g. subset & large_set == subset). You could still sort the vector by count, but not sure that this would be needed considering the speed of the logical operation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文