溫馨提示×

c++ 中的 set 如何進行集合運算

c++
小樊
110
2024-11-29 11:30:45
欄目: 編程語言

在 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,重復元素會被自動去除。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女