std::map基于红黑树实现,支持自动排序,常用插入方法有insert、下标[]和emplace,查找可用find、count、at等,注意下标可能意外插入元素。

在C++中,std::map 是一个关联容器,用于存储键值对(key-value pairs),并按照键的顺序自动排序。它基于红黑树实现,插入和查找的时间复杂度为 O(log n)。下面介绍 map 的常见插入与查找方法。
插入元素
向 map 中插入元素有多种方式,常用的方法包括:
-
使用 insert() 方法:可以传入一个 pair 或使用 make_pair。
map<int, string> m;
m.insert({1, "apple"});
m.insert(make_pair(2, "banana"));
m.insert(pair<int, string>(3, "cherry"));
-
使用下标操作符 [ ]:通过键直接赋值。如果键不存在,会自动创建并插入;若存在,则更新其值。
m[4] = "date";
m[1] = "apricot"; // 修改键为1的值
-
使用 emplace() 方法:原地构造元素,效率更高,适合复杂对象。
m.emplace(5, "elderberry");
查找元素
查找 map 中的元素有几种常用方式,根据需求选择合适的方法:
-
使用 find() 方法:返回指向元素的迭代器,若未找到则返回 end()。适合判断是否存在某个键。
auto it = m.find(2);
if (it != m.end()) {
cout << "Found: " << it->second;
}
-
使用 count() 方法:返回键存在的个数(map 中最多1个),可用于判断是否存在。
if (m.count(3)) {
cout << "Key 3 exists";
}
-
使用下标操作符 [ ] 和 at():
- [ ] 会自动插入默认值(如果键不存在),可能改变 map 内容。
- at() 在键不存在时抛出 std::out_of_range 异常,更安全。
try {
cout << m.at(1);
} catch (const out_of_range& e) {
cout << "Key not found";
}
完整示例代码
#include <iostream>
#include <map>
using namespace std;
int main() {
map<int, string> m;
// 插入元素
m[1] = "apple";
m.insert({2, "banana"});
m.emplace(3, "cherry");
// 查找元素
auto it = m.find(2);
if (it != m.end()) {
cout << "Key: " << it->first << ", Value: " << it->second << endl;
}
// 使用 at()
cout << "Value of key 1: " << m.at(1) << endl;
return 0;
}
基本上就这些。掌握 insert、find、[ ] 和 emplace 等方法,就能高效使用 map 进行数据存储与检索。注意避免误用 [ ] 导致意外插入。
立即学习“C++免费学习笔记(深入)”;
以上就是c++++中map如何插入和查找元素_c++ map插入与查找元素用法的详细内容,更多请关注php中文网其它相关文章!