乐闻世界logo
搜索文章和话题

How to find if a given key exists in a std:: map

4 个月前提问
3 个月前修改
浏览次数21

1个答案

1

在C++中,std::map 是一个基于红黑树的有序关联容器,它存储了键值对,并且可以通过键来快速检索值。要查找 std::map 中是否存在给定的key值,可以使用几种方法,主要有以下几种:

方法1: 使用 find 方法

std::map 类提供了 find 方法,它接收一个键作为参数,并返回一个迭代器。如果找到该键,迭代器指向包含该键的元素;如果未找到,则迭代器等于 end() 方法返回的迭代器。

示例代码:

cpp
#include <iostream> #include <map> int main() { std::map<int, std::string> map; map[1] = "apple"; map[2] = "banana"; map[3] = "cherry"; int key = 2; auto it = map.find(key); if (it != map.end()) { std::cout << "找到键 " << key << ",其对应的值为 " << it->second << std::endl; } else { std::cout << "未找到键 " << key << std::endl; } return 0; }

在这个例子中,我们检查键 2 是否存在于map中,并成功找到并打印出对应的值 "banana"。

方法2: 使用 count 方法

std::map 同样提供了 count 方法,该方法返回具有指定键的元素的数量。对于 std::map,这个数量只能是 01,因为键是唯一的。

示例代码:

cpp
#include <iostream> #include <map> int main() { std::map<int, std::string> map; map[1] = "apple"; map[2] = "banana"; map[3] = "cherry"; int key = 4; if (map.count(key) > 0) { std::cout << "键 " << key << " 存在于map中。" << std::endl; } else { std::cout << "键 " << key << " 不存在于map中。" << std::endl; } return 0; }

在这个例子中,我们尝试找到键 4,但因为它不存在,所以输出表明该键不在map中。

方法3: 使用 contains 方法(C++20及以后版本)

从C++20开始,std::map 引入了 contains 方法,可以直接检查键是否存在,返回 truefalse

示例代码(需要C++20支持):

cpp
#include <iostream> #include <map> int main() { std::map<int, std::string> map; map[1] = "apple"; map[2] = "banana"; map[3] = "cherry"; int key = 3; if (map.contains(key)) { std::cout << "键 " << key << " 存在于map中。" << std::endl; } else { std::cout << "键 " << key << " 不存在于map中。" << std::endl; } return 0; }

在这个例子中,我们检查键 3 是否存在,由于它存在,输出正确显示键存在于map中。

总结来说,根据使用的C++版本和个人偏好,可以选择合适的方法来判断 std::map 中是否存在特定的键。

2024年6月29日 12:07 回复

你的答案