program story

여러 세트 요소를 단일 세트로 병합

inputbox 2021. 1. 5. 08:03
반응형

여러 세트 요소를 단일 세트로 병합


여러 세트의 내용을 단일 세트로 쉽게 병합 할 수있는 std 라이브러리 또는 부스트 도구가 있는지 알고 싶습니다.

제 경우에는 병합하고 싶은 정수 세트가 있습니다.


다음과 같이 할 수 있습니다.

std::set<int> s1;
std::set<int> s2;
// fill your sets
s1.insert(s2.begin(), s2.end());

을 요청하신 것 같습니다 std::set_union.

예:

#include <set>
#include <algorithm>

std::set<int> s1; 
std::set<int> s2; 
std::set<int> s3;

// Fill s1 and s2 

std::set_union(std::begin(s1), std::end(s1),
               std::begin(s2), std::end(s2),                  
               std::inserter(s3, std::begin(s3)));

// s3 now contains the union of s1 and s2

std :: merge가 당신을 위해 무엇을 할 수 있는지보세요

cplusplus.com/reference/algorithm/merge


C ++ 17에서는의 merge기능을 set직접 사용할 수 있습니다.

병합의 일부로 set2 요소를 추출하여 set1에 삽입하려는 경우 더 좋습니다.

아래와 같이 :

set<int> set1{ 1, 2, 3 };
set<int> set2{ 1, 4, 5 };

// set1 has     1 2 3       set2 has     1 4 5
set1.merge(set2);
// set1 now has 1 2 3 4 5   set2 now has 1   (duplicates are left in the source, set2)

참조 URL : https://stackoverflow.com/questions/7089494/merge-multiple-sets-elements-in-a-single-set

반응형