map
是 C++ 标准模板库(STL)中的关联容器,用于存储键值对(key-value pairs)。每个元素是一个包含两个值的 pair 对象,一个是键(key),另一个是对应的值(value)。map
中的键值对是唯一的,且按照键的升序顺序进行排序。
特点:
-
键值对存储:
map
存储键值对,每个键都关联一个值。 -
唯一键:
map
中的键是唯一的,每个键只能出现一次。 -
按键排序:
map
中的键值对按照键的升序顺序进行排序,默认情况下使用键的比较运算符进行排序。 -
动态操作:可以动态地插入和删除键值对,
map
会自动维护键的有序性
- map的定义
map<typename1, typename2> mp;
map需要确定映射前类型和映射后类型,所以需要在<>内填写两个类型,第一个是键的类型,第二个是值的类型。
注:如果是字符串到整型的映射,必须使用string而不能使用char数组。
map<string, int> mp;
- map容器内元素的访问
map可以通过下标访问或通过迭代器访问。
(1)通过下标访问
#include <iostream>
#include <map>
using namespace std;
map<char, int> mp;
int main()
{
mp['a']=1;
mp['c']=2;
cout<<mp['c'];
return 0;
}
输出结果:
2
(2)通过迭代器访问
map迭代器的定义:
map<typename1, typename2>::iterator it;
map可以使用it->first来访问键,使用it->second来访问值。
实例:
#include <iostream>
#include <map>
using namespace std;
map<char, int> mp;
int main()
{
mp['a']=1;
mp['c']=2;
mp['b']=3;
for(map<char, int>::iterator it=mp.begin();it!=mp.end();it++){
cout<<it->first<<" "<<it->second<<endl;
}
return 0;
}
输出结果:
a 1
b 3
c 2
从上面例子我们可以看出,map会以键从小到大的顺序自动排序。这是由于map内部是使用红黑树实现的(set也是)。
- map常用函数
(1)find()
find(key)返回键值为key的映射的迭代器,时间复杂度为O(logN),N为map中映射的个数。
#include <iostream>
#include <map>
using namespace std;
map<char, int> mp;
int main()
{
mp['a']=1;
mp['c']=2;
mp['b']=3;
map<char, int>::iterator it=mp.find('c');
cout<<it->first<<" "<<it->second;
return 0;
}
输出结果:
c 2
(2)erase()
erase()可以删除单个元素,也可以删除一个区间的所有元素。
①删除单个元素
mp.erase(it),it为需要删除的元素的迭代器,时间复杂度为O(1)。
#include <iostream>
#include <map>
using namespace std;
map<char, int> mp;
int main()
{
mp['a']=1;
mp['c']=2;
mp['b']=3;
map<char, int>::iterator it=mp.find('c');
mp.erase(it);
for(map<char, int>::iterator it=mp.begin();it!=mp.end();it++){
cout<<it->first<<" "<<it->second<<endl;
}
return 0;
}
输出结果:
a 1
b 3
mp.erase(key),key为欲删除的映射的键。时间复杂度为O(logN),N为map内元素的个数。
#include <iostream>
#include <map>
using namespace std;
map<char, int> mp;
int main()
{
mp['a']=1;
mp['c']=2;
mp['b']=3;
mp.erase('c');
for(map<char, int>::iterator it=mp.begin();it!=mp.end();it++){
cout<<it->first<<" "<<it->second<<endl;
}
return 0;
}
输出结果:
a 1
b 3
②删除一个区间内的所有元素
#include <iostream>
#include <map>
using namespace std;
map<char, int> mp;
int main()
{
mp['a']=1;
mp['c']=2;
mp['b']=3;
map<char, int>::iterator it=mp.find('c'); //令it指向键为c的值
mp.erase(it, mp.end()); //删除it之后的所有映射
for(map<char, int>::iterator it=mp.begin();it!=mp.end();it++){
cout<<it->first<<" "<<it->second<<endl;
}
return 0;
}
输出结果:
a 1
b 3
(3)size()
size()用来获得map中映射的对数,时间复杂度为O(1)。
#include <iostream>
#include <map>
using namespace std;
map<char, int> mp;
int main()
{
mp['a']=1;
mp['c']=2;
mp['b']=3;
cout<<mp.size();
return 0;
}
输出结果:
3
(4)clear()
clear()用来清除map中的所有元素,时间复杂度为O(N)。
#include <iostream>
#include <map>
using namespace std;
map<char, int> mp;
int main()
{
mp['a']=1;
mp['c']=2;
mp['b']=3;
mp.clear(); //清空map
cout<<mp.size();
return 0;
}
输出结果:
0