C++ set 交, 并, 差集用法

有时做数据过滤时, 需要使用到集合的交,并,差集. 下面用一个例子记录一下用法:

#include <algorithm>
#include <iostream>
#include <set>
#include <vector>

using namespace std;

int main(void) {
    set<int> a{1, 2, 3};
    set<int> b{2, 3, 4};
    set<int> c;

    // 交集: 2, 3
    set_intersection(a.begin(), a.end(), b.begin(), b.end(),
                     inserter(c, c.begin()));
    c.clear();

    // 并集: 1, 2, 3, 4
    set_union(a.begin(), a.end(), b.begin(), b.end(), inserter(c, c.begin()));
    c.clear();

    // 差集: 1
    set_difference(a.begin(), a.end(), b.begin(), b.end(),
                   inserter(c, c.begin()));
    c.clear();

    // 差集: 4
    set_difference(b.begin(), b.end(), a.begin(), a.end(),
                   inserter(c, c.begin()));

    auto it = c.find(5);
    if (it == c.end()) {
        cout << "c don't have element 5 " << endl;
    }

    int n = c.erase(4);
    cout << n << endl;
}

如果觉得有帮助, 可以扫描右边的微信打赏码支持一下.

Leave a Reply

Your email address will not be published. Required fields are marked *