C++ map에서 키 값 찾기 (find, contains, count)

김종민·2025년 3월 19일

C++

목록 보기
5/5

map을 사용할 때 원하는 값이 있는지 확인하는 방법 세가지

find()

문법

iterator find (const key_type& k);const_iterator find (const key_type& k) const;

키 값인 k가 있는지 검색 후 map의 iterator를 반환한다.
없다면 map::end를 반환한다.

예시 : 성적을 입력하면 점수를 출력하는 코드

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

using namespace std;


int main()
{
    map<string, float> grade_map = {
        {"A+", 4.3},{"A0", 4.0},{"A-", 3.7},
        {"B+", 3.3},{"B0", 3.0},{"B-", 2.7},
        {"C+", 2.3},{"C0", 2.0},{"C-", 1.7},
        {"D+", 1.3},{"D0", 1.0},{"D-", 0.7}
    };

    string grade;
    cin >> grade;

    cout << fixed;
    cout.precision(1);
	
    // find의 결과로 iterator를 반환하기때문에 바로 value값 출력하도록함
    cout << grade_map.find(grade)->second;

    return 0;
}

입력

A+

출력

4.3

contains() - C++20 이상부터 사용가능

문법

bool contains( const Key& k ) const;

키 값인 k가 있다면 true, 아니라면 false를 반환한다.

예시

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

using namespace std;


int main()
{
    map<string, float> grade_map = {
        {"A+", 4.3},{"A0", 4.0},{"A-", 3.7},
        {"B+", 3.3},{"B0", 3.0},{"B-", 2.7},
        {"C+", 2.3},{"C0", 2.0},{"C-", 1.7},
        {"D+", 1.3},{"D0", 1.0},{"D-", 0.7}
    };

    // boolalpha - manipulator로 bool값을 true/false로 출력하도록해준다.
    cout << boolalpha << grade_map.contains("F");

    return 0;
}

출력

false

count()

문법

size_type count (const key_type& k) const;

키 값인 k가 몇 개 있는지 카운트해서 반환한다.
map 특성상 키 값은 유니크하기때문에 있으면 1, 없으면 0을 리턴한다.

예시

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

using namespace std;


int main()
{
    map<string, float> grade_map = {
        {"A+", 4.3},{"A0", 4.0},{"A-", 3.7},
        {"B+", 3.3},{"B0", 3.0},{"B-", 2.7},
        {"C+", 2.3},{"C0", 2.0},{"C-", 1.7},
        {"D+", 1.3},{"D0", 1.0},{"D-", 0.7}
    };
	
    if(grade_map.count("C+"))
    {
    	cout << "true";
    }
    else
    {
    	cout << "false";
    }

    return 0;
}

출력

true

참고 자료

https://cplusplus.com/reference/map/map/find/
https://www.delftstack.com/ko/howto/cpp/map-find-in-cpp/

profile
정리와 기록

0개의 댓글