C++의 맵에 키가 있는지 확인
이 게시물에서는 C++의 맵에 키가 있는지 확인하는 방법에 대해 설명합니다.
1. 사용 std::map::find
표준 사용 방법 std::map::find
맵에서 키를 검색하고 이터레이터를 반환하는 함수 또는 std::map::end
키가 맵에 없는 경우. 다음 코드 예제는 이 함수에 대한 호출을 보여줍니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <string> #include <map> int main() { std::map<std::string, int> map = { {"one", 1}, {"two", 2}, {"three", 3} }; std::string key = "two"; if (map.find(key) != map.end()) { std::cout << "Key found" << std::endl; } else { std::cout << "Key not found" << std::endl; } return 0; } |
결과:
Key found
2. 사용 std::map::count
또 다른 옵션은 std::map::count
특정 키가 있는 맵의 총 요소 수를 가져옵니다. 키가 맵에 있는 경우 맵 컨테이너의 모든 키가 고유하므로 개수는 정확히 1이 됩니다. 키를 찾을 수 없으면 count 함수는 0을 반환합니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <string> #include <map> int main() { std::map<std::string, int> map = { {"one", 1}, {"two", 2}, {"three", 3} }; std::string key = "two"; if (map.count(key) != 0) { std::cout << "Key found" << std::endl; } else { std::cout << "Key not found" << std::endl; } return 0; } |
결과:
Key found
3. 사용 std::map::contains
맵에 특정 키가 있는지 확인하는 또 다른 옵션은 std::map::contains
멤버 함수. 이 기능은 C++20부터 사용할 수 있습니다. 그것은 반환 true
맵에 특정 키가 있는 요소가 포함된 경우 false
그렇지 않으면.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <string> #include <map> int main() { std::map<std::string, int> map = { {"one", 1}, {"two", 2}, {"three", 3} }; std::string key = "two"; if (map.contains(key)) { std::cout << "Key found" << std::endl; } else { std::cout << "Key not found" << std::endl; } return 0; } |
결과:
Key found
C++의 맵에 키가 있는지 확인하는 것이 전부입니다.