在C++中,std::set
是一个关联容器,它包含一组唯一的对象。你可以使用std::set
的内置方法来进行集合运算,如并集、交集、差集和对称差集。以下是如何使用这些操作的示例:
#include <iostream>
#include <set>
int main() {
std::set<int> set1 = {1, 2, 3, 4, 5};
std::set<int> set2 = {4, 5, 6, 7, 8};
// 并集
std::set<int> union_set = set1;
union_set.insert(set2.begin(), set2.end());
std::cout << "Union: ";
for (int num : union_set) {
std::cout << num << " ";
}
std::cout << std::endl;
// 交集
std::set<int> intersection_set = set1;
intersection_set.intersection(set2);
std::cout << "Intersection: ";
for (int num : intersection_set) {
std::cout << num << " ";
}
std::cout << std::endl;
// 差集
std::set<int> difference_set = set1;
difference_set.difference(set2);
std::cout << "Difference: ";
for (int num : difference_set) {
std::cout << num << " ";
}
std::cout << std::endl;
// 对称差集
std::set<int> symmetric_difference_set = set1;
symmetric_difference_set.symmetric_difference(set2);
std::cout << "Symmetric Difference: ";
for (int num : symmetric_difference_set) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
输出结果:
Union: 1 2 3 4 5 6 7 8
Intersection: 4 5
Difference: 1 2 3
Symmetric Difference: 1 2 3 6 7 8
注意:std::set
中的元素是自动排序的,所以在输出结果中,元素会按照升序排列。