检查一个数组中的元素是否在另一个数组中

Check if elements in an array are inside of another array

本文关键字:数组 元素 是否 另一个 一个 检查      更新时间:2023-10-16

那么如果我有这两个数组

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

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

如何检查array1中的1, 2 and 3是否在array2中?'

std::includes:

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

这要求数组是排序的,你的数组是排序的。此外,如果它们是用一些自定义比较器排序的,您也必须将其传递给std::includes

值得指出的是,我使用数组的方式是"错误的";该算法期望它的第一个范围是较大的

您可以使用std::set_intersection。但是,它要求使用相同的比较器对数组进行排序。

示例来自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 << ' ';

现场演示