Symmetric Difference (ความต่างแบบสมมาตร) ของเซตสองเซต ประกอบด้วยองค์ประกอบที่อยู่ในเซตใดเซตหนึ่ง แต่อยู่ในทั้งสองเซตไม่ได้ (คือ XOR ของเซต)
การดำเนินการเซตทั่วไป
- Set Union
- Set Intersection
- Symmetric Set Difference (Exclusive-OR)
- Set Difference
อัลกอริธึม
- ประกาศเวกเตอร์
vและ iteratorst - เรียงลำดับเซตทั้งสอง
- เรียก
set_symmetric_difference(set1, set1+n, set2, set2+n, v.begin()) - ปรับขนาดเวกเตอร์และแสดงผล
โค้ดตัวอย่าง
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
int set1[] = {5, 6, 7, 8, 9, 10};
int set2[] = {1, 2, 3, 4, 6, 7};
vector<int> v(10);
vector<int>::iterator st;
sort(set1, set1 + 6);
sort(set2, set2 + 6);
st = set_symmetric_difference(set1, set1 + 6, set2, set2 + 6, v.begin());
v.resize(st - v.begin());
cout << "The symmetric difference between the sets has " << v.size() << " elements: " << endl;
for (st = v.begin(); st != v.end(); ++st)
cout << *st << " ";
cout << endl;
return 0;
}
ผลลัพธ์
The symmetric difference between the sets has 8 elements: 1 2 3 4 5 8 9 10
คำอธิบาย: ตัวเลข 6 และ 7 อยู่ในทั้งสองเซต จึงไม่ปรากฏใน symmetric difference ตัวเลข 1-5 และ 8-10 อยู่ในเซตใดเซตหนึ่งอย่างเดียว จึงอยู่ในผลลัพธ์