温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++ set实现集合的交集、并集

发布时间:2024-08-15 10:37:28 来源:亿速云 阅读:117 作者:小樊 栏目:编程语言
#include <iostream>
#include <set>

using namespace std;

set<int> intersection(set<int> set1, set<int> set2) {
    set<int> result;
    for (int num : set1) {
        if (set2.count(num) > 0) {
            result.insert(num);
        }
    }
    return result;
}

set<int> unionSet(set<int> set1, set<int> set2) {
    set<int> result = set1;
    result.insert(set2.begin(), set2.end());
    return result;
}

int main() {
    set<int> set1 = {1, 2, 3, 4, 5};
    set<int> set2 = {3, 4, 5, 6, 7};

    set<int> intersect = intersection(set1, set2);
    set<int> unite = unionSet(set1, set2);

    cout << "Intersection:";
    for (int num : intersect) {
        cout << " " << num;
    }
    cout << endl;

    cout << "Union:";
    for (int num : unite) {
        cout << " " << num;
    }
    cout << endl;

    return 0;
}

这段代码演示了如何使用C++的set容器来实现集合的交集和并集操作。通过intersection函数可以计算两个set的交集,通过unionSet函数可以计算两个set的并集。在main函数中,我们定义了两个set,然后计算它们的交集和并集,并输出结果。输出结果将会是:

Intersection: 3 4 5
Union: 1 2 3 4 5 6 7
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI