C++ Map 에서 요소 제거하기

C++Beginner
지금 연습하기

소개

이 랩에서는 C++ STL 에서 erase() 메서드를 사용하여 map 의 요소를 제거하는 방법을 배우게 됩니다. map 은 key-value 쌍으로 데이터를 저장하는 컨테이너입니다.

맵 생성하기

main.cpp 파일에서 map 인스턴스를 생성하려면 파일 상단에 다음 헤더 파일을 포함합니다.

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

정수 key 와 value 를 갖는 map 을 다음과 같이 선언합니다.

map<int, int> m;

Map 에 데이터 삽입하기

insert() 메서드를 사용하여 map 에 임의의 데이터를 삽입합니다. make_pair() 메서드를 사용하여 key-value 쌍을 map 에 할당할 수 있습니다.

m.insert(make_pair(3, 9));
m.insert(make_pair(2, 4));
m.insert(make_pair(5, 25));
m.insert(make_pair(9, 81));
m.insert(make_pair(1, 1));

Map 에서 요소 삭제하기

erase(x) 메서드를 사용하여 key 값이 x인 map 의 요소를 제거합니다. 값이 존재하지 않으면 0 을 반환하고, 그렇지 않으면 1 을 반환합니다.

int j = m.erase(5);

if(j == 1) {
    cout << "\nThe Map element with key 5 is deleted.";
} else {
    cout << "\nThe Map element with key 5 does not exist.";
}

프로그램이 충돌하지 않고 map 에 존재하지 않는 key 값을 가진 요소를 제거할 수도 있습니다. 예를 들어:

int k = m.erase(6);

if(k != 0){
    cout << "\n\nThe Map element with key 6 is deleted\n\n";
} else {
    cout << "\n\nThe Map element with key 6 does not exist.";
}

코드 실행

코드를 실행하려면 터미널에서 main.cpp 파일이 있는 디렉토리로 이동하여 다음 명령을 입력하여 컴파일하고 실행합니다.

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

코드 완성

다음은 참조용 전체 코드입니다.

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

using namespace std;

int main()
{
    cout << "\n\nWelcome to LabEx :-)\n\n\n";
    cout << "===== Program to demonstrate the working of erase() method in a Map (Part 1), in CPP ===== \n\n\n";

    cout << "*** The erase(x) method deletes the map element with key as x and returns 1 if found else returns 0. *** \n\n";

    // Map declaration (Map with key and value both as integers)
    map<int, int> m;

    // Filling the elements by using the insert() method.
    cout << "\n\nFilling the Map with key-value pairs of integers in random order."; //Map automatically stores them in increasing order of keys

    //make_pair() is used to insert a key-value pair into the map
    m.insert(make_pair(3, 9));
    m.insert(make_pair(2, 4));
    m.insert(make_pair(5, 25));
    m.insert(make_pair(9, 81));
    m.insert(make_pair(1, 1));

    cout << "\n\nThe number of elements in the Map are: " << m.size();

    cout << "\n\nThe elements of the Map m are: ";

    map<int, int>::iterator i;
    int j = 0;

    for (i = m.begin(); i != m.end(); i++)
    {
        cout << "( " << i->first << ", " << i->second << " ) ";
    }

    //Finding the map element with key 5
    j = m.erase(5);

    if (j == 1)
    {
        cout << "\n\nThe Map element with key 5 is deleted.";
    }
    else
    {
        cout << "\n\nThe Map element with key 5 does not exist.";
    }

    cout << "\n\nThe number of elements in the Map becomes: " << m.size();

    cout << "\n\nThe elements of the Map m after the erase operation are:  ";

    j = 0;

    for (i = m.begin(); i != m.end(); i++)
    {
        cout << "( " << i->first << ", " << i->second << " ) ";
    }

    j = m.erase(6);

    if (i != m.end())
    {
        cout << "\n\nThe Map element with key 6 is deleted\n\n";
    }

    else
    {
        cout << "\n\nThe Map element with key 6 does not exist.";
    }

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

    return 0;
}

요약

이 랩에서는 맵을 생성하고 데이터를 채우는 것으로 시작했습니다. 그런 다음, erase() 메서드를 사용하여 키를 통해 맵에서 요소를 제거하는 방법을 배웠습니다. 위의 예제가 C++ STL 에서 맵에서 요소를 제거하는 방법을 이해하는 데 도움이 되기를 바랍니다.