[C++ STL] map 사용

map 기본 설명

하나의 key와 value가 쌍으로 저장되는 컨테이너.
중복된 key을 저장해야한다면 multimap을 사용해야한다.

필요 헤더파일

#include <map>

생성, 값 입력 예시는 아래와 같다.

map<int, int> map_test;
    
// index처럼 입력
map_test[1] = 11;

// pair를 이용한 입력
pair<int, int> p( 2, 12 );
map_test.insert( p );

map_test.insert( pair<int, int>( 3,13 ) );
	
map_test.insert( make_pair( 4, 14 ) );

// 혹은 typedef를 하여 입력하기도 한다
typedef pair<int, int> Map_Unit;
map_test.insert( Map_Unit( 5, 15 ) );

값을 입력할 때 중복을 확인하는 방법은 아래와 같다.

// find 함수로 확인
if ( map_test.end() != map_test.find( 1 ) )
	cout << "이미 존재합니다" << endl;
    
// pair를 이용하여 입력하며 확인
pair< map<int, int>::iterator, bool > prResult;
prResult = map_test.insert( pair<int, int>( 6, 16 ) );
if ( prResult.second )
	cout << "(" << prResult.first->first << ", " << prResult.first->second << ")" << endl;
else
	cout << "이미 존재합니다" << endl;

특정 key값을 읽기 위해선 아래 예시처럼 한다.

int iGet = map_test[1];

map에서 특정 key를 삭제하려면 아래와 같다.

map_test.erase(1);
심화 : vector와 map

map 컨테이너는 일반 변수 뿐만 아니라, 구조체, 클래스 또한 value로 사용 가능하다.

#include <iostream>
#include <string>
#include <vector>
#include <map>

using namespace std;

typedef vector<string> vectorType;
typedef map<int, vectorType> MapType;

void main()
{
	MapType map_Test;
	vectorType vector_Test;

	vector_Test = vectorType{ "string1_1", "string1_2", "string1_3" };
	map_Test[1] = vector_Test;

	vector_Test = vectorType{ "string2_1", "string2_2" };
	map_Test[2] = vector_Test;

	vector_Test = vectorType{ "string3_1", "string3_2", "string3_3", "string3_4" };
	map_Test[3] = vector_Test;
    
	MapType::iterator mapitr;
	for ( mapitr = map_Test.begin() ; mapitr != map_Test.end() ; mapitr++ )
	{
		cout << mapitr->first << " : ";

		vectorType::iterator vectoritr;
		for ( vectoritr = mapitr->second.begin(); vectoritr != mapitr->second.end() ; vectoritr++ )
		{
			cout << *vectoritr << ", ";
		}
		cout << endl;
	}
}