C++中查找std::map键值有四种方法:1. operator[]直接访问,但会插入不存在的key;2. find()返回迭代器,安全且不修改map;3. at()提供异常安全访问;4. count()判断key是否存在。

在C++中,std::map 是一个关联容器,用于存储键值对(key-value pairs),并且按键(key)自动排序。要根据 key 查找对应的 value,有几种常用方法,每种方式适用不同场景。
如果 key 存在,返回对应的 value;如果 key 不存在,会自动插入该 key,并用默认值初始化 value(例如 int 默认为 0)。
注意:这种方式可能无意中修改 map 内容。示例:
#include <map>
#include <iostream>
int main() {
std::map<std::string, int> ageMap;
ageMap["Alice"] = 25;
ageMap["Bob"] = 30;
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">std::cout << "Alice's age: " << ageMap["Alice"] << std::endl; // 输出 25
std::cout << "Charlie's age: " << ageMap["Charlie"] << std::endl; // 插入 Charlie,默认值 0
return 0;}
如果找到,返回指向键值对的迭代器;否则返回 map.end()。
立即学习“C++免费学习笔记(深入)”;
推荐用于只读查找,不会修改 map。示例:
#include <map>
#include <iostream>
int main() {
std::map<std::string, int> ageMap;
ageMap["Alice"] = 25;
ageMap["Bob"] = 30;
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">auto it = ageMap.find("Alice");
if (it != ageMap.end()) {
std::cout << "Found: " << it->first << " - " << it->second << std::endl;
} else {
std::cout << "Key not found." << std::endl;
}
return 0;}
如果 key 不存在,会抛出 std::out_of_range 异常。
适合需要安全访问且确定 key 存在的场景。示例:
#include <map>
#include <iostream>
#include <stdexcept>
int main() {
std::map<std::string, int> ageMap;
ageMap["Alice"] = 25;
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">try {
std::cout << "Alice's age: " << ageMap.at("Alice") << std::endl;
std::cout << "Charlie's age: " << ageMap.at("Charlie") << std::endl; // 抛异常
} catch (const std::out_of_range& e) {
std::cout << "Key not found: " << e.what() << std::endl;
}
return 0;}
可用于判断 key 是否存在,再决定是否访问。
示例:
if (ageMap.count("Alice")) {
std::cout << "Value: " << ageMap["Alice"] << std::endl;
}
基本上就这些。日常使用中,find() 最安全,operator[] 最方便但小心副作用,at() 提供异常保护。按需选择即可。
以上就是c++++ map如何根据key查找value_c++ map按key查找方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号