[C++] map container

Yewon Choi·2020년 6월 22일
0

C++

목록 보기
7/9

  • 노드 기반으로 이루어진 균형 이진 트리 구조
  • key, value로 이루어져 있으며 pair객체 형태로 저장
  • 중복 불가능한 Unique key (중복 key는 multimap에서 가능)
  • 삽입되면서 자동으로 정렬 (기준 : 오름차순)
  • 동적할당

map 생성자와 연산자

  • map<int, int> m; m[1] = 1 //[1, 1]
  • map<int, string> m;
  • map m(pred);
  • map m2(m1);

map 기본 함수

기본형태

  • map : key와 value를 pair 형태로 선언합니다.

iterator(반복자)

  • begin() : beginning iterator를 반환
  • end() : end iterator를 반환

추가 및 삭제

  • insert( make_pair(key,value) ) : 맵에 원소를 pair 형태로 추가
  • erase(key) : 맵에서 key(키값)에 해당하는 원소 삭제
  • clear() : 맵의 원소들 모두 삭제

조회

  • find(key) : key(키값)에 해당하는 iterator를 반환
  • count(key) : key(키값)에 해당하는 원소들(value들)의 개수를 반환

기타

  • empty() : 맵이 비어있으면 true 아니면 false를 반환
  • size() : 맵 원소들의 수를 반환

구현 코드

#include <iostream>
#include <map>

using namespace std;

int main(void){
	map<int, string> m;
	m.insert(pair<int, string>(1, "one"));
	m.insert(pair<int, string>(2, "two"));
	m.insert(pair<int, string>(3, "three"));
	m.insert(pair<int, string>(4, "four"));
	
	map<int, string>::iterator iter;
	for(iter = m.begin(); iter != m.end(); iter++){
		cout << (*iter).first << ", " << (*iter).second << endl;
	}
	
	map<int, int> m2;
	m2[9] = 123;
	m2[3] = 532;
	m2[4] = 999;
	
	map<int, int>::iterator iter2;
	for(iter2 = m2.begin(); iter2 != m2.end(); iter2++){
		cout << iter2->first << ' ' << iter2->second << endl;
	}
}

1, one
2, two
3, three
4, four
3 532
4 999
9 123






출처 : https://blockdmask.tistory.com

profile
https://github.com/devAon 찰나의 개발흔적을 남기는 개발블로그 입니다 🐥 https://aonee.tistory.com 에서 Velog로 블로그 이전 작업중입니다 ! 🎶

0개의 댓글