C++ STL Set erase 메서드

C++Beginner
지금 연습하기

소개

이 랩에서는 C++ 프로그래밍 언어에서 Multiset 의 작동 방식과 구현에 대해 배우게 됩니다. 특히 Set 또는 Multiset 에서 요소를 삭제하기 위해 erase() 메서드를 사용하는 방법을 배우게 됩니다.

C++ 코드 파일 생성

원하는 텍스트 편집기를 사용하여 프로젝트 디렉토리 ~/projectmain.cpp라는 새 C++ 코드 파일을 생성합니다.

cd ~/project
touch main.cpp

C++ 코드 작성

다음 코드를 main.cpp 파일에 입력합니다. 주석은 코드를 설명합니다.

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

// 반복자를 사용하여 multiset 의 요소를 출력하는 함수
void show(multiset<int> s)
{
    // multiset 을 반복하기 위한 반복자 선언
    multiset<int>::iterator i;

    for (i = s.begin(); i != s.end(); i++)
    {
        cout << *i << "  "; // i가 각 요소의 주소를 저장하므로 *를 사용하여 multiset의 요소에 접근
    }

    cout << endl;
}

int main()
{
    cout << "\n\nSTL Set erase() 메서드 랩에 오신 것을 환영합니다\n\n\n";
    cout << " =====  CPP 에서 Multiset 의 작동 방식을 보여주는 프로그램  ===== \n\n\n\n";

    cout << "*** Multiset은 여러 요소가 동일한 값을 가질 수 있다는 예외를 제외하고 set과 유사합니다. *** \n\n";

    // Set 선언 (정수 집합)
    multiset<int> s;

    // insert() 메서드를 사용하여 요소 채우기
    cout << "\n\n무작위 순서로 정수로 Multiset 채우기."; // Multiset은 자동으로 정렬하여 저장합니다.

    s.insert(5);
    s.insert(39);
    s.insert(5);
    s.insert(82);
    s.insert(39);
    s.insert(54);

    cout << "\n\nMultiset의 요소 수는: " << s.size();

    cout << "\n\nMultiset의 요소는: ";
    show(s);

    multiset<int>::iterator it;

    // 54 미만인 set의 모든 요소 삭제
    s.erase(s.begin(), s.find(54));

    cout << "\n\n54 미만인 모든 요소를 삭제한 후 Multiset은 다음과 같습니다: ";

    for (it = s.begin(); it != s.end(); it++)
    {
        cout << " " << *it;
    }

    cout << "\n\n\n";

    return 0;
}

C++ 코드 컴파일 및 실행

터미널에서 g++ 명령을 사용하여 main.cpp 파일을 컴파일한 다음, 컴파일된 파일을 실행합니다.

g++ main.cpp -o main && ./main

다음과 같은 출력을 볼 수 있습니다.

Welcome to STL Set erase() Method Lab


 =====  Program to demonstrate the working of a Multiset, in CPP  =====



*** Multisets are similar to set, with an exception that multiple elements can have same values. ***


Filling the Multiset with integers in random order.
The number of elements in the Multiset are: 6

The elements of the Multiset are: 5  5  39  39  54  82

After deleting all the elements that are less than 54, the Multiset becomes :  54  82

코드 검토

코드를 검토하고 erase() 메서드가 Multiset 에서 요소를 삭제하는 방법을 이해했는지 확인하십시오.

//Deleting all the elements of the set that are less than 54
s.erase(s.begin(), s.find(54));

이 코드는 erase() 메서드를 사용하여 Multiset 의 시작 부분부터 값 54 를 가진 요소를 제외한 모든 요소를 삭제합니다. 따라서 결과 Multiset 에는 값 54 와 82 만 포함됩니다.

요약

이 Lab 에서는 C++ Set 또는 Multiset 에서 erase() 메서드를 사용하여 요소를 삭제하는 방법을 배웠습니다. 또한 반복자 (iterator) 를 사용하여 multiset 을 반복하고 show() 메서드를 사용하여 요소를 출력하는 방법도 배웠습니다. 이는 Set 및 Multiset 과 같은 복잡한 데이터 구조의 디버깅 또는 내용 확인에 유용합니다.