Set Union (ยูเนียนของเซต) ถูกสร้างขึ้นจากองค์ประกอบที่มีอยู่ในเซตใดเซตหนึ่ง หรือในทั้งสองเซต องค์ประกอบจากเซตที่สองที่มีค่าเท่ากับในเซตแรกจะไม่ถูกคัดลอกซ้ำในผลลัพธ์
การดำเนินการเซตทั่วไป
- Set Union (ยูเนียน)
- Set Intersection (อินเตอร์เซกชัน)
- Symmetric Set Difference (ความต่างแบบสมมาตร/XOR)
- Set Difference (ความต่าง/ลบเซต)
อัลกอริธึม
- ประกาศเวกเตอร์
vและ iteratorst - เรียงลำดับเซตทั้งสองก่อน (เงื่อนไขของ
set_union) - เรียก
set_union(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;
// ต้องเรียงลำดับก่อนใช้ set_union
sort(set1, set1 + 6);
sort(set2, set2 + 6);
st = set_union(set1, set1 + 6, set2, set2 + 6, v.begin());
v.resize(st - v.begin());
cout << "The union between the sets has " << v.size() << " elements: " << endl;
for (st = v.begin(); st != v.end(); ++st)
cout << *st << " ";
cout << endl;
return 0;
}
ผลลัพธ์
The union between the sets has 10 elements: 1 2 3 4 5 6 7 8 9 10
สรุป: std::set_union ต้องการช่วงข้อมูลที่เรียงลำดับแล้ว ผลลัพธ์จะไม่มีค่าซ้ำ และเรียงลำดับจากน้อยไปมาก