Make Unreal REAL.
article thumbnail

 

map에서 키가 존재하는지 확인하는 방법은 3가지가 있다.

 

첫 번째 방법은 [] 연산자를 사용하는 것이다.

 

#include <iostream>
#include <map>

using namespace std;

void main()
{
    map<string, int> mp;
    
    if (mp["Key"] == 0)
        cout << "Found " << mp["Key"] << endl;
        
    cout << "Map size: " << mp.size();
}

 

이 방법의 문제점은 2가지다.

  1. [] 연산자를 통해 접근하는 것만으로도 해당 자료형의 기본값으로 초기화가 진행되어 버린다.
    그래서 크기가 증가한다.
  2. 자동으로 할당된 기본값과 의도적으로 할당한 기본값을 구분할 수 없다.

 

Found 0
Map size: 1

 

두 번째 방법은 map.at() 함수를 사용하는 것이다.

 

#include <iostream>
#include <map>

using namespace std;

void main()
{
    map<string, int> mp;
    
    if (mp.at("Key") == 0)
        cout << "Found " << mp["Key"] << endl;
        
    cout << "Map size: " << mp.size();
}

 

이 방법의 문제점은 키가 존재하지 않으면, out_of_range 예외를 발생시켜 버린다는 것이다.

 

terminate called after throwing an instance of 'std::out_of_range'
  what():  map::at

 

마지막 방법은 map.find() 함수를 사용하는 것이다.

 

#include <iostream>
#include <map>

using namespace std;

void main()
{
    map<string, int> mp;
    
    if (mp.find("Key") != mp.end())
        cout << "Found " << mp["Key"] << endl;
        
    cout << "Map size: " << mp.size();
}

 

기본값 초기화나 예외 발생 없이 가장 안전하게 사용할 수 있는 방법이다.

 

Map size: 0
profile

Make Unreal REAL.

@diesuki4

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

검색 태그