在C++98中,STL提供了底层为红黑树结构的一系列关联式容器,在查询时效率可达到
l
o
g
2
N
log_2 N
l o g 2 N ,即最差情况下需要比较红黑树的高度次,当树中的节点非常多时,查询效率也不理想。最好的查询是,进行很少的比较次数就能够将元素找到,因此在C++11中,STL又提供了4个unordered系列的关联式容器,这四个容器与红黑树结构的关联式容器使用方式基本类似,只是其底层结构不同,本文中对 unordered_map 和 unordered_set 进行介绍。
一、 unordered_set
1.1 unordered_set 的构造函数
1.2 unordered_set 的容量
函数声明 功能介绍 bool empty() const noexcept; 检测unordered_set 是否为空 size_type size() const noexcept; 返回unordered_set 中有效元素的个数
1.3 unordered_set 的迭代器
函数声明 功能介绍 begin 返回unordered_set第一个元素的迭代器 end 返回unordered_set最后一个元素下一个位置的迭代器 cbegin 返回unordered_set第一个元素的const迭代器 cend 返回unordered_set最后一个元素下一个位置的const迭代器
1.4 unordered_set 的元素查询
函数声明 功能介绍 iterator find ( const key_type& k ); 返回key在哈希桶中的位置 size_type count ( const key_type& k ) const; 返回哈希桶中关键码为key的键值对的个数
1.5 unordered_set 的修改操作
函数声明 功能介绍 insert 向容器中插入键值对 erase 删除容器中的键值对 void clear() noexcept; 清空容器中有效元素个数 void swap ( unordered_set& ust ); 交换两个容器中的元素
1.6 unordered_set 的桶操作
函数声明 功能介绍 size_type bucket_count() const noexcept; 返回哈希桶中桶的个数 size_type bucket_size ( size_type n ) const; 返回n号桶中有效元素的总个数 size_type bucket ( const key_type& k ) const; 返回元素key所在桶的编号
二、 unordered_map
2.1 unordered_map 的构造函数
2.2 unordered_map 的容量
函数声明 功能介绍 bool empty() const noexcept; 检测unordered_map 是否为空 size_type size() const noexcept; 返回unordered_map 中有效元素的个数
2.3 unordered_map 的迭代器
函数声明 功能介绍 begin 返回unordered_map第一个元素的迭代器 end 返回unordered_map最后一个元素下一个位置的迭代器 cbegin 返回unordered_map第一个元素的const迭代器 cend 返回unordered_map最后一个元素下一个位置的const迭代器
2.4 unordered_map 的元素访问
函数声明 功能介绍 [ ] 返回与key对应的value,没有一个默认值
2.5 unordered_map 的元素查询
函数声明 功能介绍 iterator find ( const key_type& k ); 返回key在哈希桶中的位置 size_type count ( const key_type& k ) const; 返回哈希桶中关键码为key的键值对的个数
2.6 unordered_map 的修改操作
函数声明 功能介绍 insert 向容器中插入键值对 erase 删除容器中的键值对 void clear() noexcept; 清空容器中有效元素个数 void swap ( unordered_map& ump ); 交换两个容器中的元素
2.7 unordered_map 的桶操作
函数声明 功能介绍 size_type bucket_count() const noexcept; 返回哈希桶中桶的个数 size_type bucket_size ( size_type n ) const; 返回n号桶中有效元素的总个数 size_type bucket ( const key_type& k ) const; 返回元素key所在桶的编号