ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • C++_map
    Programming/_C++ 2023. 7. 27. 15:40

     map은 각각의 노드가 key와 value가 한 쌍으로 이루어진 트리이며 중복을 허용하지 않는다는 특징이 있다.

    우리가 Alogrithm 문제를 풀면서 key와 value를 다룰때가 많은데 Python의 경우 dictionary가 있지만, C++에서는 map을 사용해서 문제를 풀어나가게 된다.

    이번에는 map을 어떻게 사용하는지 한번 알아보자.

    #include <map>
    
    //map의 기본형태
    map<key_type, value_type> test_map;

    map은 key type과 value type으로 선언을 한다. map에 insert()를 사용하여 값을 삽입하는데 삽입이 되면 자동으로 정렬을 하며, 기본적으로는 오름차순 정렬을 한다.

     

    기본적인 사용법은 아래의 예제와 같다.

    #include <iostream>
    #include <map>
    
    using namespace std;
    
    int main() 
    {
        //test_map 선언
        map<string, int> test_map;
    
        test_map.insert(pair<string, int>("number2", 20));
        test_map.insert(pair<string, int>("number1", 10));
    
        //copy_map에 test_map 복사
        map<string, int> copy_map(test_map);
    
        // test_map2 내림차순으로 선언
        map<string, int, greater<string>> test_map2;
    
        test_map2.insert(pair<string, int>("number1", 50));
        test_map2.insert(pair<string, int>("number3", 60));
        test_map2.insert(pair<string, int>("number2", 90));
        
        // 순회 접근하기위해 선언
        map<string, int>::iterator iter;
    
        // test_map 출력
        for (iter = test_map.begin(); iter != test_map.end(); iter++)
        {
            cout << iter -> first << ", " << iter -> second << " ";
        } cout << endl;
    
        // copy_map 출력
        for (iter = copy_map.begin(); iter != copy_map.end(); iter++)
        {
            cout << (*iter).first << ", " << (*iter).second << " ";
        } cout << endl;
    
        // test_map2 출력
        for (iter = test_map2.begin(); iter != test_map2.end(); iter++)
        {
            cout << iter -> first << ", " << iter -> second << " ";
        } cout << endl;
    }

    결과:

    insert(pair)를 사용하여 key와 value를 넣었고, greater<>를 사용하여 key의 오름차순 및 내림차순으로 정렬되는 것을 볼 수 있다.

    insert(pair)가 아닌 [] operator로도 key, value를 추가할 수 있다.

    #include <iostream>
    #include <map>
    
    using namespace std;
    
    int main() 
    {
        //test_map 선언
        map<int, int> test_map;
    
        test_map[10] = 1004;
        test_map[1] = 20;
        test_map[3] = 25;
        
        // 순회 접근하기위해 선언
        map<int, int>::iterator iter;
    
        // test_map 출력
        for (iter = test_map.begin(); iter != test_map.end(); iter++)
        {
            cout << iter -> first << ", " << iter -> second << " ";
        } cout << endl;
    }

    결과:

    [] 안에 들어간 숫자가 key의 역할을 한다고 볼 수 있다.

     

    이번에는 map에서 사용하는 member function에 대해 알아보자


    - begin(), end()

     begin()은 첫번째 원소를, end()는 마지막 원소의 다음 부분을 가르킨다.

    #include <iostream>
    #include <map>
    
    using namespace std;
    
    int main() 
    {
        //test_map 선언
        map<string, int> test_map;
    
        test_map["num1"] = 5;
        test_map["num2"] = 10;
        test_map["num3"] = 15;
        
        // 순회 접근하기위해 선언
        map<string, int>::iterator iter;
        // test_map 출력
        for (iter = test_map.begin(); iter != test_map.end(); iter++)
        {
            cout << iter -> first << ", " << iter -> second << " ";
        } cout << endl;
    }

     

    - rbegin(), rend()

     begin(), end()와 반대로 역으로 출력이 된다.

    rbegin(), rend()를 쓸때는 reverse_iterator를 사용해야 한다.

    #include <iostream>
    #include <map>
    
    using namespace std;
    
    int main() 
    {
        //test_map 선언
        map<string, int> test_map;
    
        test_map["num1"] = 5;
        test_map["num2"] = 10;
        test_map["num3"] = 15;
        
        // reverse_iterator
        map<string, int>::reverse_iterator r_iter;
    
        // test_map 출력
        for (r_iter = test_map.rbegin(); r_iter != test_map.rend(); r_iter++)
        {
            cout << r_iter -> first << ", " << r_iter -> second << " ";
        } cout << endl;
    }

     

    - empty()

     선언한 map이 비어있는지 확인한다.

    #include <iostream>
    #include <map>
    
    using namespace std;
    
    int main() 
    {
        //test_map 선언
        map<string, int> test_map;
    
        cout << test_map.empty() << endl; // 1출력
    
        test_map["num1"] = 5;
    
        cout << test_map.empty() << endl; // 0출력
    }

     

    - size(), max_size()

     size()는 선언한 map 원소의 갯수를 반환하고, max_size()는 선언한 map이 가질 수 있는 최대 메모리 크기를 이야기한다.

    #include <iostream>
    #include <map>
    
    using namespace std;
    
    int main() 
    {
        //test_map 선언
        map<string, int> test_map;
    
        cout << test_map.size() << endl;
        cout << test_map.max_size() << endl;
    
        test_map["num1"] = 5;
    
        cout << test_map.size() << endl;
        cout << test_map.max_size() << endl;
    }

    결과:

     

    - clear

    #include <iostream>
    #include <map>
    
    using namespace std;
    
    int main() 
    {
        //test_map 선언
        map<string, int> test_map;
        map<string, int>::iterator iter;
    
        test_map["num1"] = 5;
    
        for (iter = test_map.begin(); iter != test_map.end(); iter++)
        {
            cout << iter -> first << ", " << iter -> second << " ";
        } cout << endl;
    
        test_map.clear(); //clear
    
        for (iter = test_map.begin(); iter != test_map.end(); iter++)
        {
            cout << iter -> first << ", " << iter -> second << " ";
        } cout << endl;
    }

     

    - find()

     

     

    - insert()

     insert()는 element를 추가할 수 있다. key가 같지 않은 element라면 추가하고, key가 존재한다면, element를 반환한다.

    insert()를 사용하는 방법은 몇가지 예시가 있다.

     

    ex) 기본적인 형태

    #include <iostream>
    #include <map>
    
    using namespace std;
    
    int main() 
    {
        //test_map 선언
        map<char, int> test_map;
        
        //일반적인 insert
        test_map.insert(pair<char, int>('1', 1));
        test_map.insert(pair<char, int>('9', 9));
    
        // 앞에서 부터
        map<char, int>::iterator first_itor = test_map.begin();
        test_map.insert(first_itor, pair<char, int>('3', 3));
    
        // 뒤에서 부터
        map<char, int>::iterator last_itor = test_map.end();
        test_map.insert(last_itor, pair<char, int>('8', 8));
    }

    일반적으로 insert를 할 수 있으며, map 원소의 위치를 지정하여 그 부분부터 지정된 key로 insert 할 수도 있다.

     

    ex) bool

    #include <iostream>
    #include <map>
    
    using namespace std;
    
    int main() 
    {
        //test_map 선언
        map<char, int> test_map;
        
        //check_bool 선언
        pair<map<char, int>::iterator, bool> check_bool;
        check_bool = test_map.insert(pair<char, int> ('1', 1)); // pair<iter, bool> 반환
    
        if (check_bool.second) // check_bool의 second는 bool
        {
            cout << check_bool.first -> first << ':' << check_bool.second;
        }
    }

     

    ex) range

    #include <iostream>
    #include <map>
    
    using namespace std;
    
    int main() 
    {
        //test_map 선언
        map<char, int> test_map;
    
        map<char, int>::iterator itor;
        
        //일반적인 insert
        test_map.insert(pair<char, int>('1', 1));
        test_map.insert(pair<char, int>('3', 3));
        test_map.insert(pair<char, int>('9', 9));
        test_map.insert(pair<char, int>('7', 7));
        
        //당연히 정렬됨
        for (itor = test_map.begin(); itor != test_map.end(); itor++)
            cout << (*itor).first << ':' << (*itor).second << ' ';
        cout << endl;
        //copy_map 선언
        map<char, int> copy_map;
    
        //처음부터 7 key를 갖는 원소의 전까지 copy_map에 insert
        copy_map.insert(test_map.begin(), test_map.find('7'));
    
        for (itor = copy_map.begin(); itor != copy_map.end(); itor++)
            cout << (*itor).first <<  ':' << (*itor).second << ' ';
        cout << endl;
    }

     

    ex) 여러개 insert

    #include <iostream>
    #include <map>
    
    using namespace std;
    
    int main() 
    {
        //test_map 선언
        map<char, int> test_map;
    
        map<char, int>::iterator itor;
    
        //여러개의 key, value 입력
        test_map.insert({ {'1', 1}, {'2', 2} });
        
        for (itor = test_map.begin(); itor != test_map.end(); itor++)
            cout << (*itor).first << ':' << (*itor).second << ' ';
        cout << endl;
    }

     여러개의 key, value도 insert할 수 있다.

     

    - erase()

     

     

    - swap()

     

     

    - extract()

     

     

    - count()

     

     

     

     

     

    - contains()

     

     

    map 함수의 member function은 여러가지가 있으며, 아래의 사이트에 자세히 설명이 되어있다.


    https://en.cppreference.com/w/cpp/container/map

     

    std::map - cppreference.com

    (1) (2) (since C++17) std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare. Search, removal, and insertion operations have logarithmic complexity. Maps are usual

    en.cppreference.com

    'Programming > _C++' 카테고리의 다른 글

    _C++_알고리즘_Part_1  (0) 2023.09.19
    _C++_Smart_Pointer  (1) 2023.09.19
    C++_address_pointer_reference  (0) 2023.07.25
    C++_function  (0) 2023.07.21
    C++_for_while_(loop statement)  (0) 2023.07.20
Designed by Tistory.