C++_[STL]MAP

hong·2022년 5월 3일
0

💡 MAP이란??

  • 각 노드가 {key:value} 쌍으로 이루어진 균형 이진 트리 구조
  • key가 중복되는 것을 허용X
  • 삽입, 삭제시 자동으로 정렬(오름차순)
  • 필요에 따라 동적 할당
  • key값은 first인자로, value값은 second인자로 나타냄
  • index 사용X

✔️ 헤더파일

#include <map>

✔️ 변수 선언

map<char, int> m;

✔️ <key, value>쌍 데이터 추가

  1. 'map명'[key] = [value]
m['A'] = 1 ;
m['B'] = 2 ;
  1. 'map명'.insert(<key, value>쌍)
m.insert(make_pair('C', 3));
m.insert(pair<char, int>('D', 4));

✔️ map 모든 데이터 조회

map<char, int>::iterator it;
for (it = m.begin(); it != m.end(); it++)    // auto 형으로도 사용 가능
    cout << it->first << ' ' << it->second << '\n';
    
    
for (auto p : m)
    cout << p.first << ' ' << p.second << '\n';

✔️ 노드 삭제

'map명'.erase(key)

m.erase('A');

✔️ 모든 노드 삭제

'map명'.clear()

m.clear();

✔️ 노드 찾기

find 함수는 iterator 반환.'map명'.find(key)로 해당 노드 찾은 뒤, value값 접근

→ 키 값이 존재하지 않을 시 m.end() 반환

//value값 출력
cout << m.find('A')->second << endl;

map<char, int>::iterator it = m.find('A');
cout << it->second << endl;

if (m.find('A') == m.end())
    cout << "key 'A' doesn't exist" << endl;
else
    cout << "key 'A' exist" << endl;

✔️ map 비어있는지 확인

비어 있으면 true 반환. 비어 있지 않으면 false 반환

m.empty();

✔️ map 노드 개수 확인

m.size();

✔️ map 정렬

map을 vector 형태로 변환 후, vector와 동일하게 sort 적용

#include <algorithm>
#include <vector>

// 비교할 때 사용하는 함수
bool cmp(const pair<char, int>& a, const pair<char, int>& b){
	if(a.second == b.second) return a.first < b.first;
    return a.second < b.second;
}

vector<pair<char, int>> map2vec(m.begin(), m.end());
sort(map2vec.begin(), map2vec.end(), cmp);
profile
🐶 ☕️ 🧳

0개의 댓글