关联容器:map和set
map提供一对一的数据,key-value。map内部自建一颗红黑树,具有对数据自动排序的功能,map的所有数据都是有序的。
map的这种key-value类型,不过key只能在map中出现一次,也就是说键值是唯一的。
map内部实现是一颗红黑树。这棵树具有对数据的自动排序功能。
定义一个int类型的key和string类型的value,如下:
map<int, string> mp;
//用insert插入。
mp.insert(pair<int, string>(3, "boy"));
//数组插入
mp['key'] = value; //这种是最长用的方式
//查看
mp.find('key');
//删除和清空
mp.erase('key'); //成功返回1,否则返回0
//迭代器清空
mp.erase(mp.begin(), mp.end());//和mp.clear()类似
map:底层采用的是树型结构,多数使用平衡二叉树实现,查找某一值是常数时间,遍历起来效果也不错, 只是每次插入值的时候,会重新构成底层的平衡二叉树,效率有一定影响.
回头补充下map的底层实现。
set:
set作为一个容器也是用来存储同一数据类型的数据类型,并且能从一个数据集合中取出数据,在set中每个元素的值都唯一,而且系统能根据元素的值自动进行排序。应该注意的是set中数元素的值不能直接被改变。
常用方法:
begin(), 返回set容器的第一个元素
end() , 返回set容器的最后一个元素
clear(), 删除set容器中的所有的元素
empty() 判断set容器是否为空
max_size(),返回set容器可能包含的元素最大个数
size() , 返回当前set容器中的元素个数
rbegin, 返回的值和end()相同
rend(), 返回的值和rbegin()相同
#include <iostream>
#include <set>
using namespace std;
int main()
{
set<int> S;//声明
S.insert(1);
S.insert(2);
S.insert(3);
cout << "S size is:" << S.size() << endl;
cout << "S first:" << *S.begin() << endl;
cout << "S end:" << *S.end() << endl;
S.insert(2);
cout << "S size is:" << S.size() << endl;
set<int>::iterator it;
for(it = S.begin(); it != S.end(); ++it)
{
cout << *it << " " ;
}
cout << endl;
S.clear();
if(S.empty())
{
cout << "S is empty" << endl;
}
return 0;
}
result:
S size is:3
S first:1
S end:3
S size is:3 //从这里可以看出,当map中有2时,再插入将不起作用
1 2 3
S is empty