四个stl容器的底层都是使用红黑树实现的(平衡二叉搜索树的一种,后续博主会更新),set是key类型的,map是key-value类型.由于底层是由二叉搜索树(前一篇有介绍)写的,所以查找效率很高为logN。

set:

下面介绍一下set的几个重要接口和用法

插入函数insert(),如:s.insert(5);

遍历:迭代器遍历例如:auto it = s.begin();
while (it != s.end()) {
cout << *it << " ";
it++;
}

查找find()注意:find方法使用中序遍历

删除:s.erase() 1.直接删除s.erase(x); 例如:int num = s.erase(x);
if (num == 0) cout << "删除不成功" << endl;
else cout << "删除不成功" << endl; 2.使用find方法 auto apos = s.find(x);
if (apos != s.end()) {
s.erase(x);
}

clear:清除所有元素
cout:返回值的个数
lower_bound返回大于等于val位置的迭代器
upper_bound返回大于val位置的迭代器
通常用于删除区间
[30,50]

例:s.insert({ 30,34,30,50,55,65,65 });
auto itlow = s.lower_bound(30);
auto itupper = s.upper_bound(50);
s.erase(itlow, itupper);//左闭右开,按搜索树的规则找
for (auto e : s) {
cout << e << " ";
}删除[30,50]之间的数

greater:按照降序排列 例:set>s;

mutiset:mutiset是多重映射的意思,里面可以存在相同的值,函数也基本相同,博主这里只介绍差异 find函数multiset查找的中序遍历中的第一个(一直向左子树查找,找到最底层的第一个)
erase函数会删除所有值

map、mutimap

map里面是一个键值对(pair),他和set相似,博主这里也只介绍差异

遍历 map::iterator it auto it = dict.begin(); while (it != dict.end()) { cout << (*it).first << " " << (*it).second << endl; cout << it->first << " " << it->second << endl; cout << it.operator->()->first << " " << it.operator->()->second << endl;//itr.operator->()返回的是指向pair的指针 it++; }//second可以修改,key不能修改 return 0;

}insert函数:map的插入有很多种方法:如: mapdict;
1.pairkv1(“frist”, “第一个”);
2.dict.insert(kv1);
3.dict.insert(pair(“second”, “第二个”));
4.dict.insert(make_pair(“sort”, “排序”));
dict.insert({ “sort”,”排序!!!!” });//不会更新
注意插入已有key并不会更新value的值、

遍历 :
map::iterator it
auto it = dict.begin();
while (it != dict.end()) {
    cout << (*it).first << " " << (*it).second << endl;
    cout << it->first << " " << it->second << endl;
    cout << it.operator->()->first << " " << it.operator->()->second << endl;//itr.operator->()返回的是指向pair的指针
    it++;
}//second可以修改,key不能修改
return 0;}遍历有三种方法大家按照习惯使用

multimap和map的差异:operator[]的使用 []的使用:统计次数返回对应的value(可修改)
它存在 插入,查找,修改 3个功能

map和mutimap的区别 mutmap不能使用[],可也插入value值相同的函数

今天的更新到这了,如有不对的地方,联系 博主修改