Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Tìm phần bù tương đối của hai mảng đã sắp xếp trong C++

Cho hai mảng đã sắp xếp arr1 (size m), arr2 (size n). Tìm các phần tử có trong arr1 nhưng không trong arr2 (hiệu tập hợp). Ví dụ: A=[3,6,10,12,15], B=[1,3,5,10,16] → [6,12,15].

Dùng set_difference() từ <algorithm> (yêu cầu mảng đã sắp xếp).

Ví dụ

#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);
    sort(first, first + 5);
    sort(second, second + 5);
    cout << "First array: ";
    for (int i = 0; i < n; i++) cout << " " << first[i];
    cout << "\nSecond array: ";
    for (int i = 0; i < n; i++) cout << " " << second[i];
    auto ls = set_difference(first, first + 5, second, second + 5, temp.begin());
    cout << "\nThe result of relative complement: ";
    for (auto it = temp.begin(); it < ls; ++it)
        cout << " " << *it;
}

Kết quả

First array: 3 6 10 12 15
Second array: 1 3 5 10 16
The result of relative complement: 6 12 15