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

C++ STL set 컨테이너의 삽입과 삭제 완벽 가이드

C++ STL의 set은 중복을 허용하지 않고 자동으로 정렬된 상태를 유지하는 연관 컨테이너입니다. 이 글에서는 set에 요소를 추가하는 insert()emplace(), 그리고 요소를 제거하는 erase() 함수의 사용법을 예제 코드와 함께 살펴봅니다.


삽입(Insertion)

STL set에 요소를 삽입하는 방법에는 insert()emplace() 두 가지가 있습니다.

insert(): set에 요소를 삽입하는 데 사용되며, 삽입할 객체에 대한 참조를 인자로 전달받습니다.

사용되는 주요 함수

  • st.size() = set의 크기(저장된 요소 개수)를 반환합니다.
  • st.insert() = set에 요소를 삽입하는 데 사용됩니다.

예제 코드

#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.Display the set: "<<endl;
        cout<<"4.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<<"Displaying Set by Iterator: ";
                for (it = st.begin(); it != st.end(); it++) {
                    cout << (*it)<<" ";
                }
                cout<<endl;
            break;
            case 4:
                exit(1);
            break;
            default:
                cout<<"Wrong Choice"<<endl;
        }
    }
    return 0;
}

실행 결과

1.Size of the Set
2.Insert Element into the Set
3.Display the set:
4.Exit

Enter your Choice: 1
Size of the Set: 0
1.Size of the Set
2.Insert Element into the Set
3.Display the set:
4.Exit

Enter your Choice: 2
Enter value to be inserted: 4
1.Size of the Set
2.Insert Element into the Set
3.Display the set:
4.Exit

Enter your Choice: 2
Enter value to be inserted: 6
1.Size of the Set
2.Insert Element into the Set
3.Display the set:
4.Exit

Enter your Choice: 2
Enter value to be inserted: 8
1.Size of the Set
2.Insert Element into the Set
3.Display the set:
4.Exit

Enter your Choice: 2
Enter value to be inserted: 10
1.Size of the Set
2.Insert Element into the Set
3.Display the set:
4.Exit

Enter your Choice: 3
Displaying Set by Iterator: 4 6 8 10
1.Size of the Set
2.Insert Element into the Set
3.Display the set:
4.Exit
Enter your Choice: 4

Exit code: 1

실행 결과를 보면 입력 순서와 관계없이 요소들이 항상 오름차순(4, 6, 8, 10)으로 정렬되어 출력되는 것을 확인할 수 있습니다. 이것이 set의 핵심 특징입니다.

emplace()

emplace() 연산 역시 set에 요소를 삽입하는 데 사용되지만, 컨테이너 내부에서 객체를 직접 생성(in-place)한다는 점이 다릅니다. 불필요한 객체 복사나 이동 과정을 생략하기 때문에 insert()보다 더 효율적으로 동작할 수 있습니다.

사용되는 주요 함수

  • st.size() = set의 크기를 반환합니다.
  • st.emplace() = set에 요소를 제자리에서 생성하여 삽입하는 데 사용됩니다.

예제 코드

#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.Display the set: "<<endl;
        cout<<"4.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.emplace(i);
            break;
            case 3:
                cout<<"Displaying Set by Iterator: ";
                for (it = st.begin(); it != st.end(); it++) {
                    cout << (*it)<<" ";
                }
                cout<<endl;
            break;
            case 4:
                exit(1);
            break;
            default:
                cout<<"Wrong Choice"<<endl;
        }
    }
return 0;
}

실행 결과

1.Size of the Set
2.Insert Element into the Set
3.Display the set:
4.Exit
Enter your Choice: 1
Size of the Set: 0
1.Size of the Set
2.Insert Element into the Set
3.Display the set:
4.Exit
Enter your Choice: 2
Enter value to be inserted: 4
1.Size of the Set
2.Insert Element into the Set
3.Display the set:
4.Exit
Enter your Choice: 6
Wrong Choice
1.Size of the Set
2.Insert Element into the Set
3.Display the set:
4.Exit
Enter your Choice: 2
Enter value to be inserted: 6
1.Size of the Set
2.Insert Element into the Set
3.Display the set:
4.Exit
Enter your Choice: 2
Enter value to be inserted: 7
1.Size of the Set
2.Insert Element into the Set
3.Display the set:
4.Exit
Enter your Choice: 2
Enter value to be inserted: 8
1.Size of the Set
2.Insert Element into the Set
3.Display the set:
4.Exit
Enter your Choice: 3
Displaying Set by Iterator: 4 6 7 8
1.Size of the Set
2.Insert Element into the Set
3.Display the set:
4.Exit
Enter your Choice: 4

Exit code: 1

삭제(Deletion)

erase() 함수를 사용하면 set에서 요소를 삭제할 수 있습니다. 인자로 특정 위치(반복자), 값(value), 또는 범위(range)를 지정할 수 있어 다양한 방식의 삭제가 가능합니다.

사용되는 주요 함수

  • st.size() = set의 크기를 반환합니다.
  • st.insert() = set에 요소를 삽입하는 데 사용됩니다.
  • st.erase() = set에서 요소를 삭제하는 데 사용됩니다.

예제 코드

#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 from the Set"<<endl;
        cout<<"4.Display the set: "<<endl;
        cout<<"5.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<<"Displaying Set by Iterator: ";
                for (it = st.begin(); it != st.end(); it++) {
                    cout << (*it)<<" ";
                }
                cout<<endl;
            break;
            case 5:
                exit(1);
            break;
            default:
                cout<<"Wrong Choice"<<endl;
        }
}
return 0;
}

실행 결과

1.Size of the Set
2.Insert Element into the Set
3.Delete Element from the Set
4.Display the set:
5.Exit

Enter your Choice: 1
Size of the Set: 0
1.Size of the Set
2.Insert Element into the Set
3.Delete Element from the Set
4.Display the set:
5.Exit

Enter your Choice: 2
Enter value to be inserted: 1
1.Size of the Set
2.Insert Element into the Set
3.Delete Element from the Set
4.Display the set:
5.Exit

Enter your Choice: 2
Enter value to be inserted: 2
1.Size of the Set
2.Insert Element into the Set
3.Delete Element from the Set
4.Display the set:
5.Exit

Enter your Choice: 2
Enter value to be inserted: 3
1.Size of the Set
2.Insert Element into the Set
3.Delete Element from the Set
4.Display the set:
5.Exit

Enter your Choice: 2
Enter value to be inserted: 4
1.Size of the Set
2.Insert Element into the Set
3.Delete Element from the Set
4.Display the set:
5.Exit

Enter your Choice: 4
Displaying Set by Iterator: 1 2 3 4
1.Size of the Set
2.Insert Element into the Set
3.Delete Element from the Set
4.Display the set:
5.Exit

Enter your Choice: 3
Enter the element to be deleted: 2
1.Size of the Set
2.Insert Element into the Set
3.Delete Element from the Set
4.Display the set:
5.Exit

Enter your Choice: 4
Displaying Set by Iterator: 1 3 4
1.Size of the Set
2.Insert Element into the Set
3.Delete Element from the Set
4.Display the set:
5.Exit
Enter your Choice: 5

Exit code: 1

위 실행 결과에서 값 2를 삭제한 후 set이 1 3 4로 출력된 것을 확인할 수 있습니다. 이처럼 erase()는 값을 기준으로 해당 요소를 간단하게 제거할 수 있으며, 삽입과 마찬가지로 남은 요소들은 계속 정렬된 상태를 유지합니다.