c++ std::map erase 방법입니다. map 각 노드가 key와 value 쌍으로 이루어진 트리입니다. 중복을 허용하지 않습니다.(multimap 중복 허용)
map은 first, second가 있는 pair 객체로 저장됩니다. frist는 key, second는 value로 저장됩니다.
C++ map은 내부 구현은 검색, 삭제가 O(lonn)인 레드블랙트리로 구성되어 있습니다.
#include <iostream>
#include <map>
int main()
{
std::map<int, int> test_map;
for (int i = 0; i < 10; i++)
{
test_map.insert(std::pair<int,int>(i, i));
}
for (auto it = test_map.begin(); it!=test_map.end(); it++ ) {
std::cout << it->first << "," << it->second << std::endl;
}
for (auto it = test_map.begin(); it != test_map.end(); it++) // 오류 발생
{
test_map.erase(it);
}
/*
for (auto it = test_map.begin(); it != test_map.end();)
{
test_map.erase(it++);
}
*/
}
map erase() 사용 시 주의사항이 있습니다. erase 이후 이터레이터는 무효화가 됩니다.

일반적으로 for문에서 아래와 같이 사용하는 경우 이터레이터를 증감하는 경우가 많습니다. 하지만 일부 구간에서는 정상적으로 동작 할 수 있으나, erase()호출 이후 이터레이터가 무효화되어 정상적인 동작이 안되는 경우도 발생합니다.
for (auto it = test_map.begin(); it != test_map.end(); it++) // 오류 발생
{
test_map.erase(it);
}
무효화를 방지하기 위해서 erase 호출하기 전 미리 반복자를 이요해서 복사를 하고 erase를 호출하는 것이 안전합니다.
for (auto it = test_map.begin(); it != test_map.end();)
{
test_map.erase(it++);
}
it++를 내부적으로 복사를 하고 증가하기 때문에 erase에 의해 제거된 원소를 참조하지 않고 증감된 it를 참조해 안전하게 삭제가 이루어 집니다.
for (auto it = test_map.begin(); it != test_map.end();)
{
it = test_map.erase(it);
}
c+11인 경우 erase()리턴을 받는 방법도 가능합니다.

참고
https://cplusplus.com/reference/map/map/erase/
https://cplusplus.com/reference/map/map/erase/
The other versions return no value. The other versions return an iterator to the element that follows the last element removed (or map::end, if the last element was removed). Member type iterator is a bidirectional iterator type that points to an element.
cplusplus.com
[C++] STL map의 요소 삭제시 주의 할 점
요즘들어 포스팅 하는 주기가 점점 길어 지고 있네요. 날씨는 점점 추워지고 솔로들이 더욱 살아 남기 힘들어지는 크리스마스가 다가 오고 있습니다. 저도 크리스마스 때 남들처럼 거리를 활보
kukuta.tistory.com
https://life-with-coding.tistory.com/305
[C++][STL] map 사용법 정리
인트로 안녕하세요. 오늘은 C++ STL 연관 컨테이너 중 하나인 map에 대해 알려드리겠습니다. 목차 1) Map이란? 2) Map 기본 형태 3) Map 정렬 4) Map 사용방법 - 헤더 포함 - map 선언 - search : map에서 데이터
life-with-coding.tistory.com