c++ 中的 set 如何进行集合运算

在 C++ 中,std::set 是一个关联容器,它包含一组唯一的对象。你可以使用 std::set 进行集合运算,例如并集、交集和差集。以下是如何使用 std::set 进行这些操作的示例:#include #include int main() {// 创建两个集合std::set set1 = {1, 2, 3, 4, 5};std::set<in

C++ 中,std::set 是一个关联容器,它包含一组唯一的对象。你可以使用 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; // 复制 set1 到 union_set
    union_set.insert(set2.begin(), set2.end()); // 插入 set2 的元素
    std::cout << "Union: ";
    for (int num : union_set) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    // 交集
    std::set<int> intersection_set = set1; // 复制 set1 到 intersection_set
    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; // 复制 set1 到 difference_set
    difference_set.difference(set2); // 计算差集
    std::cout << "Difference: ";
    for (int num : 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

注意,std::set 会自动去除重复元素,所以并集和交集的结果中不会有重复的元素。而差集的结果中可能包含重复的元素,但在这个例子中,由于我们使用的是 std::set,重复元素会被自动去除。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/1201409.html

(0)
派派
上一篇 2024-11-29
下一篇 2024-11-29

发表回复

登录后才能评论