[C++] STL 맵(Map)

Date:     Updated:

카테고리:

태그:

이 글은 C++ STL 맵(Map)을 공부하고 정리한 글입니다

  • 키(key)와 값(value)의 쌍들을 저장
  • 키는 중복될 수 없음
  • C++ 맵은 자동 정렬되는 컨테이너이진 탐색 트리(binary search tree) 기반
    • 오름차순

    코드 예시

    #include <map>
    
    int main()
    {
        std::map<std::string, int> simpleScoreMap;
          
        simpleScoreMap.insert(std::pair<std::string, int>("Mocha", 100));
        simpleScoreMap.insert(std::pair<std::string, int>("Coco", 50));
    
        simpleScoreMap["Mocha"] = 0;
    
        std::cout << "Current Size: " << simpleScoreMap.size() << std::endl;
    
        return 0;
    }
    

    std::pair<key, value>

    pair<first_type, second_type>
    
    • 두 데이터를 한 단위로 저장하는 구조
    std::pair<std::string, int> student1("Coco", 10);
    

    insert()

    std::pair<iterator, bool> insert(const value_type& value)
    
    • 새 요소를 map에 삽입한다
    • 반복자와 bool 값을 한 쌍으로 반환
      • 반복자는 요소를 가리키고
      • Bool 값은 삽입 결과를 알려줌
    • 키를 중복으로 삽입할 수 없음
    // <iterator, true>를 반환한다
    simpleScoreMap.insert(std::pair<std::string, int>("Moca", 100));
    
    // <iterator, false>를 반환한다
    simpleScoreMap.insert(std::pair<std::string, int>("Moca", 0));
    

    operator[]

    mapped_type& operator[](const Key& key);
    
    • key에 대응하는 값을 참조로 반환한다
    • map에 키가 없으면 새 요소를 삽입
      • int num = map["Key"] 로 값을 읽어 올 때 만약 해당 키가 없었다면 map에 해당 키로 새 요소가 추가된다(기본값 0)
    • map에 키가 이미 있으면 그 값을 덮어씀
    std::map<std::string, int> simpleScoreMap;
    
    simpleScoreMap["Coco"] = 10;      // 새 요소를 삽입한다
    simpleScoreMap["Coco"] = 50;      // "Coco"의 값을 덮어쓴다
    

    find()

    iterator find(const Key& key);
    
    • map에서 key를 찾으면 그에 대응하는 값을 가리키는 반복자를 반환
    • 못 찾으면 end()를 반환
    std::map<std::string, int>::iterator it = simpleScoreMap.find("Coco");
    
    if(it != simpleScoreMap.end())
    {
        std::cout << it->second << std::endl;
    }
    

    swap()

    void swap(map& other);
    
    • 두 map의 키와 값을 서로 맞바꾼다

    clear()

    void clear();
    
    • map을 비운다

    erase()

    void erase(iterator position);
    size_type erase(const key_type& key);
    void erase(iterator first, iterator last)
    
    • map의 요소들을 제거한다

사용자 정의 자료형을 키로 사용했을 때

  • 맵은 항상 정렬되서 반드시 두 키를 비교하는 함수를 만들어야 함
    • operator<()
bool StudentInfo::operator<(const StudentInfo& other) const
{
    if (mName == other.mName)
    {
        return mStudentID < other.mStudentID;
    }

    return mName < other.mName;
}

요소들을 정렬하는 또 다른 방법

  • map을 만들 때 비교함수(comparer)를 넣을 수도 있음
    • 남이 만든 구조체여서 접근이 안되거나 바꿀 수 없을 경우 사용하면 좋다
  struct StudentInfoComparer
  {
      bool operator()(const StudentInfo& left, const StudentInfo& right) const
      {
          return (left.getName() < right.getName());
      }
  };

  // Main.cpp
  std::map<StudentInfo, int, StudentInfoComparer> Scores;

맵의 장점

  • std::list나 std::vector보다 탐색속도가 더 빠름

맵의 단점

  • 자동으로 정렬됨
  • 해쉬맵이 아님. 따라서 O(1)이 아님


참조

포큐아카데미 C++ 언매니지드 프로그래밍



💻 열심히 공부해서 작성 중이니 오류나 틀린 부분이 있을 경우 
  언제든지 댓글 혹은 메일로 알려주시면 감사하겠습니다! 😸

맨 위로 이동하기

Cpp 카테고리 내 다른 글 보러가기

댓글 남기기