目录
1.序列式容器和关联式容器
之前接触过的STL中的部分容器如:string、vector、list、deque、array、forward_list等,这 些容器统称为序列式容器,因为逻辑结构为线性序列的数据结构,两个位置存储的值之间⼀般没有紧密的关联关系,⽐如交换⼀下,他依旧是序列式容器。顺序容器中的元素是按他们在容器中的存储位置来顺序保存和访问的。
关联式容器也是⽤来存储数据的,与序列式容器不同的是,关联式容器逻辑结构通常是⾮线性结构,两个位置有紧密的关联关系,交换⼀下,他的存储结构就被破坏了。顺序容器中的元素是按关键字来保存和访问的。关联式容器有map/set系列和unordered_map/unordered_set系列。
map和set底层是红⿊树,红⿊树是⼀颗平衡⼆叉搜索树。set是key搜索场景的结构,map是key/value搜索场景的结构。
2.set系列的使用
参考文档:set和muitiset参考文档。
2.1set类的介绍
template < class T, // set::key_type/value_type
class Compare = less<T>, // set::key_compare/value_compare
class Alloc = allocator<T>> // set::allocator_type
class set;
2.2set的构造和迭代器
set的构造关注以下几个接口即可。set的⽀持正向和反向迭代遍历,遍历默认按升序顺序,因为底层是⼆叉搜索树,迭代器遍历⾛的中序;⽀持迭代器就意味着⽀持范围for,set的iterator和const_iterator都不⽀持迭代器修改数据,修改关键字数据,破坏了底层搜索树的结构。
// 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.3insert和迭代器遍历使用样例
库里面的set默认是不插入相同的值的,并且通过中序遍历的时候默认是升序,所以默认是小于根的值存储在左边,大于根的值存储在右边。
#include <iostream>
#include <string>
#include <set>
#include <map>
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);
auto it = s.begin();
while (it != s.end())
{
//error C3892 : “it”: 不能给常量赋值
//*it = 1;
cout << *it << " ";
++it;
}
cout << endl;
return 0;
}
通过初始化列表进行插入:
#include <iostream>
#include <string>
#include <set>
#include <map>
using namespace std;
int main()
{
set<int> s;
s.insert({ 2,8,3,9,2,6 });
for (auto e : s)
{
cout << e << " ";
}
cout << endl;
return 0;
}
如果插入的是字符串,是通过ASCII码进行比较的:
#include <iostream>
#include <string>
#include <set>
#include <map>
using namespace std;
int main()
{
set<string> strset = { "sort", "insert", "add" };
// 遍历string⽐较ascii码⼤⼩顺序遍历的
for (auto& e : strset)
{
cout << e << " ";
}
cout << endl;
return 0;
}
2.4find和erase使用样例
删除最小值删除begin()指向的节点即可。
#include <iostream>
#include <string>
#include <set>
#include <map>
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;
return 0;
}
两种删除值的方法:
(1)直接使用erase()进行删除,如果不存在要删除的值,erase()函数会返回0.
(2)先通过find()查找到要删除的值,然后再通过遍历进行删除。
//直接删除x
int x;
cin >> x;
int num = s.erase(x);
if (num == 0)
{
cout << x << "不存在!" << endl;
}
for (auto e : s)
{
cout << e << " ";
}
cout << endl;
//直接查找在利⽤迭代器删除x
cin >> x;
auto pos = s.find(x);
if (pos != s.end())
{
s.erase(pos);
}
else
{
cout << x << "不存在!" << endl;
}
s.erase(s.begin());
for (auto e : s)
{
cout << e << " ";
}
cout << endl;
注意:set里面自带的查找方法时间复杂度是,算法库里面的查找是暴力查找,是通过迭代器从头进行遍历,时间复杂度是。
可以利用count()函数进行间接的查找,count()函数是统计该值在set中出现的次数,不存在返回0,反之返回存在的次数。在这里存在这个函数是为了与后面的multiset进行统一。
#include <iostream>
#include <string>
#include <set>
#include <map>
using namespace std;
int main()
{
set<int> s = { 4,2,7,2,8,5,9 };
for (auto e : s)
{
cout << e << " ";
}
cout << endl;
int x;
cin >> x;
if (s.count(x))
{
cout << x << "在!" << endl;
}
else
{
cout << x << "不存在!" << endl;
}
return 0;
}
2.5lower_bound和upper_bound的使用
这两个函数返回的都是迭代器,不同的是,lower_bound是返回大于等于给的参数值的第一个迭代器,upper_bound返回大于给的参数值的第一个迭代器。如果删除lower_bound和upper_bound之间的值,刚好是左闭右开的迭代器区间。
#include <iostream>
#include <string>
#include <set>
#include <map>
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]区间
// 返回 >= 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.6multiser和set的差异
multiset和set的使⽤基本完全类似,主要区别点在于multiset⽀持值冗余。
#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;
}
3.map系列的使用
参考文档:map系列的参考文档
3.1map类的介绍
map的声明如下,Key就是map底层关键字的类型,T是map底层value的类型,set默认要求Key⽀持⼩于⽐较,如果不⽀持或者需要的话可以⾃⾏实现仿函数传给第⼆个模版参数,map底层存储数据的内存是从空间配置器申请的。⼀般情况下,我们都不需要传后两个模版参数。map底层是⽤红⿊树实现,增删查改效率是 O(logN) ,迭代器遍历是⾛的中序,是按key有序顺序遍历的。map和set其实很相似,只是存储的数据不一样,set存储的是一种T类型的数据,map存储的是pair类型的键值对。所以后面就不过多的进行介绍,只介绍有差异的部分。
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.2pair类型的介绍
map底层的红黑树节点中的数据,使用pair<Key, T>存储键值对数据。pair类是一个类模板,传入两个值,自动推导数据类型,里面first存储的是Key的值,second存储的是T的值。其中Key值是不允许修改的。
//在map中将pair类型重命名为value_type
typedef pair<const 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)
{}
//拷贝构造
template<class U, class V>
pair (const pair<U,V>& pr): first(pr.first), second(pr.second)
{}
};
//maka_pair函数模板
template <class T1,class T2>
inline pair<T1,T2> make_pair (T1 x, T2 y)
{
return ( pair<T1,T2>(x,y) );
}
3.3map类的增删查
insert()的使用:
#include <iostream>
#include <string>
#include <set>
#include <map>
using namespace std;
int main()
{
//利用初始化列表进行插入
// map<string, string> dict = { {"left", "左边"}, {"right", "右边"},
// {"insert", "插⼊"},{ "string", "字符串" } };
map<string, string> dict;
//插入有名对象
pair<string, string> kv1("first", "第一个");
dict.insert(kv1);
//插入匿名对象
dict.insert(pair<string, string>("second", "第二个"));
//调用库里面的函数构建pair
dict.insert(make_pair("sort", "排序"));
//C++11
//多参数隐式类型转换
dict.insert({ "auto", "自动的" });
//不会更新,插入的时候只看key相不相等,key相等不插入
dict.insert({ "auto", "自动的XXXX" });
map<string, string>::iterator it = dict.begin();
while (it != dict.end())
{
//可以修改value,不支持修改key
//it->first += 'x';
it->second += 'x';
//cout << (*it).first << ":" << (*it).second << endl;
cout << it.operator->()->first << ":" << it.operator->()->second << endl;
++it;
}
cout << endl;
return 0;
}
注:查找和删除都只与Key有关,所以这里和set基本类似,不过多进行介绍。
下面给出部分接口的使用说明:
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存在则插⼊失败,key存在相等value不相等也会插⼊失败
pair<iterator,bool> insert (const value_type& val);
// 列表插⼊,已经在容器中存在的值不会插⼊
void insert (initializer_list<value_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);
// 删除k,k不存在返回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;
3.4map的数据修改
前⾯我提到map⽀持修改mapped_type(T类型的数据)数据,不⽀持修改key数据,修改关键字数据,破坏了底层搜索树的结构。map第⼀个⽀持修改的⽅式时通过迭代器,迭代器遍历时或者find返回key所在的iterator修改,map还有⼀个⾮常重要的修改接⼝operator[],但是operator[]不仅仅⽀持修改,还⽀持插⼊数据和查找数据,所以他是⼀个多功能复合接⼝需要注意从内部实现⻆度,map这⾥把我们传统说的value值,给的是T类型,typedef为mapped_type。⽽value_type是红⿊树结点中存储的pair键值对值。⽇常使⽤我们还是习惯将这⾥的T映射值叫做value。
这里主要介绍operator[]进行数据修改的几种情况:
int main()
{
map<string, string> dict;
dict.insert(make_pair("sort", "排序"));
//key不存在 -> 插入 {"insert", string()}
dict["insert"];
//key不存在 -> 插入+修改
dict["left"] = "左边";
//key存在 -> 修改
dict["left"] = "左边, 剩余";
//确定key在时 -> 查找
cout << dict["left"] << endl;
//key不在 -> 插入{"sort", string()}
cout << dict["right"] << endl;
return 0;
}
所以使用operator[]进行查找的时候要注意,如果要查找的数据不存在,则使用operator[]进行查找时会插入数据。
3.5operator[]的内部实现
operator[]是插入,查找,修改三个功能的复合接口。要实现operator[]必须把insert()函数了解清楚。
insert()函数单值插入的函数说明:
pair<iterator,bool> insert (const value_type& val);
insert插⼊⼀个pair<key, T>对象
1、如果key已经在map中,插⼊失败,则返回⼀个pair<iterator,bool>对象,返回pair对象
first是key所在结点的迭代器,second是false。
2、如果key不在在map中,插⼊成功,则返回⼀个pair<iterator,bool>对象,返回pair对象
first是新插⼊key所在结点的迭代器,second是true。
也就是说⽆论插⼊成功还是失败,返回pair<iterator,bool>对象的first都会指向key所在的迭代器。那么也就意味着insert插⼊失败时充当了查找的功能,正是因为这⼀点,insert可以⽤来实现operator[]。需要注意的是这⾥有两个pair,不要混淆了,⼀个是map底层红⿊树节点中存的pair<key, T>,另⼀个是insert返回值pair<iterator,bool>。
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.6map的迭代器和operator[]功能样例
利⽤find和iterator修改功能,统计⽔果出现的次数:
// 利⽤find和iterator修改功能,统计⽔果出现的次数
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
string arr[] = { "苹果", "西瓜", "苹果", "西瓜", "苹果", "苹果", "西瓜",
"苹果", "香蕉", "苹果", "香蕉" };
map<string, 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;
}
上述循环体中可以替换成下列一行代码:
int main()
{
string arr[] = { "苹果", "西瓜", "苹果", "西瓜", "苹果", "苹果", "西瓜",
"苹果", "香蕉", "苹果", "香蕉" };
map<string, int> countMap;
for (const auto& str : arr)
{
countMap[str]++;
}
for (const auto& e : countMap)
{
cout << e.first << ":" << e.second << endl;
}
cout << endl;
return 0;
}
此行代码的意思是:先对str进行查找,如果在countMap中,对返回mapped_value(次数)进行++操作,如果str不在countMap中,则插入pair<str, 0>的键值对,然后对返回的mapped_value(此时为新插入的键值对,次数为0)进行++操作,将次数变为1。
3.7multimap和map的差异
multimap和map的使⽤基本完全类似,主要区别点在于multimap⽀持关键值key冗余,那么insert/find/count/erase都围绕着⽀持关键值key冗余有所差异,这⾥跟set和multiset完全⼀样,⽐如find时,有多个key,返回中序第⼀个。其次就是multimap不⽀持[],因为⽀持key冗余,[]就只能⽀持插⼊了,不能⽀持修改,如果支持修改的话,就不能确定修改的是哪个Key对应的value值了。