简体   繁体   中英

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}

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?

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 (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). The inclusion test is then done with very fast logical operation (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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