简体   繁体   English

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

[英]C++ set how to check if a list of sets contains a subset

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}现在我有另一组,可以这样说: {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例如,setlist[0] 和 setlist[1] 都是子集,因此 output 为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.我的想法是遍历整个向量并检查是否有任何索引是使用std::includes function 的子集,但我正在寻找一种更快的方法。 Is this possible?这可能吗?

Consider using a list of set<int> instead.考虑改用set<int>列表。 This allows you to use std::include .这允许您使用std::include Run your loop on the vector after having sorted it by number of elements in the set (ie 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).如果整数的范围不太大,您可以考虑使用std::bitset实现集合(如果包含 n,则位 n 为真)。 The inclusion test is then done with very fast logical operation (eg subset & large_set == subset ).然后通过非常快速的逻辑操作(例如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.您仍然可以按count对向量进行排序,但不确定考虑到逻辑运算的速度是否需要这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM