定义于头文件
template< class Key, class T, class Compare = std::less, class Allocator = std::allocator > > class map; |
(1) |
|
namespace pmr { template > using map = std::map std::pmr::polymorphic_allocator>> } |
(2) |
(C++17 起) |
std::map
是有序键值对容器,它的元素的键是唯一的。用比较函数 Compare
排序键。搜索、移除和插入操作拥有对数复杂度。 map 通常实现为红黑树。
在每个标准库使用比较 (Compare) 概念的位置,以等价关系检验唯一性。不精确而言,若二个对象 a
与 b
互相比较不小于对方 : !comp(a, b) && !comp(b, a)
,则认为它们等价(非唯一)。
std::map
满足容器 (Container) 、具分配器容器 (AllocatorAwareContainer) 、关联容器 (AssociativeContainer) 和可逆容器 (ReversibleContainer) 的要求。
容量
检查容器是否为空
std::map::empty
bool empty() const; |
|
(C++11 前) |
bool empty() const noexcept; |
|
(C++11 起) (C++20 前) |
[[nodiscard]] bool empty() const noexcept; |
|
(C++20 起) |
检查容器是否无元素,即是否 begin() == end() 。
参数
(无)
返回值
若容器为空则为 true ,否则为 false
复杂度
常数。
返回容纳的元素数
std::map::size
size_type size() const; |
|
(C++11 前) |
size_type size() const noexcept; |
|
(C++11 起) |
返回容器中的元素数,即 std::distance(begin(), end()) 。
参数
(无)
返回值
容器中的元素数量。
复杂度
常数。
返回可容纳的最大元素数
std::map::max_size
size_type max_size() const; |
|
(C++11 前) |
size_type max_size() const noexcept; |
|
(C++11 起) |
返回根据系统或库实现限制的容器可保有的元素最大数量,即对于最大容器的 std::distance(begin(), end()) 。
参数
(无)
返回值
元素数量的最大值。
复杂度
常数。
注意
此值通常反映容器大小上的理论极限,至多为 std::numeric_limits::max() 。运行时,可用 RAM 总量可能会限制容器大小到小于 max_size()
的值。
调用示例
#include
#include
#include
#include
#include
#include
#include
输出