检查一个数组中的元素是否在另一个数组中
Check if elements in an array are inside of another array
那么如果我有这两个数组
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 << ' ';
现场演示
相关文章:
- 数组元素打印的递归方法
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 数组元素更改值?
- 如何访问宏中定义的数组元素
- 将数组元素递增 1
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 在 std::map 中插入数组元素
- 使用指针访问数组元素时出现意外结果
- c++ 使用动态分配运算符反向数组元素
- 为什么在 c++ 中分配 char 数组元素时,分配的字符会被销毁?
- 缺少数组元素问题
- 如何在类中制作 2D 数组元素,然后在其构造函数中指定其维度?
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 删除在结构 c++ 中声明的数组元素
- Getter 和 Setter 用于类 C++ 中的数组元素
- 尝试递归获取数组元素的总和
- 使用SWIG将numpy数组元素(int)传递给c++int