c++ set_intersection(), set_union() ,set_difference 交集 并集 差集

1、关于集合

#include <iostream>     // std::cout
#include <algorithm>    // std::set_intersection, std::sort
#include<set>
#include<string>
#include <iterator> 

using namespace std;

template<typename T>
void prints(set <T> &s)
{
    for (auto i : s)
        cout << i << " ";
    cout << endl;
}


int main() {
    set<string> words1{ "one", "two", "three", "four", "five", "six" };
    set<string> words2{ "four","five", "six", "seven", "eight", "nine" };
    set<string> result;

    set_intersection(words1.begin(), words1.end(), words2.begin(), words2.end(), inserter(result, result.begin()));
    prints(result);
    result.clear();
    set_union(words1.begin(), words1.end(), words2.begin(), words2.end(), inserter(result, result.begin()));
    prints(result);
    result.clear();
    set_difference(words1.begin(), words1.end(), words2.begin(), words2.end(), inserter(result, result.begin()));
    prints(result);
    result.clear();

    set<int> s1 = { 1,2,3,4,5 };
    set<int> s2 = { 8,7,3,21,2,1 };
    set<int> rs;
    set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(rs, rs.begin()));
    prints(rs);
    rs.clear();
    set_union(s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(rs, rs.begin()));
    prints(rs);
    rs.clear();
    set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(rs, rs.begin()));
    prints(rs);
    rs.clear();
    system("pause");
    return 0;
}

 

2、对数组

其实对数组也可以进行类似操作,但是需要数组有序

#include <iostream>     // std::cout
#include <algorithm>    // std::set_intersection, std::sort
#include <vector>       // std::vector
#include<set>
#include<string>
#include <iterator> 

using namespace std;

template<typename T>
void prints(vector <T> &s)
{
    for (auto i : s)
        cout << i << " ";
    cout << endl;
}


int main() {
    vector<int> first = { 5,10,15,20,25,100 };
    vector<int> second = { 50,40,30,20,10 };
    vector<int> v(20);                      // 0  0  0  0  0  0  0  0  0  0
    vector<int>::iterator it;
    sort(first.begin(), first.end());     //  5 10 15 20 25
    sort(second.begin(), second.end());   // 10 20 30 40 50
    it = set_intersection(first.begin(), first.end(), second.begin(), second.end(), v.begin());
    v.resize(it - v.begin());                      // 10 20
    prints(v);

    vector<int> v2;
    set_union(first.begin(), first.end(), second.begin(), second.end(), inserter(v2, v2.begin()));                  // 10 20
    prints(v2);

    int nums1[] = { 1,3,5,7,9 };
    int nums2[] = { 2,4,6,8,0 };
    vector<int> v3(10);
    sort(nums1, nums1+5); 
    sort(nums2, nums2 + 5);
    set_difference(nums1, nums1 + 5, nums2, nums2 + 5, v3.begin());
    prints(v3);

    system("pause");
    return 0;
}

 

posted @ 2020-10-15 15:25  r1-12king  阅读(273)  评论(0编辑  收藏  举报