I am trying to find a simple way to check whether a vector is a subset of another without sorting the order of elements in the vector. Both the vectors contain random number elements in them.
std::includes
seems to work only for sorted ranges. How can I accomplish this?
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.
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.
Getting a subvector from a vector in C++ Begin Declare s as vector s(vector const &v, int m, int n) to initialize start and end position of vector to constructor. auto first = v. begin() + m. auto last = v.
Copy the vectors. Sort the copies. Then use std::includes
on the copies.
template <typename T>
bool IsSubset(std::vector<T> A, std::vector<T> B)
{
std::sort(A.begin(), A.end());
std::sort(B.begin(), B.end());
return std::includes(A.begin(), A.end(), B.begin(), B.end());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With