关联式容器
map和set是关联性容器,不像vector,list,deque,forward_list是序列式容器。
序列式容器底层是线性序列的数据结构,里边存储的是元素本身。关联式容器也是用来存储数据的,只不过它存储的是<key,value>结构的键值对,在检索时效率更高。
键值对
用来表示一一对应的一种结构,该结构一般只包含两个成员变量key和value,key代表键值,value表示与key对应的信息。
树状结构的关联式容器
STL总共实现了两种不同结构的管理式容器:树型结构与哈希结构。树型结构的关联式容器主要有四种:map、set、multimap、multiset。
set
1.底层是二叉搜索树
2.set的键值对实际是<value,value>
3.set中value是唯一的
4.容器中不允许修改,因为元素总是const常量,但可以插入或删除
set的接口使用
std::set<int> first; // empty set of ints int myints[]= {10,20,30,40,50};
//利用数组 std::set<int> second (myints,myints+5); // range std::set<int> third
(second); // a copy of second std::set<int> fourth (second.begin(),
second.end()); // iterator ctor. std::set<int,classcomp> fifth; // class as
Compare
map
1.底层通常为平衡二叉搜索树
2.支持 [] 下标访问
3.按照特定次序储存元素
map() //构造一个空的map begin()和end() //begin:首元素的位置,end最后一个元素的下一个位置 cbegin()和cend()
//与begin和end意义相同,但cbegin和cend所指向的元素不能修改 rbegin()和rend()
//反向迭代器,rbegin在end位置,rend在begin位置,其++和--操作与begin和end操作移动相反 crbegin()和crend()
//与rbegin和rend位置相同,操作相同,但crbegin和crend所指向的元素不能修改 bool empty ( ) const
//检测map中的元素是否为空,是返回true,否则返回false size_type size() const //返回map中有效元素的个数
mapped_type& operator[] (const key_type& k) //返回去key对应的value
pair<iterator,bool> insert (const value_type& x )
//在map中插入键值对x,注意x是一个键值对,返回值也是键值对:iterator代表新插入元素的位置,bool代表释放插入成功 void erase (
iterator position ) //删除position位置上的元素 size_type erase ( const key_type& x )
//删除键值为x的元素 void erase ( iterator first,iterator last ) //删除[first, last)区间中的元素
void swap (map<Key,T,Compare,Allocator>&mp ) //交换两个map中的元素 void clear ( )
//将map中的元素清空 iterator find ( const key_type& x)
//在map中插入key为x的元素,找到返回该元素的位置的迭代器,否则返回end const_iterator find ( const key_type&
x ) const //在map中插入key为x的元素,找到返回该元素的位置的const迭代器,否则返回cend size_type count (
const key_type& x ) const
//返回key为x的键值在map中的个数,注意map中key是唯一的,因此该函数的返回值要么为0,要么为1,因此也可以用该函数来检测一个key是否在map中
今日推荐