Computer >> 컴퓨터 >  >> 프로그래밍 >> C++

C++ STL 집합(Set) 구현 방법: 주요 함수와 예제 코드 총정리

집합(Set)이란?

집합(Set)은 모든 요소가 고유한 값을 가져야 하는 추상 데이터 타입(ADT)입니다. 요소의 값 자체가 식별자 역할을 하기 때문에 중복된 값은 허용되지 않습니다. 또한 한 번 집합에 추가된 요소의 값은 직접 수정할 수 없으며, 값을 바꿔야 할 경우에는 해당 요소를 삭제한 뒤 수정된 값을 다시 삽입해야 합니다.

C++ STL의 std::set은 내부적으로 균형 이진 탐색 트리(레드-블랙 트리) 기반으로 구현되어 있어, 요소가 항상 오름차순으로 정렬된 상태를 유지하며 삽입·삭제·탐색 연산이 O(log n)의 시간 복잡도로 처리됩니다.

주요 함수 및 설명

  • st.size() : 집합에 저장된 요소의 개수를 반환합니다.
  • st.insert() : 집합에 요소를 삽입합니다. 이미 존재하는 값은 자동으로 무시됩니다.
  • st.erase() : 지정한 요소를 집합에서 삭제합니다.
  • st.find() : 찾는 요소가 존재하면 해당 요소를 가리키는 반복자(iterator)를 반환하고, 존재하지 않으면 st.end()를 반환합니다.
  • st.begin() : 집합의 첫 번째 요소를 가리키는 반복자를 반환합니다.
  • st.end() : 집합의 마지막 요소 다음 위치를 가리키는 반복자를 반환합니다.

예제 코드

아래 프로그램은 메뉴 방식으로 동작하며, 집합의 크기 확인, 요소 삽입·삭제, 특정 요소 탐색, 반복자를 이용한 전체 출력 기능을 제공합니다.

#include <iostream>
#include <set>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
    set<int> st;
    set<int>::iterator it;
    int c, i;
    while (1) {
       cout<<"1.Size of the Set"<<endl;
       cout<<"2.Insert Element into the Set"<<endl;
       cout<<"3.Delete Element of the Set"<<endl;
       cout<<"4.Find Element in a Set"<<endl;
       cout<<"5.Display the set: "<<endl;
       cout<<"6.Exit"<<endl;
       cout<<"Enter your Choice: ";
       cin>>c;
       switch(c) {
           case 1:
              cout<<"Size of the Set: ";
              cout<<st.size()<<endl;
           break;
           case 2:
              cout<<"Enter value to be inserted: ";
              cin>>i;
              st.insert(i);
           break;
           case 3:
              cout<<"Enter the element to be deleted: ";
              cin>>i;
              st.erase(i);
           break;
           case 4:
              cout<<"Enter the element to be found: ";
              cin>>i;
              it = st.find(i);
              if (it != st.end())
                 cout<<"Element "<<*it<<" found in the set" <<endl;
              else
                 cout<<"No Element Found"<<endl;
           break;
           case 5:
              cout<<"Displaying Set by Iterator: ";
              for (it = st.begin(); it != st.end(); it++) {
                 cout << (*it)<<" ";
              }
              cout<<endl;
           break;
           case 6:
              exit(1);
           break;
           default:
              cout<<"Wrong Choice"<<endl;
       }
   }
return 0;
}

실행 결과

프로그램을 실행하면 메뉴가 계속 반복해서 표시되며, 번호를 입력할 때마다 해당 기능이 수행됩니다. 아래는 핵심 동작 흐름을 정리한 실행 결과 예시입니다.

1.Size of the Set
2.Insert Element into the Set
3.Delete Element of the Set
4.Find Element in a Set
5.Display the set:
6.Exit

Enter your Choice: 1
Size of the Set: 0

Enter your Choice: 2
Enter value to be inserted: 1

Enter your Choice: 2
Enter value to be inserted: 7

Enter your Choice: 2
Enter value to be inserted: 6

Enter your Choice: 2
Enter value to be inserted: 4

Enter your Choice: 3
Enter the element to be deleted: 1

Enter your Choice: 4
Enter the element to be found: 7
Element 7 found in the set

Enter your Choice: 6
Exit code: 1

위 실행 결과에서 알 수 있듯이, 집합에 1, 7, 6, 4를 차례로 삽입한 뒤 1을 삭제하면 나머지 요소인 4, 6, 7만 남게 됩니다. 또한 find() 함수를 통해 값 7이 집합에 존재하는지 성공적으로 확인할 수 있습니다. 만약 5번 메뉴를 선택하면 begin()부터 end()까지 반복자를 순회하면서 요소들이 항상 정렬된 순서(4 6 7)로 출력되는 것을 확인할 수 있습니다.