c++

C++ set函数如何进行集合运算

小樊
84
2024-11-30 18:57:51
栏目: 编程语言

在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中的元素是自动排序的,所以在输出结果中,元素会按照升序排列。

0
看了该问题的人还看了