C++/STL

Map

돌아온무니 2024. 3. 19. 13:56

Map이란?

map은 각 노드가 key와 value 쌍으로 이루어진 트리입니다.  특히, 중복을 허용하지 않습니다.

따라서 map은 first, second가 있는 pair 객체로 저장되는 데 first- key로 second- value로 저장된다. 

C++의 map의 내부 구현은 검색, 삽입, 삭제가 O(logn) 인 레드블랙트리로 구성되어 있다.


MAP 기본형

map <key, value> map1;

 

3) MAP 정렬

map은 자료를 저장할때 내부에서 자동으로 정렬합니다.

map은 key를 기준으로 정렬하며 오름차순으로 정렬합니다.

만약 내림차순으로 정렬하고 싶은 경우와 같이 사용하면 됩니다.

map <int, int, greater> map1; 

(만약 다른 방법으로 int데이터를 내림차순으로 정렬하고 싶을 경우,

데이터에 -(마이너스)를 붙여 삽입하여 처리하면 내림차순으로 정렬됩니다.)

 

 

Map 헤더파일

 #include <map> 

 

 

 Map 데이터 찾기

 

데이터를 끝까지 찾지 못했을 경우, iterator는 map.end()를 반환합니다.

if (m.find("Moon") != m.end()) {
	cout << "find" << endl;
}
else {
	cout << "not find" << endl;
}

 

Map 데이터 삽입

map은 중복을 허용하지 않습니다.

m.insert({"money", 300});


반복문 데이터 접근 (first, second)

//인덱스기반
for (auto iter = m.begin() ; iter !=  m.end(); iter++)
{
	cout << iter->first << " " << iter->second << endl;
}
cout << endl;

 

범위 기반 반복문 활용한 예제 

for (auto iter : m) {
	cout << iter.first << " " << iter.second << endl;
}

 

 Map에서 삭제

 

특정 위치의 요소 삭제

m.erase(m.begin()+2);

key값 삭제

m.erase("Moon");

map의 모든 요소 삭제

m.erase(m.begin(), m.end());

clear 함수 모든 요소 삭제

m.clear();

 


 

map 예제 코드

#include <iostream>
#include <map>
using namespace std;
map<string, int> mapset;
int main(void) {

	mapset.insert({ "Kim", 100 });
	mapset.insert({ "Lee", 200 });

	if (mapset.find("Kim") != mapset.end()) 
	{
		cout << "find" << endl;
	}
	else {
		cout << "not find" << endl;
	}

	//인덱스기반
	for (auto iter = mapset.begin() ; iter !=  mapset.end(); iter++)
	{
		cout << iter->first << " " << iter->second << endl;
	}
	cout << endl;

	//범위기반
	for (auto iter : mapset) {
		cout << iter.first << " " << iter.second << endl;
	}

	return 0;
}