C++进阶——map和set的使用
目录
1、序列式容器和关联式容器
2、set系列的使用
2.1 set和multiset的参考文档
2.2 set类的介绍
2.3 set的构造和迭代器
2.4 set的增删查
2.5 set的insert和迭代器遍历
2.6 set的find和erase
2.7 set的lower_bound和upper_bound
2.8 multiset和set的差异
2.9 349. 两个数组的交集 - 力扣(LeetCode)
2.10 142. 环形链表 II - 力扣(LeetCode)
3、map系列的使用
3.1 map和multimap的参考文档
3.2 map类的介绍
3.3 pair类型的介绍
3.4 map的构造和迭代器
3.5 map的增删查
3.6 map的数据修改
3.7 map的构造遍历及增删查
3.8 map的迭代器和[ ]
3.9 multimap和map的差异
3.10 138. 随机链表的复制 - 力扣(LeetCode)
3.11 692. 前K个高频单词 - 力扣(LeetCode)
1、序列式容器和关联式容器
前面我们已经接触过STL中的部分容器如:string、vector、list、deque、array、forward_list等,这些容器统称为序列式容器,因为逻辑结构为线性结构,两个位置存储的值之间一般没有紧密的关联关系,比如交换一下,他依旧是序列式容器。序列式容器中的元素是按他们在容器中的存储位置(插入位置)来顺序保存和访问的。
关联式容器的逻辑结构通常是非线性结构, 两个位置有紧密的关联关系,交换⼀下,他的存储结构就被破坏了。序列式容器中的元素是按关键字(key)来保存和访问的。关联式容器有map/set系列和unordered_map/unordered_set系列。 本节讲解的map和set底层是红黑树,红黑树是一颗平衡二叉搜索树。set是key搜索场景的结构, map是key/value搜索场景的结构。
2、set系列的使用
2.1 set和multiset的参考文档
<set> - C++ Reference
2.2 set类的介绍
1. set的声明如下,T就是set底层关键字key的类型。
2. set 默认要求key支持小于比较(升序),如果不支持或者想按自己的需求走可以自行实现仿函数传给第二个模版参数。
3. set底层存储数据的内存是从空间配置器申请的,如果需要可以自己实现内存池,传给第三个参 数。
4. 一般情况下,我们都不需要传后两个模版参数。
5. set底层是用红黑树实现,增删查效率是O(logN)。迭代器遍历走的是搜索树的中序,所以是有序。
template < class T, // set::key_type/value_type // 为了和map保持一致
class Compare = less<T>, // set::key_compare/value_compare
class Alloc = allocator<T> // set::allocator_type
> class set;
2.3 set的构造和迭代器
set的支持正向和反向 迭代遍历(即双向),支持迭代器就意味着支持范围for。
set不支持修改key数据,修改关键字数据,会破坏底层搜索树的性质。
// 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_list<value_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();
2.4 set的增删查
set的增删查关注以下几个接口即可:
// Member types
key_type -> The first template parameter(T)
value_type -> The first template parameter(T)
// 单个数据插入,如果已经存在则插入失败
pair<iterator, bool> insert(const value_type& val);
// 列表插入,已经在容器中存在的值不会插入
void insert(initializer_list<value_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);
// 删除val,val不存在返回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;
2.5 set的insert和迭代器遍历
#include <iostream>
#include <set>
using namespace std;
int main()
{
// 去重+升序排序
set<int> s;
// 去重+降序排序(给一个大于的仿函数)
//set<int, greater<int>> s;
s.insert(5);
s.insert(2);
s.insert(7);
s.insert(5);
//set<int>::iterator it = s.begin();
auto it = s.begin();
while (it != s.end())
{
// error C3892: “it”: 不能给常量赋值
// *it = 1;
cout << *it << " ";
++it;
}
cout << endl;
// 插入一段initializer_list列表值,已经存在的值插入失败
s.insert({ 2,8,3,9 });
for (auto e : s)
{
cout << e << " ";
}
cout << endl;
set<string> strset = { "sort", "insert", "add" };
// 遍历string,以ascll码升序遍历
for (auto& e : strset)
{
cout << e << " ";
}
cout << endl;
}
2.6 set的find和erase
#include <iostream>
#include <set>
using namespace std;
int main()
{
set<int> 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;
}
for (auto e : s)
{
cout << e << " ";
}
cout << endl;
int y;
// 查找,再利用迭代器删除y
cin >> y;
auto pos = s.find(y);
if (pos != s.end())
{
s.erase(pos);
}
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;
}
2.7 set的lower_bound和upper_bound
#include <iostream>
#include <set>
using namespace std;
int main()
{
std::set<int> 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;
// 实现查找到[itlow, itup)包含[30, 60]的区间
// C++区间必须是必须是左闭右开,如果是[ ],通过以下方式,转成[ )
// 返回>= 30
auto itlow = myset.lower_bound(30);
// 返回> 60
auto itup = myset.upper_bound(60);
// 删除这段区间的值
myset.erase(itlow, itup);
for (auto e : myset)
{
cout << e << " ";
}
cout << endl;
return 0;
}
2.8 multiset和set的差异
multiset和set的使用基本类似,主要区别点在于multiset支持冗余,那么 insert/find/count/erase都围绕着支持冗余有所差异。
#include <iostream>
#include <set>
using namespace std;
int main()
{
// 相比set不同的是,multiset是排序,但是不去重
multiset<int> 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;
}
2.9 349. 两个数组的交集 - 力扣(LeetCode)
思路:
set(去重+排序) + 双指针
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
set<int> s1(nums1.begin(),nums1.end());
set<int> s2(nums2.begin(),nums2.end());
vector<int> v;
auto it1 = s1.begin();
auto it2 = s2.begin();
while(it1 != s1.end() &&it2 != s2.end())
{
if(*it1<*it2)
++it1;
else if(*it1>*it2)
++it2;
else
{
v.push_back(*it1);
++it1;
++it2;
}
}
return v;
}
};
2.10 142. 环形链表 II - 力扣(LeetCode)
思路:
set.count()的返回值充当查找的功能。
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
set<ListNode*> s;
ListNode* cur = head;
while(cur)
{
if(s.count(cur) == 0)
s.insert(cur);
else
return cur;
cur = cur->next;
}
return nullptr;
}
};
3、map系列的使用
3.1 map和multimap的参考文档
<map> - C++ Reference
3.2 map类的介绍
1. map的声明如下,Key就是map底层关键字key的类型,T是map底层value的类型。
2. map 默认要求key支持小于比较(升序),如果不支持或者需要的话可以自行实现仿函数传给第二个模版参数。
3. map底层存储数据的内存是从空间配置器申请的,如果需要可以自己实现内存池,传给第三个参 数。
4. 一般情况下,我们都不需要传后两个模版参数。
5. map 底层是用红黑树实现,增删查改效率是 O(logN)。迭代器遍历走的是搜索树的中序,所以是按key有序。
template < class Key, // map::key_type
class T, // map::mapped_type
class Compare = less<Key>, // map::key_compare
class Alloc = allocator < pair<const Key, T> >//map::allocator_type
> class map;
3.3 pair类型的介绍
map底层的红黑树节点中的数据,使用pair存储 键值对 数据。
typedef pair<const Key, T> value_type;
// pair 类模板
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)
{}
// 更加通用,允许从不同类型的 pair 对象进行构造
template<class U, class V>
pair(const pair<U, V>& pr) : first(pr.first), second(pr.second)
{}
};
// make_pair 函数模板
template <class T1, class T2>
inline pair<T1, T2> make_pair(T1 x, T2 y)
{
return (pair<T1, T2>(x, y));
}
3.4 map的构造和迭代器
map的支持正向和反向 迭代遍历(即双向),支持迭代器就意味着⽀持范围for。
map支持修改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_list<value_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();
3.5 map的增删查
map的增删查关注以下几个接口即可:
map插入的是pair键值对数据,跟set所有不同,但是查和删的接口只用关键字key跟set是完全类似的,不过find返回iterator(pair指针),不仅仅可以确认key在不在,修改到key映射的value。
// Member types
key_type->The first template parameter(Key)
mapped_type->The second template parameter(T)
value_type->pair<const key_type, mapped_type>
// 单个数据插入,如果存在key则插入失败
pair<iterator, bool> insert(const value_type& val);
// 列表插入,已经在容器中存在key.那么这个pair不会插入
void insert(initializer_list<value_type> il);
// 迭代器区间插⼊,已经在容器中存在key.那么这个pair不会插入
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);
// 删除k,k存在返回0,存在返回1
size_type erase(const key_type & k);
// 删除一段迭代器区间的值
iterator erase(const_iterator first, const_iterator last);
3.6 map的数据修改
map支持修改mapped_type数据,不支持修改key数据,修改关键字数据,会破坏底层搜索树的结构。
map 第一个支持修改的方式是通过迭代器,迭代器遍历时或者find返回key所在的iterator修改。
map 还有一个非常重要的修改接口 operator[ ],但是operator[ ]不仅仅支持修改,还支持插入数据和查找数据,所以他是一个多功能复合接口。
// Member types
key_type->The first template parameter(Key)
mapped_type->The second template parameter(T)
value_type->pair<const key_type, mapped_type>
// 查找k,返回k所在的迭代器,没有找到返回end(),如果找到了通过iterator可以修改key对应的mapped_type值
iterator find(const key_type& k);
// insert插入一个pair<key, T>对象
// 1、如果key已经在map中,插入失败,则返回一个pair<iterator, bool>对象,
// iterator是key所在结点的迭代器,false
// 2、如果key不存在map中,插入成功,则返回一个pair<iterator, bool>对象,
// iterator是新插入key所在结点的迭代器,true
// 那么也就意味着insert插入失败时充当了查找的功能,因此,insert可以用来实现operator[]
// 注意:这里有两个pair,一个是map底层红黑树节点中存的pair<key, T>,另一个是insert返回值pair<iterator, bool>
pair<iterator, bool> insert(const value_type & val);
// 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值的引用
// 所以[]具备了查找+修改的功能
pair<iterator, bool> ret = insert({ k, mapped_type() });
iterator it = ret.first;
return it->second;
}
3.7 map的构造遍历及增删查
#include<iostream>
#include<map>
using namespace std;
int main()
{
// initializer_list构造及迭代遍历
map<string, string> dict = { {"left", "左边"}, {"right", "右边"},
{"insert", "插入"},{ "string", "字符串" } };
//map<string, string>::iterator it = dict.begin();
auto it = dict.begin();
while (it != dict.end())
{
//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;
}
cout << endl;
string str;
while (cin >> str)
{
auto ret = dict.find(str);
if (ret != dict.end())
{
cout << "->" << ret->second << endl;
}
else
{
cout << "无此单词,请重新输入" << endl;
}
}
// insert插入pair对象的4种方式,对比之下,最后一种最方便
pair<string, string> kv1("first", "第一个");
dict.insert(kv1);
dict.insert(pair<string, string>("second", "第二个"));
dict.insert(make_pair("third", "第三个"));
dict.insert({ "fourth", "第四个" });
// 范围for遍历
for (const auto& e : dict)
{
cout << e.first << ":" << e.second << endl;
}
cout << endl;
// erase等接口跟set完全类似,这里就不演时讲解了
return 0;
}
3.8 map的迭代器和[ ]
#include<iostream>
#include<map>
using namespace std;
int main()
{
// 利用find和iterator修改功能,统计水果出现的次数
string arr[] = { "苹果", "西瓜", "苹果", "西瓜", "苹果", "苹果",
"西瓜", "苹果", "香蕉", "苹果", "香蕉" };
map<string, int> countMap1;
for (const auto& str : arr)
{
// 先查找水果在不在map中
// 1、不在,说明水果第一次出现,则插入{水果, 1}
// 2、在,则查找到的节点中水果对应的次数++
auto ret = countMap1.find(str);
if (ret == countMap1.end())
{
countMap1.insert({ str, 1 });
}
else
{
ret->second++;
}
}
for (const auto& e : countMap1)
{
cout << e.first << ":" << e.second << endl;
}
cout << endl;
// 利用[ ]插入+修改功能,巧妙实现统计水果出现的次数
map<string, int> countMap2;
for (const auto& str : arr)
{
// [ ]先查找水果在不在map中
// 1、不在,说明⽔果第一次出现,则插入{水果, 0 },同时返回次数的引用,++一下就变成1次了
// 2、在,则返回水果对应的次数++
countMap2[str]++;
}
for (const auto& e : countMap2)
{
cout << e.first << ":" << e.second << endl;
}
cout << endl;
return 0;
}
3.9 multimap和map的差异
multimap和map的使用基本类似,主要区别点在于multimap支持关键值key冗余。
那么insert/find/count/erase都围绕着支持关键值key冗余有所差异,这里跟set和multiset完全一样。
如 find 时,有多个key,返回中序第一个。其次就是multimap不支持[ ],因为支持key冗余。
3.10 138. 随机链表的复制 - 力扣(LeetCode)
思路1:
A→A′→B→B′→C→C′
写的时候,注意先保存,链表头 尾连接的情况。head要经常用,使用不直接使用head。
class Solution {
public:
Node* copyRandomList(Node* head) {
if(head == nullptr)
return nullptr;
Node* cur = head;
while(cur)
{
Node* node = new Node(cur->val);
Node* tmp = cur->next; // 先保存原节点的next
// 连接节点
cur->next = node;
node->next = tmp;
cur = tmp;
}
cur = head;
while(cur)
{
if(cur->random)
cur->next->random = cur->random->next;
else
cur->next->random = nullptr;
cur = cur->next->next;
}
cur = head;
Node* h = head->next; // 保存拷贝链表的头节点
while(cur)
{
Node* node = cur->next; // 先保存拷贝节点
// 原链表连接
cur->next = node->next;
cur = cur->next;
// 拷贝链表连接
if(cur) // 原链表cur为nullptr,单独处理
node->next = cur->next;
else
node->next = nullptr;
}
return h;
}
};
思路2:
map<Node*,Node*>,对应拷贝,拷贝的节点的next和random,注意一下nullptr。
class Solution {
public:
Node* copyRandomList(Node* head) {
if(head == nullptr)
return nullptr;
map<Node*,Node*> mp;
Node* cur = head;
while(cur)
{
mp.insert({cur,new Node(cur->val)});
cur = cur->next;
}
auto it = mp.begin();
while(it != mp.end())
{
if(it->first->next)
it->second->next = mp[it->first->next];
else
it->second->next = nullptr;
if(it->first->random)
it->second->random = mp[it->first->random];
else
it->second->random = nullptr;
++it;
}
return mp[head];
}
};
3.11 692. 前K个高频单词 - 力扣(LeetCode)
思路一:
map<string,int>,会按string(key)默认升序,sort需要随机迭代器,先转成vector,排序时改变sort的比较方式,使其稳定,或者直接使用stable_sort(稳定的排序,应该是希尔排序)。
class Solution {
public:
struct Compare
{
bool operator()(const pair<string,int>& p1,const pair<string,int>& p2)
{
return p1.second>p2.second||p1.second==p2.second&&p1.first<p2.first;
}
};
vector<string> topKFrequent(vector<string>& words, int k) {
map<string,int> mp;
for(const auto& e:words)
{
++mp[e];
}
vector<pair<string,int>> v(mp.begin(),mp.end());
sort(v.begin(),v.end(),Compare());
vector<string> ans;
for(int i = 0;i<k;++i)
{
ans.push_back(v[i].first);
}
return ans;
}
};