สมมติเรามีอาร์เรย์สองอัน A และ B มีสมาชิกบางส่วน เราต้องหาสมาชิกที่อยู่ในเซต A แต่ไม่อยู่ในเซต B หากเราคิดว่าสถานการณ์นั้น และพิจารณา A และ B เป็นเซต นี่คือการดำเนินการหาความต่างของเซต (set difference) ความต่างของเซตระหว่าง A และ B จะคืนค่าสมาชิกเหล่านั้น
ตัวอย่าง
#include <iostream>
#include <set>
#include <algorithm>
#include <vector>
using namespace std;
void setDiffResults(int A[], int B[], int An, int Bn) {
sort(A, A + An);
sort(B, B + Bn);
vector<int> res(An);
vector<int>::iterator it;
vector<int>::iterator it_res = set_difference(A, A + An, B, B + Bn, res.begin());
cout << "Elements are: ";
for(it = res.begin(); it < it_res; ++it){
cout << *it << " ";
}
}
int main() {
int A[] = {9, 4, 5, 3, 1, 7, 6};
int B[] = {9, 3, 5};
int An = 7, Bn = 3;
setDiffResults(A, B, An, Bn);
}
ผลลัพธ์
Elements are: 1 4 6 7