Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if one vector is a subset of another?

Currently, I think my best option is to use std::set_intersection, and then check if the size of the smaller input is the same as the number of elements filled by set_intersection.

Is there a better solution?

like image 531
deworde Avatar asked Nov 01 '10 10:11

deworde


People also ask

How do you find if a vector is subset of another vector?

So if you have two instances of the number 99 in vector a, then as long as vector b has at least one instance of the number 99, then it will be declared as a subset. Why do you want another method?

How do you check if a vector is a subset of another vector in Matlab?

Function ismember(B, A) will return an array with all elements set to true if, and only if, all elements in B are in A (which means B is a subset of A). Thus, all(ismember(B, A)) = true iff B is a subset of A.

How do you check if a set is a subset of another C++?

The function std::includes() can be used to determine if one set is a subset of another. The function returns true if and only if each distinct element in the second sorted range has a corresponding distinct element in the first sorted range to which it compares equal.

How do you know if a subset is B?

In mathematics, a set A is a subset of a set B if all elements of A are also elements of B; B is then a superset of A. It is possible for A and B to be equal; if they are unequal, then A is a proper subset of B.


1 Answers

Try this:

if (std::includes(set_one.begin(), set_one.end(),
                  set_two.begin(), set_two.end()))
{
// ...
}

About includes().

The includes() algorithm compares two sorted sequences and returns true if every element in the range [start2, finish2) is contained in the range [start1, finish1). It returns false otherwise. includes() assumes that the sequences are sorted using operator<(), or using the predicate comp.

runs in

At most ((finish1 - start1) + (finish2 - start2)) * 2 - 1 comparisons are performed.

Plus O(nlog(n)) for sorting vectors. You won't get it any faster than that.

like image 170
Klark Avatar answered Oct 06 '22 21:10

Klark