假设我们有两个排序的数组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