happy318
팽도리블로그
happy318
전체 방문자
오늘
어제
  • 전체글 (252)
    • 공부 (5)
      • Algorithm 정리 (0)
      • 논문리뷰 (1)
      • C++ (2)
      • Python (2)
      • Java (0)
      • Back-end (0)
      • Front-end (0)
      • Embedded (0)
    • 코딩테스트 (218)
      • Python 문제풀이 (100)
      • C++ 문제풀이 (108)
      • Python template (9)
      • C++ template (1)
    • 일상 (20)
      • 맛집 (13)
      • 쇼핑 (5)
      • 아무 일상 (2)
    • 게임 (9)
      • 메이플스토리 (9)

최근 글

인기 글

hELLO · Designed By 정상우.
happy318

팽도리블로그

공부/C++

[C++] map과 defaultdict

2022. 8. 19. 21:19

 

https://www.geeksforgeeks.org/default-values-in-a-map-in-c-stl/

 

Default values in a Map in C++ STL - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

 

C++에서 map자료구조는 처음 선언 될 때는 empty하다. 

 

하지만, [] 등으로 조회가 되는 경우, key가 없다면, (e.g map<int,int> mpp;   mpp[1]; )

초기 자료형태를 기존에 가지고 있던 것 처럼, 즉 python의 defaultdict처럼 동작한다. 위의 mpp example에서는 int 자료구조의 0을 이미 가지고 있었던 것처럼 act 할 것이다.

https://stackoverflow.com/questions/2667355/mapint-int-default-values

 

map<int,int> default values

std::map<int,int> mapy; ++mapy[5]; Is it safe to assume that mapy[5] will always be 1? I mean, will mapy[5] always get the default value of 0 before '++', even if not explicitly declared, as...

stackoverflow.com

 

실제로 아래 두 코드는 동일한 형태로 동작하는 것을 확인 할 수 있다.

input : 영어 대소문자로 이루어진 문자열
output : 해당하는 문자열의 각 알파벳의 등장횟수

 

[Compile]

g++ -o test test.cpp -std=c++11

 

[코드 1]

#include <iostream>
#include <cctype>
#include <algorithm>
#include <map>

using namespace std;
int main(){
    string s;
    cin >> s;
    transform(s.begin(), s.end(), s.begin(), ::tolower);

    map<char, int> s_map; 
    for(int i = 0; i < s.length() ; i++){
        s_map[s[i]]++;
    }

    for(map<char, int>::iterator it = s_map.begin();
        it != s_map.end(); ++it)
    {
        std::cout << it->first << " " << it->second<< "\n";
    }

}

[코드 2]

#include <iostream>
#include <cctype>
#include <algorithm>
#include <map>

using namespace std;
int main(){
    string s;
    cin >> s;
    transform(s.begin(), s.end(), s.begin(), ::tolower);

    map<char, int> s_map; // todo : study unoredered map..
    for(int i = 0; i < s.length() ; i++){
        if (s_map.find(s[i]) == s_map.end()) {
        // not found
            s_map[s[i]] = 1;
        } else {
        // found
            s_map[s[i]]++;
        }
    }

    for(map<char, int>::iterator it = s_map.begin();
        it != s_map.end(); ++it)
    {
        std::cout << it->first << " " << it->second<< "\n";
    }

}
반응형

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

[C++] vector [], at 속도차이와 고찰  (0) 2022.08.21
    '공부/C++' 카테고리의 다른 글
    • [C++] vector [], at 속도차이와 고찰
    happy318
    happy318

    티스토리툴바