Check if Any Element of Array is in Another Array in C++

This tutorial will discuss about a unique way to check if any element of array is in another array in C++.

Suppose we have two arrays,

int arr1[] = {11, 34, 23, 44, 56};
int arr2[] = {46, 77, 18, 92, 23, 67, 99};

Now we want to check if any element of first array is present in the second array. For this we can use the STL Algorithm std::any_of() to check if any element of first array matches a given condition. This condition is a lambda function, which accepts an element as argument, and searches for that element in the second array. If the given element is present in the second array, then it will return true, otherwise it will return false.

// check if eny element of array arr1
// is present in another array arr2
bool result = std::any_of(
                    std::begin(arr1),
                    std::end(arr1),
                    [&](const auto& elem) {
                        return std::find(
                                    std::begin(arr2),
                                    std::end(arr2),
                                    elem) != std::end(arr2);
                    });

If for any element of first array, the lambda function returns true, then the std::any_of() function will return true. It means at least an element of first array is present in the second array.

Let’s see the complete example,

#include <iostream>
#include <algorithm>

int main()
{
    int arr1[] = {11, 34, 23, 44, 56};
    int arr2[] = {46, 77, 18, 92, 23, 67, 99};

    // check if eny element of array arr1
    // is present in another array arr2
    bool result = std::any_of(
                        std::begin(arr1),
                        std::end(arr1),
                        [&](const auto& elem) {
                            return std::find(
                                        std::begin(arr2),
                                        std::end(arr2),
                                        elem) != std::end(arr2);
                        });

    if (result)
    {
        std::cout<<"Yes, at least one element of Array arr1 is present in Another Array arr2.\n";
    }
    else
    {
        std::cout << "No, none of the elements of arr1 is present in arr2.\n";
    }

    return 0;
}

Output :

Yes, at least one element of Array arr1 is present in Another Array arr2.

Summary

Today we learned about several ways to check if any element of array is in another array in C++. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top