C++的set与map 📅 发布时间:2026/8/27 9:45:49 👁 浏览次数: 这是我第一次发文章……毕竟是一个学生如果有问题请及时提出QwQ前言std::map和std::set内部都基于红黑树实现会自动排序当然你也可以用set或者map代替vector/数组sort。使用map应包含#include map定义方式容器类型 数据类型 容器名;mapstring,intmp;插入1.下标插入容器名[键] 值;mp[Li Hua]12;2.insert():(1). make_pair容器名.insert(make_pair(键, 值));mp.insert(make_pair(Xiao Ming,20));(2).C11及以后insert({键, 值})mp.insert({Li Ming,15});元素访问1.下标访问容器名[键]coutmp[Xiao Ming];Tips: 如果所给键不存在于当前容器将自动创建2.at()访问coutmp.at(Li Hua);查找find(键)autoitmp.find(Xiao Ming);if(it!mp.end())coutit.first it.second;elsecoutNot Found.;删除erase()1.按照key删除mp.erase(Xiao Ming);2.按照迭代器删除autoitmp.find(Xiao Ming);mp.erase(it);按照区间删除mp.erase(mp.begin(),mp.end());遍历C11及以后for(autoi:mp){couti.first i.second\n;}以上for循环会先将整个map容器复制到另一块内存中再进行遍历。或者for(autoi:mp){couti.first i.second\n;}以上for循环会直接遍历map原容器速度会更快。判断是否存在count(键)boolflag1 mp.count(Tian Tian);存在返回true否则返回false元素个数获取size()coutmp.size();判断是否为空empty()boolflag2 mp.empty();二分查找1.lower_bound()autoitmp.lower_bound(x);2.upper_bound()autoitmp.upper_bound(x);使用set应包含#include set定义方式容器类型 数据类型 容器名;setintst;setint,greaterints2;// 降序插入insert()1.单个值插入autot1st.insert(10);2.批量插入st.insert({1,3,5,8,11});容器的遍历for(autoi:st)couti ;查找1.find()if(st.find(9)!st.end())coutFound;2.count()if(st.count(8))coutFound;删除erase()1.按照指定值删除st.erase(11);2.按照迭代器删除autoitst.find(1);st.erase(it);3.按照区间删除st.erase(st.begin(),st.end());元素个数获取size()coutst.size();判断是否为空empty()boolflag2 st.empty();清空整个容器clear()st.clear();二分查找1.lower_bound()lower_bound(x)用于寻找第一个小于x的数的位置时间复杂度O(log n)autoitst.lower_bound(x);2.upper_bound()upper_bound(x)用于寻找第一个大于x的数的位置时间复杂度O(log n)autoitst.upper_bound(x);附加也用了指针顺便提一下1.string获取首位字符string shello world!;couts[0]\n;cout*s.begin()\n;couts.front()\n;2.string获取末尾字符string shello world!;couts[s.size()-1]\n;cout*(--s.end())\n;couts.back()\n;本系列的其他文章传送门1传送门2Copyright Matthew