This tutorial will discuss about a unique way to check if an array is a subset of another array in C++.
Suppose we have two arrays,
int arr1[] = {72, 51, 12, 63, 54, 56, 78, 22}; int arr2[] = {63, 54, 56};
Now we want to check if the second array arr2
is a subset of first array arr1
. For this, we are going to use STL algorithm std::includes()
which accepts 2 ranges as arguments.
Basically std::includes()
function will accept 4 arguments i.e.
- Iterator pointing to the start of first array
arr1
. - Iterator pointing to the end of first array
arr1
. - Iterator pointing to the start of second array
arr2
. - Iterator pointing to the end of second array
arr2
.
It returns true if all the elements of the secondary exist in the first range.
Frequently Asked:
But the important point, is that it expects both the arrays to be sorted. Therefore first we will use the std::sort()
function to sort all the elements of both the arrays i.e. arr1
and arr2
. Then we will use the std::includes()
function to check if all the elements of second array exist in the first array or not.
Let’s see the complete example,
#include <iostream> #include <vector> #include <algorithm> int main() { int arr1[] = {72, 51, 12, 63, 54, 56, 78, 22}; int arr2[] = {63, 54, 56}; // Sort the numbers in array arr1 std::sort(std::begin(arr1), std::end(arr1)); // Sort the numbers in array arr2 std::sort(std::begin(arr2), std::end(arr2)); // Check if array arr2 includes all the elements // of array arr1 bool result = std::includes( std::begin(arr1), std::end(arr1), std::begin(arr2), std::end(arr2)); if(result) { std::cout << "Yes, Array arr2 is a subset of Array arr1" << std::endl; } else { std::cout << "No, Array arr2 is not a subset of Array arr1" << std::endl; } return 0; }
Output :
Yes, Array arr2 is a subset of Array arr1
Summary
Today we learned about a way to check if an array is a subset of another array in C++. Thanks.