The multimap Type

本文介绍了C++标准库中多映射(multimap)的概念及使用方法。多映射允许键值对应多个元素,适合存储一个键对应多个值的情况。文章通过示例展示了如何插入、查找及删除元素,并对比了find、equal_range等方法的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

As we know, both map and set can contain only a single instance of each key . The type multimap allow multiple instances of a key (1:n). In a phone directory, for example, some might wish to provide a separate listing for each phone number associated with an individual. The multimap type is defined in the same headers as the corresponding single-element versions: the map header .

 

[Note]

[1] The operations supported by multimap are the same as those on map, with one exception : multimap does not support subscripting . We cannot subscript a multimap because there may be more than one value associated with a given key.

 

[2] Because keys need not be unique, insert always adds an element .

 

[3] Finding elements in a multimap , we should note that maps store their elements in order, the multimap type does so as well . As a result, when a multimap has multiple instances of a given key, those instances will be adjacent elements within the container . It turns out that there are three strategies we might use to find and print all the elements by a given key. Each of these strategies relies on the face that we know that all the entries for a given key will be adjacent within the multimap . The strategies are as following.

(1) using find and count

(2) using lower_bound and upper_bound

(3) using equal_range (the best way )

 

[An example of multimap]

output:


[The usage of find and equal_range ]

[1]

typedef multimap<type,type>::iterator itType;

itType iter=m.find(key);

 

[2]

typedef multimap<type,type>::iterator itType;

pair<itType,itType> pos=m.equal_range(key);

output:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值