公司动态
【c++】map和set的使用
前言在上一期c中了解了二叉搜树。什么树是二叉搜索树在插入节点时应该如何插入又该如何查找节点在删除节点时又该注意什么以及key与key-value有什么区别应用在哪。在上期中都有提到。在这次分享中我介绍到了set和map他们是如何使用的以及有区别。序列式容器和关联式容器前⾯我们已经接触过STL中的部分容器如string、vector、list、deque、array、forward_list等这些容器统称为序列式容器因为逻辑结构为线性序列的数据结构两个位置存储的值之间⼀般没有紧密的关联关系⽐如交换⼀下他依旧是序列式容器。顺序容器中的元素是按他们在容器中的存储位置来顺序保存和访问的。关联式容器也是⽤来存储数据的与序列式容器不同的是关联式容器逻辑结构通常是⾮线性结构两个位置有紧密的关联关系交换⼀下他的存储结构就被破坏了。顺序容器中的元素是按关键字来保存和访问的。关联式容器有map/set系列和unordered_map/unordered_set系列。本章节讲解的map和set底层是红⿊树红⿊树是⼀颗平衡⼆叉搜索树。set是key搜索场景的结构map是key/value搜索场景的结构。set系列的使用set类的介绍1、set的声明如下T就是set底层关键字的类型2、set默认要求T⽀持⼩于⽐较如果不⽀持或者想按⾃⼰的需求⾛可以⾃⾏实现仿函数传给第⼆个模版参数3、set底层存储数据的内存是从空间配置器申请的如果需要可以⾃⼰实现内存池传给第三个参数。4、⼀般情况下我们都不需要传后两个模版参数。5、set底层是⽤红⿊树实现增删查效率是O(logN)迭代器遍历是⾛的搜索树的中序所以是有序的。6、前⾯部分我们已经学习了vector/list等容器的使⽤STL容器接⼝设计⾼度相似所以这⾥我们就不再⼀个接⼝⼀个接⼝的介绍⽽是直接带着⼤家看⽂档挑⽐较重要的接⼝进⾏介绍。template class T, // set::key_type/value_type class Compare lessT, // set::key_compare/value_compare class Alloc allocatorT // set::allocator_type class set;set的构造和迭代器set的构造我们关注以下⼏个接⼝即可。set的⽀持正向和反向迭代遍历遍历默认按升序顺序因为底层是⼆叉搜索树迭代器遍历⾛的中序⽀持迭代器就意味着⽀持范围forset的iterator和const_iterator都不⽀持迭代器修改数据修改关键字数据破坏了底层搜索树的结构。// 单个数据插⼊如果已经存在则插⼊失败 pairiterator,bool insert (const value_type val); // 列表插⼊已经在容器中存在的值不会插⼊ void insert (initializer_listvalue_type il); // 迭代器区间插⼊已经在容器中存在的值不会插⼊ template class InputIterator void insert (InputIterator first, InputIterator last); // 查找val返回val所在的迭代器没有找到返回end() iterator find (const value_type val); // 查找val返回Val的个数 size_type count (const value_type val) const; // 删除⼀个迭代器位置的值 iterator erase (const_iterator position); // 删除valval不存在返回0存在返回1 size_type erase (const value_type val); // 删除⼀段迭代器区间的值 iterator erase (const_iterator first, const_iterator last); // 返回⼤于等val位置的迭代器 iterator lower_bound (const value_type val) const; // 返回⼤于val位置的迭代器 iterator upper_bound (const value_type val)const;set的增删查// empty (1) ⽆参默认构造 explicit set (const key_compare comp key_compare(), const allocator_type alloc allocator_type()); // range (2) 迭代器区间构造 template class InputIterator set (InputIterator first, InputIterator last, const key_compare comp key_compare(), const allocator_type allocator_type()); // copy (3) 拷⻉构造 set (const set x); // initializer list (5) initializer 列表构造 set (initializer_listvalue_type il, const key_compare comp key_compare(), const allocator_type alloc allocator_type()); // 迭代器是⼀个双向迭代器 iterator - a bidirectional iterator to const value_type // 正向迭代器 iterator begin(); iterator end(); // 反向迭代器 reverse_iterator rbegin(); reverse_iterator rend();使用样例#includeiostream #includeset using namespace std; int main() { // 去重升序排序 //setint s; setint, greaterint s; s.insert(5); s.insert(2); s.insert(7); s.insert(5); s.insert(7); s.insert(3); //setint::iterator it s.begin(); auto it s.begin(); while (it ! s.end()) { // error C3892: “it”: 不能给常量赋值 //*it 1; cout *it ; it; } cout endl; s.insert({ 2,8,3,9,2 }); for (auto e : s) { cout e ; } cout endl; // void insert (initializer_listvalue_type il); setstring strset { sort, insert, add }; //setstring strset({ sort, insert, add }); // // 遍历string比较ascll码大小顺序遍历的 for (auto e : strset) { cout e ; } cout endl; return 0; } int main() { setint s { 4,2,7,2,8,5,9 }; for (auto e : s) { cout e ; } cout endl; // 删除最小值 s.erase(s.begin()); for (auto e : s) { cout e ; } cout endl; // 直接删除x int x; /*cin x; int num s.erase(x); if (num 0) { cout x 不存在 endl; } else { cout x 删除成功 endl; }*/ cin x; auto pos s.find(x); if (pos ! s.end()) { // pos失效 s.erase(pos); //cout *pos endl; } else { cout x 不存在 endl; } for (auto e : s) { cout e ; } cout endl; // 算法库的查找 O(N) auto pos1 find(s.begin(), s.end(), x); // set自身实现的查找 O(logN) auto pos2 s.find(x); // 利用count间接实现快速查找 cin x; if (s.count(x)) { cout x 在 endl; } else { cout x 不存在 endl; } return 0; } int main() { std::setint myset; for (int i 1; i 10; i) myset.insert(i * 10); // 10 20 30 40 50 60 70 80 90 for (auto e : myset) { cout e ; } cout endl; // [30, 50]值 // [25, 55]值 //// 返回 30 //auto itlow myset.lower_bound(30); //// 返回 50 //auto itup myset.upper_bound(50); // 返回 25 auto itlow myset.lower_bound(25); // 返回 55 auto itup myset.upper_bound(55); // 删除这段区间的值 myset.erase(itlow, itup); for (auto e : myset) { cout e ; } cout endl; }multiset和set的差异multiset和set的使⽤基本完全类似主要区别点在于multiset⽀持值冗余那么insert/find/count/erase都围绕着⽀持值冗余有所差异具体参看下⾯的样例代码理解。#includeiostream #includeset using namespace std; int main() { // 相⽐set不同的是multiset是排序但是不去重 multisetint s { 4,2,7,2,4,8,4,5,4,9 }; auto it s.begin(); while (it ! s.end()) { cout *it ; it; } cout endl; // 相⽐set不同的是x可能会存在多个find查找中序的第⼀个 int x; cin x; auto pos s.find(x); while (pos ! s.end() *pos x) { cout *pos ; pos; } cout endl; // 相⽐set不同的是count会返回x的实际个数 cout s.count(x) endl; // 相⽐set不同的是erase给值时会删除所有的x s.erase(x); for (auto e : s) { cout e ; } cout endl; return 0; }例题class Solution { public: vectorint intersection(vectorint nums1, vectorint nums2) { setints1(nums1.begin(), nums1.end()); setints2(nums2.begin(), nums2.end()); auto pos1 s1.begin(); auto pos2 s2.begin(); vectorintret; while (pos1 ! s1.end() pos2 ! s2.end()) { if (*pos1 *pos2) { pos1; } else if (*pos1 *pos2) { pos2; } else { ret.push_back(*pos1); pos1; pos2; } } return ret; } }解析看下图class Solution { public: ListNode* detectCycle(ListNode* head) { setListNode*s; ListNode* cur head; while (cur) { auto ret s.insert(cur); if (ret.second false) { return cur; } cur cur-next; } return nullptr; } };解析set的特点就是insert返回pair其中first是迭代器second是bool值并且不支持冗余。因此当bool为false时有重复值插入map系列的使用map类的介绍map的声明如下Key就是map底层关键字的类型T是map底层value的类型set默认要求Key⽀持⼩于⽐较如果不⽀持或者需要的话可以⾃⾏实现仿函数传给第⼆个模版参数map底层存储数据的内存是从空间配置器申请的。⼀般情况下我们都不需要传后两个模版参数。map底层是⽤红⿊树实现增删查改效率是 O(logN) 迭代器遍历是⾛的中序所以是按key有序顺序遍历的。template class Key, // map::key_type class T, // map::mapped_type class Compare lessKey, // map::key_compare class Alloc allocatorpairconst Key, T // map::allocator_type class map;pair类型的介绍map底层的红⿊树节点中的数据使⽤pairKey, T存储键值对数据。typedef pairconst Key, T value_type; template class T1, class T2 struct pair { typedef T1 first_type; typedef T2 second_type; T1 first; T2 second; pair() : first(T1()), second(T2()) { } pair(const T1 a, const T2 b) : first(a), second(b) { } templateclass U, class V pair(const pairU, V pr) : first(pr.first), second(pr.second) { } }; template class T1, class T2 inline pairT1, T2 make_pair(T1 x, T2 y) { return (pairT1, T2(x, y)); }map的构造map的构造我们关注以下⼏个接⼝即可。map的⽀持正向和反向迭代遍历遍历默认按key的升序顺序因为底层是⼆叉搜索树迭代器遍历⾛的中序⽀持迭代器就意味着⽀持范围formap⽀持修改value数据不⽀持修改key数据修改关键字数据破坏了底层搜索树的结构。// empty (1) ⽆参默认构造 explicit map(const key_compare comp key_compare(), const allocator_type alloc allocator_type()); // range (2) 迭代器区间构造 template class InputIterator map(InputIterator first, InputIterator last, const key_compare comp key_compare(), const allocator_type allocator_type()); // copy (3) 拷⻉构造 map(const map x); // initializer list (5) initializer 列表构造 map(initializer_listvalue_type il, const key_compare comp key_compare(), const allocator_type alloc allocator_type()); // 迭代器是⼀个双向迭代器 iterator-a bidirectional iterator to const value_type // 正向迭代器 iterator begin(); iterator end(); // 反向迭代器 reverse_iterator rbegin(); reverse_iterator rend();map的增删查map的增删查关注以下⼏个接⼝即可map增接⼝插⼊的pair键值对数据跟set所有不同但是查和删的接⼝只⽤关键字key跟set是完全类似的不过find返回iterator不仅仅可以确认key在不在还找到key映射的value同时通过迭代还可以修改value。Member types key_type-The first template parameter(Key) mapped_type-The second template parameter(T) value_type-pairconst key_type, mapped_type // 单个数据插⼊如果已经key存在则插⼊失败,key存在相等value不相等也会插⼊失败 pairiterator, bool insert(const value_type val); // 列表插⼊已经在容器中存在的值不会插⼊ void insert(initializer_listvalue_type il); // 迭代器区间插⼊已经在容器中存在的值不会插⼊ template class InputIterator void insert(InputIterator first, InputIterator last); // 查找k返回k所在的迭代器没有找到返回end() iterator find(const key_type k); // 查找k返回k的个数 size_type count(const key_type k) const; // 删除⼀个迭代器位置的值 iterator erase(const_iterator position); // 删除kk存在返回0存在返回1 size_type erase(const key_type k); // 删除⼀段迭代器区间的值 iterator erase(const_iterator first, const_iterator last); // 返回⼤于等k位置的迭代器 iterator lower_bound(const key_type k); // 返回⼤于k位置的迭代器 const_iterator lower_bound(const key_type k) const;构造遍历及增删查使用样例下面是对上面构造、插入、查找以及迭代器的使用。其中拷贝构造和迭代器构造没用使用在之前这种方式使用的很多了就不再使用了。并且反向迭代器也没用原理与迭代器类似就不过多赘述。int main() { //无参 //mapstring, stringdict; //列表初始化 mapstring, string dict { {left, 左边}, {right, 右边}, {insert, 插入},{ string, 字符串 } }; pairstring, string kvl { black,黑色 }; mapstring, string dict1 { kvl,pairstring,string(write,白色) }; dict1.insert(kvl); dict1.insert(pairstring, string(first, 首先)); dict1.insert(make_pair(rice, 米饭)); dict1.insert({ hello,你好 });//c11支持 // left已经存在插⼊失败 dict.insert({ left, 左边剩余 }); dict.erase({ black}); auto it dict.begin(); while (it ! dict.end()) { // 可以修改value不支持修改key //it-first x; //it-second x; //cout (*it).first : (*it).second endl; // map的迭代基本都使⽤operator-,这⾥省略了⼀个- // 第⼀个-是迭代器运算符重载返回pair*第⼆个箭头是结构指针解引⽤取 //pair数据 //cout it.operator-()-first : it.operator-()- second endl; cout it-first : it-second endl; it; } // 范围for遍历 for (const auto e : dict) { cout e.first : e.second endl; } cout endl; string str; while (cin str) { auto ret dict.find(str); if (ret ! dict.end()) { cout - ret-second endl; } else { cout ⽆此单词请重新输⼊ endl; } } // erase等接⼝跟set完全类似这⾥就不演⽰讲解了 return 0; }map的数据修改前⾯我提到map⽀持修改mapped_type 数据不⽀持修改key数据修改关键字数据破坏了底层搜索树的结构。map第⼀个⽀持修改的⽅式时通过迭代器迭代器遍历时或者find返回key所在的iterator修改map还有⼀个⾮常重要的修改接⼝operator[]但是operator[]不仅仅⽀持修改还⽀持插⼊数据和查找数据所以他是⼀个多功能复合接⼝需要注意从内部实现⻆度map这⾥把我们传统说的value值给的是T类型typedef为mapped_type。⽽value_type是红⿊树结点中存储的pair键值对值。⽇常使⽤我们还是习惯将这⾥的T映射值叫做value。Member types key_type-The first template parameter(Key) mapped_type-The second template parameter(T) value_type-pairconst key_type, mapped_type // 查找k返回k所在的迭代器没有找到返回end()如果找到了通过iterator可以修改key对应的 mapped_type值 iterator find(const key_type k); // ⽂档中对insert返回值的说明 // The single element versions (1) return a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the element with an equivalent key in the map.The pair::second element in the pair is set to true if a new element was inserted or false if an equivalent key already existed. // insert插⼊⼀个pairkey, T对象 // 1、如果key已经在map中插⼊失败则返回⼀个pairiterator,bool对象返回pair对象 first是key所在结点的迭代器second是false // 2、如果key不在在map中插⼊成功则返回⼀个pairiterator,bool对象返回pair对象 first是新插⼊key所在结点的迭代器second是true // 也就是说⽆论插⼊成功还是失败返回pairiterator,bool对象的first都会指向key所在的迭 代器 // 那么也就意味着insert插⼊失败时充当了查找的功能正是因为这⼀点insert可以⽤来实现 operator[] // 需要注意的是这⾥有两个pair不要混淆了⼀个是map底层红⿊树节点中存的pairkey, T另 ⼀个是insert返回值pairiterator, bool pairiterator, bool insert(const value_type val); mapped_type operator[] (const key_type k); // operator的内部实现 mapped_type operator[] (const key_type k) { // 1、如果k不在map中insert会插⼊k和mapped_type默认值同时[]返回结点中存储 mapped_type值的引⽤那么我们可以通过引⽤修改返映射值。所以[]具备了插⼊ 修改功能 // 2、如果k在map中insert会插⼊失败但是insert返回pair对象的first是指向key结点的 迭代器返回值同时[]返回结点中存储mapped_type值的引⽤所以[]具备了查找 修改的功能 pairiterator, bool ret insert({ k, mapped_type() }); iterator it ret.first; return it-second; }map的迭代器和[]功能样例int main() { // 利⽤find和iterator修改功能统计⽔果出现的次数 string arr[] { 苹果, 西⽠, 苹果, 西⽠, 苹果, 苹果, 西⽠, 苹果, ⾹蕉, 苹果, ⾹蕉 }; mapstring, int countMap; for (const auto str : arr) { // 先查找⽔果在不在map中 // 1、不在说明⽔果第⼀次出现则插⼊{⽔果, 1} // 2、在则查找到的节点中⽔果对应的次数 auto ret countMap.find(str); if (ret countMap.end()) { countMap.insert({ str, 1 }); } else { ret-second; } } for (const auto e : countMap) { cout e.first : e.second endl; } cout endl; return 0; } #includeiostream #includemap #includestring using namespace std; int main() { // 利⽤[]插⼊修改功能巧妙实现统计⽔果出现的次数 string arr[] { 苹果, 西⽠, 苹果, 西⽠, 苹果, 苹果, 西⽠, 苹果, ⾹蕉, 苹果, ⾹蕉 }; mapstring, int countMap; for (const auto str : arr) { // []先查找⽔果在不在map中 // 1、不在说明⽔果第⼀次出现则插⼊{⽔果, 0}同时返回次数的引⽤ //⼀下就变成1次了 // 2、在则返回⽔果对应的次数 countMap[str]; } for (const auto e : countMap) { cout e.first : e.second endl; } cout endl; return 0; }int main() { mapstring, string dict; dict.insert(make_pair(sort, 排序)); // key不存在-插⼊ {insert, string()} dict[insert]; // 插⼊修改 dict[left] 左边; // 修改 dict[left] 左边、剩余; // key存在-查找 cout dict[left] endl; return 0; }例题数据结构初阶阶段为了控制随机指针我们将拷⻉结点链接在原节点的后⾯解决后⾯拷⻉节点还得解下来链接⾮常⿇烦。这⾥我们直接让{原结点,拷⻉结点}建⽴映射关系放到map中控制随机指针会⾮常简单⽅便。class Solution { public: Node* copyRandomList(Node* head) { mapNode*,Node* nodemap; Node*copyheadnullptr; Node*copytailnullptr; Node*curhead; while(cur) { if(copytailnullptr) { copyheadcopytailnew Node(cur-val); } else { copytail-nextnew Node(cur-val); copytailcopytail-next; } //将原节点与拷贝节点映射到map中 nodemap[cur]copytail; curcur-next; } //控制random curhead; Node*copycopyhead; while(cur) { if(cur-randomnullptr) { copy-randomnullptr; } else { copy-randomnodemap[cur-random]; } curcur-next; copycopy-next; } return copyhead; } };将map统计出的次数的数据放到vector中排序或者放到priority_queue中来选出前k个。利⽤仿函数强⾏控制次数相等的字典序⼩的在前⾯。class Solution { public: struct Compare { bool operator()(const pairstring, int x, const pairstring, int y)const { return x.second y.second || (x.second y.second x.first y.first); } }; vectorstring topKFrequent(vectorstring words, int k) { mapstring, int countMap; for(auto e : words) { countMap[e]; } vectorpairstring, int v(countMap.begin(), countMap.end()); // 仿函数控制降序,仿函数控制次数相等字典序⼩的在前⾯ sort(v.begin(), v.end(), Compare()); // 取前k个 vectorstring strV; for(int i 0; i k; i) { strV.push_back(v[i].first); } return strV; } };这里就不展示优先级队列的了与这个类似。这一期就结束了感谢支持