Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a vector is a subset of another in c++

Tags:

c++

vector

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?

like image 852
Praveen Avatar asked Aug 02 '11 01:08

Praveen


People also ask

How do you check if a vector is a 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.

How do you check if a set is a subset of another set in CPP?

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 find the subset of a vector in C++?

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.


1 Answers

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());
}
like image 104
Benjamin Lindley Avatar answered Oct 01 '22 16:10

Benjamin Lindley