💡 퀵 접속: cpp.kr/set_union
C++ 표준 라이브러리의 알고리즘으로, 두 정렬된 범위의 합집합을 계산합니다. set_union은 원본 범위를 수정하지 않고, 두 범위의 모든 요소들을 다른 범위에 복사합니다. 중복된 요소는 한 번만 포함됩니다. 결과는 정렬된 상태로 저장됩니다.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> set1 = {1, 2, 3, 4, 5};
std::vector<int> set2 = {3, 4, 5, 6, 7};
std::vector<int> result;
std::cout << "첫 번째 집합: ";
for (int n : set1) std::cout << n << " ";
std::cout << std::endl;
std::cout << "두 번째 집합: ";
for (int n : set2) std::cout << n << " ";
std::cout << std::endl;
// 합집합 계산
std::set_union(set1.begin(), set1.end(),
set2.begin(), set2.end(),
std::back_inserter(result));
std::cout << "합집합: ";
for (int n : result) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
실행 결과:
첫 번째 집합: 1 2 3 4 5 두 번째 집합: 3 4 5 6 7 합집합: 1 2 3 4 5 6 7
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string str1 = "abcdef";
std::string str2 = "cdefgh";
std::string result;
std::cout << "첫 번째 문자열: " << str1 << std::endl;
std::cout << "두 번째 문자열: " << str2 << std::endl;
// 합집합 계산
std::set_union(str1.begin(), str1.end(),
str2.begin(), str2.end(),
std::back_inserter(result));
std::cout << "합집합: " << result << std::endl;
return 0;
}
실행 결과:
첫 번째 문자열: abcdef 두 번째 문자열: cdefgh 합집합: abcdefgh
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
class Person {
std::string name;
int age;
public:
Person(const std::string& n, int a) : name(n), age(a) {}
bool operator<(const Person& other) const {
return name < other.name;
}
void print() const {
std::cout << name << " (" << age << "세)" << std::endl;
}
};
int main() {
std::vector<Person> set1 = {
Person("Alice", 20),
Person("Bob", 30),
Person("Charlie", 25),
Person("David", 35)
};
std::vector<Person> set2 = {
Person("Bob", 30),
Person("Charlie", 25),
Person("Eve", 22),
Person("Frank", 40)
};
std::vector<Person> result;
std::cout << "첫 번째 집합:" << std::endl;
for (const auto& person : set1) {
person.print();
}
std::cout << "\n두 번째 집합:" << std::endl;
for (const auto& person : set2) {
person.print();
}
// 합집합 계산
std::set_union(set1.begin(), set1.end(),
set2.begin(), set2.end(),
std::back_inserter(result));
std::cout << "\n합집합:" << std::endl;
for (const auto& person : result) {
person.print();
}
return 0;
}
실행 결과:
첫 번째 집합: Alice (20세) Bob (30세) Charlie (25세) David (35세) 두 번째 집합: Bob (30세) Charlie (25세) Eve (22세) Frank (40세) 합집합: Alice (20세) Bob (30세) Charlie (25세) David (35세) Eve (22세) Frank (40세)
| 함수 | 설명 |
|---|---|
| set_union(first1, last1, first2, last2, result) | 정렬된 범위 [first1, last1)와 [first2, last2)의 합집합을 result부터 시작하는 범위에 복사 |