std::map

映射和多重映射基于某一类型Key的键集的存在,提供对T类型的数据进行快速和高效的检索。

对map而言,键只是指存储在容器中的某一成员。

Map不支持副本键,multimap支持副本键。

Map和multimap对象包涵了键和各个键有关的值,键和值的数据类型是不相同的,这与set不同。set中的key和value是Key类型的,而map中的key和value是一个pair结构中的两个分量。


使用map得包含map类所在的头文件:


#include <map> //注意, STL头文件没有扩展名.h 


map的构造:

Template<class T1, class T2>
map(); // 默认构造函数
map(const map& m) // 拷贝构造函数
map(iterator begin, iterator end ); //区间构造函数
map(iterator begin, iterator end, const traits& _compare) //带比较谓词的构造函数
map(iterator begin, iterator end, const traits& _compare, const allocator& all) //带分配器


map的基本定义:
map对象是模板类,需要关键字和存储对象两个模板参数:

std:map<int, string> personnel;

这样就定义了一个用int作为索引,并拥有相关联的指向string的指针。

为了使用方便,可以对模板类进行一下类型定义:

typedef map<int, CString> UDT_MAP_INT_CSTRING;
UDT_MAP_INT_CSTRING enumMap; 


map的嵌套定义:

map<sring,map<string,long> > //注意:最后两个>之间有个空格

map支持下标运算符operator[],用访问普通数组的方式来访问map;不过下标为map的键,在multimap中一个键可以对应多个不同的值。

map的基本用法:

插入、查找、删除、遍历等等

如何实现双键map(可以扩展到多键):

1) 只有两个键都匹配才命中目标;

2) 两个键中任意一个匹配就命中目标。


map的特点:

1) map将Key的object和T的Object绑定到一起, 因此是一种Pair Associative Container,  表示其value type为pair. 

2) 它同时也是Unique Associative Container,表示没有两个元素具有相同的Key. 

3) 它还是一种Sorted Associative Container,因此第三个参数只能是less, greater之类的functor,相比较而言,hash table是 equal_to、not_equal_to之类的functor。


参考:

百度百科:STL map


要向`std::map<std::string,std::map<std::string,std::string>>`类型的`my_map`中插入数据,可以按照以下步骤进行操作: 1. 创建要插入的数据项,包括外层`std::string`类型的键和内层`std::map<std::string,std::string>`类型的值。例如,假设要插入的数据项为`key1 -> (inner_key1 -> value1, inner_key2 -> value2)`。 2. 使用`my_map[key1]`来访问外层`std::map`中的键`key1`对应的值,如果该键不存在,则会自动创建一个新的内层`std::map`。 3. 使用内层`std::map`的插入函数,例如`my_map[key1].insert(std::make_pair(inner_key1, value1))`,将内层键值对`(inner_key1, value1)`插入到对应的内层`std::map`中。 4. 重复上述步骤,插入其他内层键值对。 下面是一个示例代码,演示了如何向`my_map`中插入数据: ```cpp #include <iostream> #include <map> #include <string> int main() { std::map<std::string, std::map<std::string, std::string>> my_map; // 创建要插入的数据项 std::string key1 = "key1"; std::string inner_key1 = "inner_key1"; std::string value1 = "value1"; std::string inner_key2 = "inner_key2"; std::string value2 = "value2"; // 插入数据项 my_map[key1].insert(std::make_pair(inner_key1, value1)); my_map[key1].insert(std::make_pair(inner_key2, value2)); // 输出结果 for (const auto& outer_pair : my_map) { std::cout << outer_pair.first << " -> "; for (const auto& inner_pair : outer_pair.second) { std::cout << "(" << inner_pair.first << " -> " << inner_pair.second << ") "; } std::cout << std::endl; } return 0; } ``` 输出结果为: ``` key1 -> (inner_key1 -> value1) (inner_key2 -> value2) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值