Table of contents

1. 정리

map 라이브러리는 key값에 따른 value를 저장하고 추가/수정/삭제를 쉽게 처리하도록 도와줍니다.

map 라이브러리를 활용하기 위해, 먼저 map을 선언해봅시다.

//map 선언 <string, int>
map< string, int > Map;		

 

선언된 map에 키 값과 키 값에 따른 값을 저장해봅시다. 방법은 2가지인데, 두 번째, 방식이 더욱 직관적이네요. 선호하는 방식에 맞춰 사용하시면 될 듯 합니다. 각각의 Key값는 0과 1을 저장했습니다.

//Map 추가방법
Map.insert(make_pair("Key1", 0));		
Map["Key2"] = 1;

 

이제 Key 값에 따라 검색해보겠습니다. 마찬가지로 2가지가 있는데 두 번째, 방식이 더욱 직관적이네요. 출력해보면 위에서 저장했던 값들인 0과 1이 출력됩니다.

//Map 검색방법
cout << "Key1 : " << Map.find("Key1")->second << endl;
cout << "Key2 : " << Map["Key2"] << endl;

 

다음은 map이 비어있는지 출력해보겠습니다. 비어있지 않기 때문에 0이 출력됩니다. 비어있다면 1이 출력됨을 유추할 수 있네요.

//Map 비어있는지 검사
cout << "Map.empty() : " << Map.empty() << endl;

 

다음은 map의 크기를 출력해보겠습니다. 저장한 값이 2개뿐이므로, 크기는 2가 출력됩니다.

//Map 사이즈
cout << "Map.size() : " << Map.size() << endl;

 

다음은 모든 map의 Key값과 Value 값를 출력하겠습니다. c++의 가장 큰 장점중 하나인 begin()과 end() 사용이 가능하네요. 

//Map 모든 변수 출력
for (auto it = Map.begin(); it != Map.end(); it++) {
	cout << "Key: " << it->first << " " << "Value: " << it->second << endl;
}

2. 전체코드

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

using namespace std;

int main() {
	//map 선언 <string, int>
	map< string, int > Map;					
	
	//Map 추가방법
	Map.insert(make_pair("Key1", 0));		
	Map["Key2"] = 1;						

	//Map 검색방법
	cout << "Key1 : " << Map.find("Key1")->second << endl;
	cout << "Key2 : " << Map["Key2"] << endl;

	//Map 비어있는지 검사
	cout << "Map.empty() : " << Map.empty() << endl;

	//Map 사이즈
	cout << "Map.size() : " << Map.size() << endl;

	//Map 모든 변수 출력
	for (auto it = Map.begin(); it != Map.end(); it++) {
		cout << "Key: " << it->first << " " << "Value: " << it->second << endl;
	}

	return 0;

}