c++/ 자료구조&알고리즘 개념 복습하기 - 10 / Map, STL map, STL unordered_map

한창희·2022년 3월 4일
0

https://kimcoder.tistory.com/122



  • 기본적으로 key 값 기준 오름차순 정렬!!

< 초기값 >

  • 존재하지 않는 key 값을 인덱스로 하여 Map에 접근하면 기본타입의 value 값이 나온다
    ex> value가 int -> 0, string -> ""
map<string, int> m;

m["hi"] -= 1;
cout << m["hi"];
  • 위 코드는 -1 이 출력된다!
  • value 타입이 int 여서 기본적으로 0값을 가진다

< 조회 >

map[key];

key 에 해당하는 value 값 반환



< map 순회 >

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

int main() {
	
    map<int, string>::iterator ite; // 직접 이터레이터 선언도 가능

    map<int, string> tempMap = {{1, "Apple",},
                                {2, "Banana",},
                                {3, "Mango",},
                                {4, "Raspberry",},
                                {5, "Blackberry",},
                                {6, "Cocoa",}};

    for (auto iter = tempMap.begin(); iter != tempMap.end(); ++iter){
        cout << "[" << iter->first << ","
                    << iter->second << "]\n";
    }
    
    for (ite = tempMap.begin(); ite != tempMap.end(); ite++)
   {
       cout << "[" << ite->first << ","
            << ite->second << "]\n";
   }
    
    return 0;
}

// 두개의 결과는 같다


< value 기준 map 정렬 >

  1. map -> vector
  2. vector 정렬
#include <string>
#include <vector>
#include <map>
#include <algorithm> // for sort
#include <iostream>

using namespace std;

bool compare(const pair<int, int> &first, const pair<int, int> &second) {
    return first.second < second.second; // value 오름차순 정렬 위함
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    map<int, int> m;
    m[1] = 2;
    m[2] = 4;
    m[3] = 3;
    m[4] = 1;

    vector<pair<int, int>> v(m.begin(), m.end()); // map -> vector

    sort(v.begin(), v.end(), compare); // sort

    for(int i = 0; i < v.size(); i++) {
        cout << "key : " << v[i].first << ", value : " << v[i].second << "\n";
    }

    return 0;
}

// 출력
key : 4, value : 1
key : 1, value : 2
key : 3, value : 3
key : 2, value : 4

< STL unordered_map>

  • <unordered_map> 헤더 필요
  • map보다 속도가 조금 더 빠름
  • 사용법은 map 과 동일
  • 정렬이 필요 없는 상황이면 unordered_map 사용해보자

https://m.blog.naver.com/rapperkjm/221038507723
https://www.geeksforgeeks.org/map-vs-unordered_map-c/


profile
매 순간 최선을 다하자

0개의 댓글