1

So If I have these two arrays:

int array1[] = {1, 2 ,3};

int array2[] = {1, 2, 3, 4, 5};

How do I check if 1, 2 and 3 from array1 are in array2? `

Thanks in advance.

3
  • 3
    You do know that Python code is actually wrong? Commented Oct 15, 2016 at 22:40
  • @UnholySheep Probably is. Haven't touched python in so long. Commented Oct 15, 2016 at 22:44
  • 1
    In that case you should probably remove that statement about Python completely, as it is misleading (and in fact straight up wrong - Python does not have built-in syntax to check if one list is part of another). Commented Oct 15, 2016 at 23:05

2 Answers 2

6

std::includes:

if (std::includes(std::begin(array2), std::end(array2),
                  std::begin(array1), std::end(array1)) {
    // array2 includes array1
}

This requires the arrays are sorted, which yours are. Also, if they are sorted with some custom comparator, you must pass that to std::includes as well.

It is worth pointing out that I use your arrays the "wrong" way round; the algorithm expects its first range to be the larger one.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, looks easy to use.
3

You can use std::set_intersection. It requires the arrays to be sorted using the same comparator, though.

example from cppreference:

std::vector<int> v1{1,2,3,4,5,6,7,8};
std::vector<int> v2{        5,  7,  9,10};
std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());

std::vector<int> v_intersection;

std::set_intersection(v1.begin(), v1.end(),
                      v2.begin(), v2.end(),
                      std::back_inserter(v_intersection));
for(int n : v_intersection)
    std::cout << n << ' ';

live demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.