std::map 查询某个key对应的值,请用c++实现
时间: 2023-12-21 08:05:23 浏览: 153
C++ map 根据value找key的实现
可以使用 `std::map` 中的 `find` 函数来查询某个 key 对应的值。示例代码如下:
```c++
#include <iostream>
#include <map>
int main() {
std::map<std::string, int> myMap;
myMap["apple"] = 10;
myMap["banana"] = 20;
myMap["cherry"] = 30;
// 查询 key 为 "banana" 的值
auto it = myMap.find("banana");
if (it != myMap.end()) {
std::cout << "The value of banana is: " << it->second << std::endl;
} else {
std::cout << "banana is not in the map." << std::endl;
}
// 查询不存在的 key
it = myMap.find("durian");
if (it != myMap.end()) {
std::cout << "The value of durian is: " << it->second << std::endl;
} else {
std::cout << "durian is not in the map." << std::endl;
}
return 0;
}
```
输出:
```
The value of banana is: 20
durian is not in the map.
```
阅读全文