STL中set求交集、並集、差集的方法


並集(http://zh.cppreference.com/w/cpp/algorithm/set_union)

交集(http://zh.cppreference.com/w/cpp/algorithm/set_intersection)

差集(http://zh.cppreference.com/w/cpp/algorithm/set_difference)

 

inserter(http://zh.cppreference.com/w/cpp/iterator/inserter)

 

 back_inserter(http://zh.cppreference.com/w/cpp/iterator/back_inserter)

#include <bits/stdc++.h>
using namespace std;
const int maxn = 123;
int n;
int num[maxn];
int main(){
    set<int> a, b;
    vector<int> c;
    a =   {2,  4,   6};
    b = {1,2,3,4,5};
    //傳入的a,b不一定是set, 但一定要有序
    set_union(a.begin(), a.end(), b.begin(), b.end(), back_inserter(c));//並集
    for(int n : c) cout << n << " "; puts("");
    c.clear();



    set_intersection(a.begin(), a.end(), b.begin(), b.end(), back_inserter(c));//交集
    for(int n : c) cout << n << " "; puts("");
    c.clear();

    set_difference(a.begin(), a.end(), b.begin(), b.end(), back_inserter(c)); //差集(b中屬於a的元素去掉)
    for(int n : c) cout << n << " "; puts("");
    c.clear();
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM