std::map 的插入元素方式
开发中遇到的问题
- @[TOC](开发中遇到的问题)
- 1. insert() 方法(最常用)
- 2. 使用下标 [] 操作符
- 3.emplace() 方法(C++11 起,推荐用于性能优化)
- 4.范围插入(插入另一个容器的多个元素)
- 5. 使用初始化列表(C++11 起)
- 总结
开发中遇到的问题
- @[TOC](开发中遇到的问题)
- 1. insert() 方法(最常用)
- 2. 使用下标 [] 操作符
- 3.emplace() 方法(C++11 起,推荐用于性能优化)
- 4.范围插入(插入另一个容器的多个元素)
- 5. 使用初始化列表(C++11 起)
- 总结
在 C++ 中,std::map 是一个关联容器,用于存储键值对(key-value pairs),并根据键自动排序(默认按升序)
1. insert() 方法(最常用)
使用 std::pair
#include <iostream>
#include <map>
#include <string>
std::map<std::string, int> studentScores;// 插入元素
studentScores.insert(std::pair<std::string, int>("Alice", 85));
studentScores.insert(std::pair<std::string, int>("Bob", 90));
使用 make_pair
studentScores.insert(std::make_pair("Charlie", 95));
使用 std::map::value_type
studentScores.insert(std::map<std::string, int>::value_type("David", 88));
使用花括号 {}(C++11 起推荐)
studentScores.insert({"Eve", 92});
返回值
insert() 返回一个 std::pair<iterator, bool>:
bool:表示是否插入成功(true = 新插入,false = 键已存在)
2. 使用下标 [] 操作符
studentScores["Alice"] = 85;
studentScores["Bob"] = 90;
/*如果键 不存在,会自动创建并插入。如果键 已存在,会覆盖原来的值。使用 [] 时,如果键不存在,会用默认构造函数创建一个值(例如 int 会被初始化为 0)。
*/
3.emplace() 方法(C++11 起,推荐用于性能优化)
emplace 直接在容器内部构造元素,避免了临时对象的创建,效率更高。
studentScores.emplace("Frank", 87); // 参数是构造 value_type 所需的参数
4.范围插入(插入另一个容器的多个元素)
std::map<std::string, int> otherMap = {{"Grace", 94}, {"Henry", 89}};
studentScores.insert(otherMap.begin(), otherMap.end());
5. 使用初始化列表(C++11 起)
std::map<std::string, int> studentScores = {{"Alice", 85},{"Bob", 90},{"Charlie", 95}
};
总结
想安全插入(不覆盖):用insert({"key", value})
想赋值或更新:用 map["key"] = value
追求性能:用 emplace("key", value)
以上的话就是本文的全部内容,如果有什么错误或者建议请指正,感谢!共同进步!