在C ++中找到两个排序数组的相对补码
假设我们有两个排序的数组arr1和arr2,大小分别为m和n。我们必须找到两个数组的相对补数。这意味着我们需要找到存在于arr1中但不存在于arr2中的所有那些元素。因此,如果数组类似于A=[3,6,10,12,15],而B=[1,3,5,10,16],则结果将为[6,12,15]
为了解决这个问题,我们可以使用set_difference函数。由于问题基本上是设置差异运算。
示例
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main() {
int first[] = {3, 6, 10, 12, 15};
int second[] = {1, 3, 5, 10, 16};
int n = sizeof(first) / sizeof(first[0]);
vector<int> temp(5);
vector<int>::iterator it, ls;
sort(first, first + 5);
sort(second, second + 5);
cout << "First array :";
for (int i = 0; i < n; i++)
cout << " " << first[i];
cout << endl;
cout << "Second array :";
for (int i = 0; i < n; i++)
cout << " " << second[i];
cout << endl;
ls = set_difference(first, first + 5, second, second + 5, temp.begin());
cout << "The result of relative complement ";
for (it = temp.begin(); it < ls; ++it)
cout << " " << *it;
cout << endl;
}输出结果
First array : 3 6 10 12 15 Second array : 1 3 5 10 16 The result of relative complement 6 12 15
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志