Programming

[C/C++] std::map - 데이터(Value) 찾은 후 삭제

Trunk 2023. 4. 16. 10:02

Data delete after find.

  • erase() 함수는 iterator(위치)를 리턴하는데 이것을 받아 처리하는 방식이 가장 흔하게 사용하는 방식이다.
  • 알고리즘 사용하는 방법이 가장 최신이며 효율적인 방법으로 보이지만 상황에 맞게 사용하면 된다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
    std::map <intint> mapTemp;
 
    // TEST CASE 01 : 입력 방법 2가지
    mapTemp.insert(std::pair<intint>(11024));
    mapTemp.insert({ 22048 });
 
    // TEST CASE 02 : key(index) 찾아서 삭제하는 방법.
    auto itr = mapTemp.find(2);
    mapTemp.erase(itr);
 
    // TEST CASE 03 : Value(data) 찾아서 삭제하는 방법.
    auto itr = mapTemp.begin();
    while (itr != mapTemp.end())
    {
        if (itr->second == 1024)
        {
            // 후위 증가 연사자 : 현재 값을 임의 장소에 복제 후 프로세스가 완료되면 복제 값을 증가하여 되돌려 준다.
            mapTemp.erase(itr++);
        }
        else
        {
            ++itr;
        }
    }
    //////////////////////////////////////////////////
    auto itr = mapTemp.begin();
    while (itr != mapTemp.end())
    {
        if (itr->second == 1024)
        {
            // 다음 위치를 리턴하는 특징을 이용
            itr = mapTemp.erase(itr);
        }
        else
        {
            ++itr;
        }
    }
    //////////////////////////////////////////////////
#include <algorithm>        // 추가 필수!
    while (true)
    {
        auto itr = std::find_if(mapTemp.begin(), mapTemp.end(),
            [](const std::pair<intint>& mapData)->bool
            {
                return mapData.second == 1004;
            }
        );
 
        if (itr == mapTemp.end()) { break; }
        
        mapTemp.erase(itr);
    }
    //////////////////////////////////////////////////
    // 무한 반복이 염려된다면 for문을 이용해도 된다.
    int mapSize = mapTemp.size();   // 수행 횟수 문제 해결 방법이다.
    for (int i = 0; i < mapSize; ++i)
    {
        auto itr = std::find_if(mapTemp.begin(), mapTemp.end(),
            [](const std::map<intint>::value_type& mapData)->bool
            {
                return mapData.second == 1004;
            }
        );
 
        if (itr == mapTemp.end()) { break; }
 
        mapTemp.erase(itr);
    }
cs