✅<1>主页:我的代码爱吃辣
<2>知识讲解:C++ STL map&&set
☂️<3>开发环境:Visual Studio 2022
<4>前言:map和set是C++98就已经支持的两个搜索效率极高的容器,其底层就是使用和红黑树作为存储容器,我们已经实现了红黑树,接下来我们熟悉一下map和set的使用,并了解其封装结构,我们自己使用红黑树封装一个。
目录
一.认识map,set
1.关联式容器
2.键值对
3.树形结构的关联式容器
二.set介绍
1.set使用
2.multiset的使用
三.map介绍
1.map使用
2.multimap
四.封装map,set
五.源码
在初阶阶段,我们已经接触过STL中的部分容器,比如:vector、list、dequeforward_list(C++11)等,这些容器统称为序列式容器,因为其底层为线性序列的数据结构,里面存储的是元素本身。那什么是关联式容器?它与序列式容器有什么区别?
关联式容器也是用来存储数据的,与序列式容器不同的是,其里面存储的是
键值对,在数据检索时比序列式容器效率更高
用来表示具有一一对应关系的一种结构,该结构中一般只包含两个成员变量key和value,key代
表键值,value表示与key对应的信息。比如:现在要建立一个英汉互译的字典,那该字典中必然
有英文单词与其对应的中文含义,而且,英文单词与其中文含义是一一对应的关系,即通过该应
该单词,在词典中就可以找到与其对应的中文含义。
SGI-STL中关于键值对的定义:
template
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)
{}
};
根据应用场景的不桶,STL总共实现了两种不同结构的管理式容器:树型结构与哈希结构。树型结
构的关联式容器主要有四种:map、set、multimap、multiset。这四种容器的共同点是:使
用平衡搜索树(即红黑树)作为其底层结果,容器中的元素是一个有序的序列。下面一依次介绍每一
个容器。
reference-------set
#include
#include
using namespace std;
int main()
{
std::set s;
int arr[] = { 4, 2, 6, 1, 3, 5, 15, 7, 16, 14 };
for (auto e : arr)
{
s.insert(e);
}
auto it = s.begin();
while (it != s.end())
{
cout << *it << ' ';
it++;
}
return 0;
}
void TestSet()
{
// 用数组 array 中的元素构造 set
int array[] = { 1, 3, 5, 7, 9, 2, 4, 6, 8, 0, 1, 3, 5, 7, 9, 2, 4, 6, 8, 0 };
set s(array, array + sizeof(array) / sizeof(array[0]));
cout << s.size() << endl;
// 正向打印set中的元素,从打印结果中可以看出:set可去重
for (auto& e : s)
cout << e << " ";
cout << endl;
// 使用迭代器逆向打印set中的元素
for (auto it = s.rbegin(); it != s.rend(); ++it)
cout << *it << " ";
cout << endl;
// set中值为3的元素出现了几次
cout << s.count(3) << endl;
}
reference-------multiset
此处只简单演示set与multiset的不同,其他接口接口与set相同,同学们可参考set:
void TestSet()
{
int array[] = { 2, 1, 3, 9, 6, 0, 5, 8, 4, 7,1,2,2,1,7 };
// 注意:multiset在底层实际存储的是的键值对
multiset s(array, array + sizeof(array) / sizeof(array[0]));
for (auto& e : s)
cout << e << " ";
cout << endl;
// set中值为3的元素出现了几次
cout << s.count(2) << endl;;
}
reference------map
void TestMap()
{
map m;
// 向map中插入元素的方式:
// 将键值对<"peach","桃子">插入map中,用pair直接来构造键值对
m.insert(pair("peach", "桃子"));
// 将键值对<"peach","桃子">插入map中,用make_pair函数来构造键值对
m.insert(make_pair("banan", "香蕉"));
// 借用operator[]向map中插入元素
/*
operator[]的原理是:
用构造一个键值对,然后调用insert()函数将该键值对插入到map中
如果key已经存在,插入失败,insert函数返回该key所在位置的迭代器
如果key不存在,插入成功,insert函数返回新插入元素所在位置的迭代器
operator[]函数最后将insert返回值键值对中的value返回
*/
// 将<"apple", "">插入map中,插入成功,返回value的引用,将“苹果”赋值给该引用结果,
m["apple"] = "苹果";
// key不存在时抛异常
//m.at("waterme") = "水蜜桃";
cout << m.size() << endl;
// 用迭代器去遍历map中的元素,可以得到一个按照key排序的序列
for (auto& e : m)
cout << e.first << "--->" << e.second << endl;
cout << endl;
// map中的键值对key一定是唯一的,如果key存在将插入失败
auto ret = m.insert(make_pair("peach", "桃色"));
if (ret.second)
cout << "不在map中, 已经插入" << endl;
else
cout << "键值为peach的元素已经存在:" << ret.first->first << "--->"
<< ret.first->second << " 插入失败" << endl;
// 删除key为"apple"的元素
m.erase("apple");
if (1 == m.count("apple"))
cout << "apple还在" << endl;
else
cout << "apple被吃了" << endl;
}
reference-------multimap
注意:multimap和map的唯一不同就是:map中的key是唯一的,而multimap中key是可以
重复的。
map和set的底层结构就是红黑树,因此在map中直接封装一棵红黑树,然后将其接口包装。
注意:此时模拟实现,我们将对set和map共用同一颗红黑树。所以红黑树的结点结构也要有所变化:
enum Color
{
RED,
BLACK
};
template
struct _RBTreeNode
{
_RBTreeNode(T date)
:_date(date),
_col(RED),
_left(nullptr),
_right(nullptr),
_parent(nullptr)
{
}
//我们并不清楚将来时map使用还是set使用,
//如果map:T -> Key,如果时map:T ->pair
T _date;
Color _col; //颜色
_RBTreeNode* _left; //左孩子
_RBTreeNode* _right; //右孩子
_RBTreeNode* _parent; //双亲结点
};
set的大致结构:
template
class set
{
public:
bool insert(const K& k)
{
return _rbTree.insert(k).second;
}
~set()
{
_rbTree.~RBTRee();
}
private:
RBTRee _rbTree;
};
由于map和set公用一颗红黑树,那么在结点访问上,map的结点存储的时pair
例如:
RB_Tree.hpp::find()
template
class RBTRee
{
typedef _RBTreeNode< T> Node;
KeyOfT keyoft;
public:
Node* find(const K& key)
{
Node* cur = _root;
while (cur)
{
if (key < keyoft(cur->_date))
{
cur = cur->_left;
}
else if (key > keyoft(cur->_date))
{
cur = cur->_right;
}
else
{
return cur;
}
}
return nullptr;
}
private:
Node* _root = nullptr;
};
set.hpp
template
class set
{
struct SetKeyOfT
{
K operator()(const K& date)
{
return date;
}
};
public:
//....
private:
RBTRee _rbTree;
};
map.hpp:
template
class map
{
struct MapKeyOfT
{
K operator()(pair date)
{
return date.first;
}
};
public:
//....
private:
RBTRee, MapKeyOfT> _rbTree;
};
迭代器:
迭代器的一个大难题就是怎么实现++操作,++操作实际上就是一个中序遍历的结果。
// T , T&/const T& , T*/const T*
template
struct __iterator
{
typedef _RBTreeNode< T> Node;
typedef __iterator Self;
public:
__iterator(Node*node)
:_node(node)
{
}
Ref operator*()
{
return _node->_date;
}
Ptr operator->()
{
return &_node->_date;
}
Self& operator++()
{
//...
return *this;
}
bool operator!=(Self it)
{
return it._node != _node;
}
Node* _node;
};
template
class RBTRee
{
KeyOfT keyoft;
typedef _RBTreeNode Node;
public:
typedef __iterator iterator;
typedef __iterator const_iterator;
iterator begin()
{
//找到最左边结点
Node* cur = _root;
while (cur->_left)
{
cur = cur->_left;
}
return iterator(cur);
}
iterator end()
{
return iterator(nullptr);
}
const_iterator begin()const
{
Node* cur = _root;
while (cur->_left)
{
cur = cur->_left;
}
return const_iterator(cur);
}
const_iterator end()const
{
return const_iterator(nullptr);
}
}
operator++()
Self& operator++()
{
Node* curright = _node->_right;
if (curright)//右子树不为空
{
//右子树的最左节点
while (curright->_left)
{
curright = curright->_left;
}
_node = curright;
}
else//右子树为空
{
//自己不是右孩子的那个父亲
Node* cur = _node;
Node* parent = cur->_parent;
while (parent && cur == parent->_right)
{
cur = parent;
parent = cur->_parent;
}
_node = parent;
}
return *this;
}
insert():
为了和库里面保持一致:将insert返回值变为,pair
pair insert(T date)
{
if (_root == nullptr)
{
_root = new Node(date);
_root->_col = BLACK;
return pair(iterator(_root), true);
}
Node* cur = _root;
Node* parent = nullptr;
while (cur)
{
if (keyoft(date) < keyoft(cur->_date))
{
parent = cur;
cur = cur->_left;
}
else if (keyoft(date) > keyoft(cur->_date))
{
parent = cur;
cur = cur->_right;
}
else
{
return pair(iterator(cur), false);
}
}
//找到了合适的位置
cur = new Node(date);
//用于返回,提前保存
Node* rettmp = cur;
if (keyoft(date) < keyoft(parent->_date))
{
parent->_left = cur;
}
else
{
parent->_right = cur;
}
cur->_parent = parent;
while ( parent && parent->_col == RED)
{
Node* grandfather = parent->_parent;
// g(B) g(R)
// p(R) u(R) --> p(B) u(B)
//c(R) c(R)
if ( grandfather->_left == parent)
{
Node* uncle = grandfather->_right;
if (uncle && uncle->_col == RED)
{
parent->_col = BLACK;
uncle->_col = BLACK;
grandfather->_col = RED;
//继续向上调整
cur = grandfather;
parent = cur->_parent;
}
else //u不存在/u存在且为黑,旋转+变色
{
// g(B) p(R)
// p(R) u(B) --> u(B) g(B)
//c(R) u(B)
if (cur == parent->_left)
{
//右单旋
RotateR(grandfather);
parent->_col = BLACK;
//cur->_col = RED;
grandfather->_col = RED;
}
else
{
// g(B) P(B)
// p(R) u(B) --> c(R) g(R)
// c(R) u(B)
// 左右双旋
RotateL(parent);
RotateR(grandfather);
cur->_col = BLACK;
grandfather->_col = RED;
}
break;
}
}
else //grandfather->_right == parent,与上述情况相反
{
Node* uncle = grandfather->_left;
if (uncle && uncle->_col == RED)
{
parent->_col = BLACK;
uncle->_col = BLACK;
grandfather->_col = RED;
cur = grandfather;
parent = cur->_parent;
}
else //u不存在/u存在且为黑,旋转+变色
{
if (cur == parent->_right)
{
//左单旋
RotateL(grandfather);
parent->_col = BLACK;
grandfather->_col = RED;
}
else
{
// 右左双旋
RotateR(parent);
RotateL(grandfather);
cur->_col = BLACK;
grandfather->_col = RED;
}
break;
}
}
}
_root->_col = BLACK;
return pair(iterator(rettmp), true);
}
set::insert()
bool insert(const K& k)
{
return _rbTree.insert(k).second;
}
map::insert()
bool insert(const pair& kv)
{
return _rbTree.insert(kv);
}
map::operator [ ] ( )
V& operator[](const K& key)
{
pair ret = _rbTree.insert(make_pair(key, V()));
return ret.first->second;
}
针对set设计,不能随意修改key
1.首先set使用的普通迭代器是由const迭代器封装的,这样可以保证key值不能随意修改,但是这就会引发另一个问题,正常的普通迭代器无法使用。
//set.hpp
typedef typename RBTRee::const_iterator iterator;
typedef typename RBTRee::const_iterator const_iterator;
iterator begin()
{
return _rbTree.begin();
}
解决方法:提供一个单参数的构造函数,支持由普通迭代器转换成const迭代器。
__iterator(const __iterator& it)
:_node(it._node)
{
}
RB_Tree.hpp
#pragma once
#include
using namespace std;
enum Color
{
RED,
BLACK
};
template
struct _RBTreeNode
{
_RBTreeNode(T date)
:_date(date),
_col(RED),
_left(nullptr),
_right(nullptr),
_parent(nullptr)
{
}
//我们并不清楚将来时map使用还是set使用,
//如果map:T -> Key,如果时map:T ->pair
T _date;
Color _col; //颜色
_RBTreeNode* _left; //左孩子
_RBTreeNode* _right; //右孩子
_RBTreeNode* _parent; //双亲结点
};
template
struct __iterator
{
typedef _RBTreeNode< T> Node;
typedef __iterator Self;
public:
__iterator(Node*node)
:_node(node)
{
}
__iterator(const __iterator& it)
:_node(it._node)
{
}
Ref operator*()
{
return _node->_date;
}
Ptr operator->()
{
return &_node->_date;
}
Self& operator++()
{
Node* curright = _node->_right;
if (curright)//右子树不为空
{
//右子树的最左节点
while (curright->_left)
{
curright = curright->_left;
}
_node = curright;
}
else//右子树为空
{
//自己不是右孩子的那个父亲
Node* cur = _node;
Node* parent = cur->_parent;
while (parent && cur == parent->_right)
{
cur = parent;
parent = cur->_parent;
}
_node = parent;
}
return *this;
}
Self& operator--()
{
Node* curright = _node->_left;
if (curright)
{
while (curright->_right)
{
curright = curright->_right;
}
_node = curright;
}
else//左子树为空
{
Node* cur = _node;
Node* parent = cur->_parent;
while (parent && cur == parent->_left)
{
cur = parent;
parent = cur->_parent;
}
_node = parent;
}
return *this;
}
bool operator!=(Self it)
{
return it._node != _node;
}
Node* _node;
};
template
class RBTRee
{
KeyOfT keyoft;
typedef _RBTreeNode Node;
public:
typedef __iterator iterator;
typedef __iterator const_iterator;
iterator begin()
{
//找到最左边结点
Node* cur = _root;
while (cur->_left)
{
cur = cur->_left;
}
return iterator(cur);
}
iterator end()
{
return iterator(nullptr);
}
const_iterator begin()const
{
Node* cur = _root;
while (cur->_left)
{
cur = cur->_left;
}
return const_iterator(cur);
}
const_iterator end()const
{
return const_iterator(nullptr);
}
public:
pair find(const K& key)
{
Node* cur = _root;
while (cur)
{
if (key < keyoft(cur->_date))
{
cur = cur->_left;
}
else if (key > keyoft(cur->_date))
{
cur = cur->_right;
}
else
{
return pair(iterator(cur),true);
}
}
return pair(iterator(nullptr), false);
}
pair insert(T date)
{
if (_root == nullptr)
{
_root = new Node(date);
_root->_col = BLACK;
return pair(iterator(_root), true);
}
Node* cur = _root;
Node* parent = nullptr;
while (cur)
{
if (keyoft(date) < keyoft(cur->_date))
{
parent = cur;
cur = cur->_left;
}
else if (keyoft(date) > keyoft(cur->_date))
{
parent = cur;
cur = cur->_right;
}
else
{
return pair(iterator(cur), false);
}
}
cur = new Node(date);
//找到了合适的位置
Node* rettmp = cur;
if (keyoft(date) < keyoft(parent->_date))
{
parent->_left = cur;
}
else
{
parent->_right = cur;
}
cur->_parent = parent;
while ( parent && parent->_col == RED)
{
Node* grandfather = parent->_parent;
// g(B) g(R)
// p(R) u(R) --> p(B) u(B)
//c(R) c(R)
if ( grandfather->_left == parent)
{
Node* uncle = grandfather->_right;
if (uncle && uncle->_col == RED)
{
parent->_col = BLACK;
uncle->_col = BLACK;
grandfather->_col = RED;
//继续向上调整
cur = grandfather;
parent = cur->_parent;
}
else //u不存在/u存在且为黑,旋转+变色
{
// g(B) p(R)
// p(R) u(B) --> u(B) g(B)
//c(R) u(B)
if (cur == parent->_left)
{
//右单旋
RotateR(grandfather);
parent->_col = BLACK;
//cur->_col = RED;
grandfather->_col = RED;
}
else
{
// g(B) P(B)
// p(R) u(B) --> c(R) g(R)
// c(R) u(B)
// 左右双旋
RotateL(parent);
RotateR(grandfather);
cur->_col = BLACK;
grandfather->_col = RED;
}
break;
}
}
else //grandfather->_right == parent,与上述情况相反
{
Node* uncle = grandfather->_left;
if (uncle && uncle->_col == RED)
{
parent->_col = BLACK;
uncle->_col = BLACK;
grandfather->_col = RED;
cur = grandfather;
parent = cur->_parent;
}
else //u不存在/u存在且为黑,旋转+变色
{
if (cur == parent->_right)
{
//左单旋
RotateL(grandfather);
parent->_col = BLACK;
grandfather->_col = RED;
}
else
{
// 右左双旋
RotateR(parent);
RotateL(grandfather);
cur->_col = BLACK;
grandfather->_col = RED;
}
break;
}
}
}
_root->_col = BLACK;
return pair(iterator(rettmp), true);
}
void Inorder()
{
_inorder(_root);
cout << endl;
}
~RBTRee()
{
_Destrory(_root);
_root = nullptr;
}
int Height()
{
return _Height(_root);
}
bool isRBTree()
{
return _isRBTree(_root, 0, -1);
}
private:
//传参时benchmark是-1,代表还没有基准值,当走完第一条路径时,
//将第一条路径的黑色节点数作为基准值,后续路径走到null时,就与基准值比较。
//blacknum记录路径上的黑色节点数
bool _isRBTree(Node* root, int blacknum, int benchmark)
{
if (root == nullptr)
{
if (benchmark == -1)
{
benchmark = blacknum;
}
else
{
if (blacknum != benchmark)
{
cout << "black Node !=" << endl;
return false;
}
}
return true;
}
if (root->_col == BLACK)
{
blacknum++;
}
if (root->_col == RED && root->_parent && root->_parent->_col == RED)
{
cout << "red connect " << endl;
return false;
}
return _isRBTree(root->_left, blacknum, benchmark) && _isRBTree(root->_right, blacknum, benchmark);
}
int _Height(Node* root)
{
if (root == nullptr)
{
return 0;
}
int Hleft = _Height(root->_left);
int Hright = _Height(root->_right);
return Hleft > Hright ? Hleft + 1 : Hright + 1;
}
void _Destrory(Node* root)
{
if (root == nullptr)
{
return;
}
_Destrory(root->_left);
_Destrory(root->_right);
delete root;
}
void _inorder(Node* root)
{
if (root == nullptr)
{
return;
}
_inorder(root->_left);
cout << keyoft(root->_date) <<" ";
_inorder(root->_right);
}
void RotateL(Node* parent)
{
Node* curR = parent->_right;
Node* curRL = curR->_left;
//调整结点,并且修改其父亲结点指针
parent->_right = curRL;
if (curRL)//可能为空
{
curRL->_parent = parent;
}
//在修改子树根节点之前,保存子树根节点的父亲
Node* pparent = parent->_parent;
//修改子树根节点
curR->_left = parent;
parent->_parent = curR;
//子树根节点有可能是整棵树的根节点
if (pparent == nullptr)
{
_root = curR;
_root->_parent = nullptr;
}
else//子树根节点不是整棵树的根节点
{
//还要看子树是它父亲的左孩子还是右孩子
if (pparent->_left == parent)
{
pparent->_left = curR;
}
else
{
pparent->_right = curR;
}
curR->_parent = pparent;
}
}
void RotateR(Node* parent)
{
Node* curL = parent->_left;
Node* curLR = curL->_right;
parent->_left = curLR;
if (curLR)
{
curLR->_parent = parent;
}
Node* pparent = parent->_parent;
curL->_right = parent;
parent->_parent = curL;
if (parent == _root)
{
_root = curL;
_root->_parent = nullptr;
}
else
{
if (pparent->_left == parent)
{
pparent->_left = curL;
}
else
{
pparent->_right = curL;
}
curL->_parent = pparent;
}
}
private:
Node* _root = nullptr;
};
set.hpp
#pragma once
#include"RB_Tree.hpp"
template
class set
{
struct SetKeyOfT
{
K operator()(const K& date)
{
return date;
}
};
public:
typedef typename RBTRee::const_iterator iterator;
typedef typename RBTRee::const_iterator const_iterator;
iterator begin()
{
return _rbTree.begin();
}
const_iterator begin() const
{
return _rbTree.begin();
}
iterator end()
{
return _rbTree.end();
}
const_iterator end() const
{
return _rbTree.end();
}
bool insert(const K& k)
{
return _rbTree.insert(k).second;
}
void Inorder()
{
_rbTree.Inorder();
}
private:
RBTRee _rbTree;
};
map.hpp
#pragma once
#include"RB_Tree.hpp"
template
class map
{
struct MapKeyOfT
{
K operator()(pair date)
{
return date.first;
}
};
public:
typedef typename RBTRee, MapKeyOfT>::iterator iterator;
typedef typename RBTRee, MapKeyOfT>::const_iterator const_iterator;
iterator begin()
{
return _rbTree.begin();
}
const_iterator begin() const
{
return _rbTree.begin();
}
iterator end()
{
return _rbTree.end();
}
const_iterator end() const
{
return _rbTree.end();
}
V& operator[](const K& key)
{
pair ret = _rbTree.insert(make_pair(key, V()));
return ret.first->second;
}
bool insert(const pair& kv)
{
return _rbTree.insert(kv);
}
void Inorder()
{
_rbTree.Inorder();
}
private:
RBTRee, MapKeyOfT> _rbTree;
};