Make Unreal REAL.
article thumbnail

 

STL 함수를 쓰지 않고 직접 구현하면 다음과 같다.

 

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

using namespace std;

void print(vector<string>& v);

int main(int argc, char* argv[])
{
    vector<string> setA = {"AA", "AA", "AA", "CC", "DD"};
    vector<string> setB = {"AA", "CC", "CC", "EE"};

    unordered_map<string, int> umapA, umapB;
    set<string> elem;

    for (string& s : setA) ++umapA[s], elem.emplace(s);
    for (string& s : setB) ++umapB[s], elem.emplace(s);

    vector<string> setUnion, setInter, setDifAB, setDifBA;

    for (const string& e : elem)
    {
        vector<string> tUinon = vector<string>(max(umapA[e], umapB[e]), e);
        vector<string> tInter = vector<string>(min(umapA[e], umapB[e]), e);
        vector<string> tDifAB = vector<string>((umapA[e] > umapB[e]) ? (umapA[e] - umapB[e]) : 0, e);
        vector<string> tDifBA = vector<string>((umapB[e] > umapA[e]) ? (umapB[e] - umapA[e]) : 0, e);

        move(tUinon.begin(), tUinon.end(), back_inserter(setUnion));
        move(tInter.begin(), tInter.end(), back_inserter(setInter));
        move(tDifAB.begin(), tDifAB.end(), back_inserter(setDifAB));
        move(tDifBA.begin(), tDifBA.end(), back_inserter(setDifBA));
    }

    cout << "A ∪ B: ";   print(setUnion);
    cout << "A ∩ B: ";   print(setInter);
    cout << "A - B: ";   print(setDifAB);
    cout << "B - A: ";   print(setDifBA);

    return 0;
}

 

출력

A ∪ B: AA AA AA CC CC DD EE
A ∩ B: AA CC
A - B: AA AA DD
B - A: CC EE

 

 

C++ 합집합, 교집합, 차집합 STL

set_(union, inersection, difference) STL내 합집합, 교집합, 차집합 함수를 사용해봅니다.

unluckyjung.github.io

 

STL 함수를 이용해 간단히 구할 수도 있다.

 

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

using namespace std;

void print(vector<string>& v);

int main(int argc, char* argv[])
{
    vector<string> setA = {"AA", "AA", "AA", "CC", "DD"};
    vector<string> setB = {"AA", "CC", "CC", "EE"};
    vector<string> setUnion, setInter, setDifAB, setDifBA;

    set_union(setA.begin(), setA.end(), setB.begin(), setB.end(), back_inserter(setUnion));
    set_intersection(setA.begin(), setA.end(), setB.begin(), setB.end(), back_inserter(setInter));
    set_difference(setA.begin(), setA.end(), setB.begin(), setB.end(), back_inserter(setDifAB));
    set_difference(setB.begin(), setB.end(), setA.begin(), setA.end(), back_inserter(setDifBA));

    cout << "A ∪ B: ";   print(setUnion);
    cout << "A ∩ B: ";   print(setInter);
    cout << "A - B: ";   print(setDifAB);
    cout << "B - A: ";   print(setDifBA);

    return 0;
}

 

출력

A ∪ B: AA AA AA CC CC DD EE
A ∩ B: AA CC
A - B: AA AA DD
B - A: CC EE
profile

Make Unreal REAL.

@diesuki4

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

검색 태그