오늘의 인기 글
최근 글
최근 댓글
Today
Total
05-08 04:42
관리 메뉴

우노

[C++] Map 사용법 본문

Language/C++

[C++] Map 사용법

운호(Noah) 2022. 4. 26. 00:09

들어가기 앞서,

  • Map 의 원소는 Key 와 Value 로 이루어져있습니다.
  • Map 은 원소를 저장할 때, Key 를 기준으로 오름차순 정렬하며, Key 가 중복되면 저장되지 않습니다.

예제 코드

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

using namespace std;

int main(void){

    // Map 생성
    map<string, int> m;

    // 삽입 (pair 객체 사용)
    m.insert(make_pair("a", 1));

    // 삽입 (operaotr 사용)
    m["a"] = 2;

    // 전체 조회
    for (auto iter = m.begin(); iter != m.end(); iter++) {
        cout << "Key : " <<  iter->first << endl;
        cout << "Value : " << iter->second << endl;
    }

    // 전체 조회 (범위 기반 For 문 사용)
    for (auto iter : m){
        cout << "Key : " << iter.first << endl;
        cout << "Value : " << iter.second << endl;
    }

    // 특정 Key 의 Value 조회 (조회되지 않는다면, m.end()가 출력됨)
    cout << "Value : " << m.find("a")->second << endl;    

    // 특정 Key 의 Value 조회 (operator 사용)
    cout << "Value : " << m["a"] << endl;

    // 삭제 (Key 값 기준)
    m.erase("a");

}

'Language > C++' 카테고리의 다른 글

[C++] 범위 기반 for 문  (0) 2022.04.26
[C++] 1차원 Vector 초기화  (0) 2022.04.26
[C++] Set 사용법  (0) 2022.04.25
[C++] String 공백 분리  (0) 2022.04.25
[C++] Priority Queue 개념과 사용법  (2) 2021.12.07
Comments