C++でmapを使用して、キーが存在するかどうかを検索する方法は?
C++では、mapのcount()関数やfind()関数を使用して、keyの存在を確認することができます。
count()関数を使用する:
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> myMap;
myMap[1] = "one";
myMap[2] = "two";
myMap[3] = "three";
if (myMap.count(2) > 0) {
std::cout << "Key 2 exists in the map" << std::endl;
}
else {
std::cout << "Key 2 does not exist in the map" << std::endl;
}
return 0;
}
find()メソッドを使用する:
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> myMap;
myMap[1] = "one";
myMap[2] = "two";
myMap[3] = "three";
if (myMap.find(2) != myMap.end()) {
std::cout << "Key 2 exists in the map" << std::endl;
}
else {
std::cout << "Key 2 does not exist in the map" << std::endl;
}
return 0;
}
上記の2つの方法は、マップ内にキーが存在するかを判断することができます。 count()関数は、マップ内でキーが現れる回数を返し、find()関数は、キーが存在する位置を指すイテレータを返します。find()関数が返すイテレータがmap.end()と等しい場合、キーはマップ内に存在しないことを示します。