set_merge

set_merge (std::set::merge — 병합)

std::set이나 std::multiset의 원소들을 현재 셋으로 이식(splice)하는 멤버 함수예요. 원소는 복사되지 않고 노드가 통째로 이동해요. 충돌하는 키는 소스에 남아요.

출처: cppreference

본문

시그니처는 다음과 같아요 (모두 since C++17).

template< class C2 >
void merge( std::set<Key, C2, Allocator>& source );      // (1)
template< class C2 >
void merge( std::set<Key, C2, Allocator>&& source );     // (2)
template< class C2 >
void merge( std::multiset<Key, C2, Allocator>& source ); // (3)
template< class C2 >
void merge( std::multiset<Key, C2, Allocator>&& source );// (4)

source의 각 원소를 추출("splice")해 *this의 비교자로 삽입하려고 시도해요. *this에 이미 같은 키가 있으면 그 원소는 source에 남아요. 원소는 복사·이동되지 않고 컨테이너 노드의 내부 포인터만 다시 연결돼요. 이동된 원소를 가리키던 모든 포인터와 참조는 유효하지만 이제 source가 아니라 *this를 가리켜요.

get_allocator() != source.get_allocator()면 동작이 정의되지 않아요.

매개변수

  • source: 원소를 이식할 호환되는 소스 컨테이너.

복잡도

N·log(size() + N). 여기서 Nsource.size()예요.

예제

#include <iostream>
#include <set>
int main()
{
    std::set<int> a{1, 2};
    std::set<int> b{2, 3};
    a.merge(b);   // 2는 이미 있어 b에 남음
    for (int x : a) std::cout << x << ' ';   // 1 2
    std::cout << " / b: ";
    for (int x : b) std::cout << x << ' ';   // 2
}

더 알아보기 (Learn more)

cppreference