C++ STL 中的 Multimap 与 Map 示例
C++ STL 中的映射
Map 以排序的方式存储唯一的键值对。每个键都与一个值唯一关联,该值可能是唯一的,也可能不是唯一的。可以从映射中插入或删除键,但不能修改。可以更改分配给键的值。这是使用键快速访问值的好方法,并且在 O(1) 时间内完成。
C++
#include
#include
#include
C++
#include
#include
#include
The map gquiz1 is :
KEY ELEMENT
1 40
2 30
3 60
4 20
5 50
6 50
7 10
The map gquiz2 after assign from gquiz1 is :
KEY ELEMENT
1 40
2 30
3 60
4 20
5 50
6 50
7 10
gquiz2 after removal of elements less than key=3 :
KEY ELEMENT
3 60
4 20
5 50
6 50
7 10
gquiz2.erase(4) : 1 removed
KEY ELEMENT
3 60
5 50
6 50
7 10
gquiz1.lower_bound(5) : KEY = 5 ELEMENT = 50
gquiz1.upper_bound(5) : KEY = 6 ELEMENT = 50
C++ STL 中的多重映射
Multimap 与 map 类似,只是多个元素可以有相同的键。此外,在这种情况下,键值和映射值对不必是唯一的。关于 multimap 需要注意的一件重要事情是 multimap 始终保持所有键的排序顺序。 multimap 的这些特性使其在竞争性编程中非常有用。
C++
#include
#include
#include
The multimap gquiz1 is :
KEY ELEMENT
1 40
2 30
3 60
6 50
6 10
The multimap gquiz1 after adding extra elements is :
KEY ELEMENT
1 40
2 30
3 60
4 50
5 10
6 50
6 10
The multimap gquiz2 after assign from gquiz1 is :
KEY ELEMENT
1 40
2 30
3 60
4 50
5 10
6 50
6 10
gquiz2 after removal of elements less than key=3 :
KEY ELEMENT
3 60
4 50
5 10
6 50
6 10
gquiz2.erase(4) : 1 removed
KEY ELEMENT
3 60
5 10
6 50
6 10
gquiz1.lower_bound(5) : KEY = 5 ELEMENT = 10
gquiz1.upper_bound(5) : KEY = 6 ELEMENT = 50
C++ STL中Map和Multimap的区别S No. Map Multimap 1 It stores unique key-value pair where each key is unique. It can store duplicate key-value pair where keys may not be unique. 2 Using count() function on a map can only return two values which is either 0 or 1. Using count() function on a multimap can return any non-negative integer. 3 Accessing Value of any key is easy and directly accessible. Accessing value of any key is not easy and is not directly accessible. 4 Deleting in a map using key will delete only one key-value pair. Deleting in a multimap using key will delete all the key-value pair having same key. 5 Map can be used when a simple look up table having unique key-value pairs is required for quickly accessing to the value using the key. Multimap can be used when grouping of values together using the keys are required.