💡 퀵 접속: cpp.kr/set

set

C++ 표준 라이브러리의 연관 컨테이너로, 중복되지 않는 요소들을 자동으로 정렬하여 저장하는 컨테이너입니다.

기본 사용법

#include <iostream>
#include <set>

int main() {
    // 셋 생성
    std::set<int> numbers;
    
    // 요소 추가
    numbers.insert(5);
    numbers.insert(2);
    numbers.insert(8);
    numbers.insert(2);  // 중복된 값은 무시됨
    
    // 요소 출력
    std::cout << "셋의 요소들: ";
    for (const auto& num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

실행 결과:

셋의 요소들: 2 5 8

요소 검색과 삭제

#include <iostream>
#include <set>

int main() {
    std::set<int> numbers = {1, 2, 3, 4, 5};
    
    // 요소 검색
    auto it = numbers.find(3);
    if (it != numbers.end()) {
        std::cout << "값 3을 찾았습니다." << std::endl;
    }
    
    // 요소 삭제
    numbers.erase(3);
    
    // 삭제 후 확인
    if (numbers.find(3) == numbers.end()) {
        std::cout << "값 3이 삭제되었습니다." << std::endl;
    }
    
    // 남은 요소 출력
    std::cout << "남은 요소들: ";
    for (const auto& num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

실행 결과:

값 3을 찾았습니다.
값 3이 삭제되었습니다.
남은 요소들: 1 2 4 5

셋 연산

#include <iostream>
#include <set>
#include <algorithm>

int main() {
    std::set<int> set1 = {1, 2, 3, 4, 5};
    std::set<int> set2 = {4, 5, 6, 7, 8};
    
    // 합집합
    std::set<int> union_set;
    std::set_union(set1.begin(), set1.end(),
                  set2.begin(), set2.end(),
                  std::inserter(union_set, union_set.begin()));
    
    // 교집합
    std::set<int> intersection_set;
    std::set_intersection(set1.begin(), set1.end(),
                         set2.begin(), set2.end(),
                         std::inserter(intersection_set, intersection_set.begin()));
    
    // 결과 출력
    std::cout << "합집합: ";
    for (const auto& num : union_set) {
        std::cout << num << " ";
    }
    std::cout << "\n교집합: ";
    for (const auto& num : intersection_set) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

실행 결과:

합집합: 1 2 3 4 5 6 7 8
교집합: 4 5

참고사항

  • set은 std 네임스페이스에 정의되어 있습니다.
  • 요소는 자동으로 정렬됩니다.
  • 중복된 값은 자동으로 제거됩니다.
  • 요소 검색은 O(log n) 시간 복잡도를 가집니다.
  • 요소 삽입과 삭제도 O(log n) 시간 복잡도를 가집니다.
메서드 설명
insert() 요소 추가
erase() 요소 삭제
find() 요소 검색
count() 요소 개수 반환
size() 요소 개수 반환
empty() 셋이 비어있는지 확인
clear() 모든 요소 삭제
begin() 시작 반복자
end() 끝 반복자