一、前言

:maple_leaf:Map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称为该关键字的值)的数据 处理能力,由于这个特性,它完成有可能在我们处理一对一数据的时候,在编程上提供快速通道。这里说下map内部数据的组织,map内部自建一颗红黑树(一 种非严格意义上的平衡二叉树),这颗树具有对数据自动排序的功能,所以在map内部所有的数据都是有序的,后边我们会见识到有序的好处。

二、map简介

map是一类关联式容器。它的特点是增加和删除节点对迭代器的影响很小,除了那个操作节点,对其他的节点都没有什么影响。对于迭代器来说,可以修改实值,而不能修改key。map的所有元素都是pair,同时具备key和value,其中pair的第一个元素作为key,第二个元素作为value。map不允许相同key出现,并且所有pair根据key来自动排序。

1. map的功能

自动建立Key-value的对应。key 和 value可以是任意你需要的类型。

根据key值快速查找记录,查找的复杂度基本是Log(N),如果有1000个记录,最多查找10次,1,000,000个记录,最多查找20次。

  • 快速插入Key -Value 记录。

  • 快速删除记录

  • 根据Key 修改value记录。

  • 遍历所有记录。

2. map的基本操作函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//map的基本操作函数:

//C++ maps是一种关联式容器,包含“关键字/值”对
begin() 返回指向map头部的迭代器

clear() 删除所有元素

count() 返回指定元素出现的次数

empty() 如果map为空则返回true

end() 返回指向map末尾的迭代器

equal_range() 返回特殊条目的迭代器对

erase() 删除一个元素

find() 查找一个元素

get_allocator() 返回map的配置器

insert() 插入元素

key_comp() 返回比较元素key的函数

lower_bound() 返回键值>=给定元素的第一个位置

max_size() 返回可以容纳的最大元素个数

rbegin() 返回一个指向map尾部的逆向迭代器

rend() 返回一个指向map头部的逆向迭代器

size() 返回map中元素的个数

swap() 交换两个map

upper_bound() 返回键值>给定元素的第一个位置

value_comp() 返回比较元素value的函数

3. map的使用

包含头文件

#include <map> //注意,STL头文件没有扩展名.h

map对象是模板类,需要关键字和存储对象两个模板参数:

std:map<int,string> personnel;

这样就定义了一个用int作为索引,并拥有相关联的指向string的指针.

为了使用方便,可以对模板类进行一下类型定义,

typedef map<int,CString> UDT_MAP_INT_CSTRING;

UDT_MAP_INT_CSTRING enumMap;

:warning:注意事项

  • map的赋值运算是深拷贝,即调用map_a = map_b后,map_a中的元素拥有独立的内存空间。
  • map的[]运算比较有意思,当元素不存在的时候会插入新的元素。在下面数据的插入中有使用到。
  • 在map中查找key是否存在时可以用find或count方法,find查找成功返回的是迭代器,查找失败则返回mymap.end(),说明该key不存在。map中的key不允许重复,故其count方法只能返回0或1。
  • 由于STL是一个统一的整体,map的很多用法都和STL中其它的东西结合在一起,比如在排序上,这里默认用的是小于号,即less<>,如果要从大到小排序呢,这里涉及到的东西很多,在此无法一一加以说明。
  • 还要说明的是,map中由于它内部有序,由红黑树保证,因此很多函数执行的时间复杂度都是log2N的,如果用map函数可以实现的功能,而STL Algorithm也可以完成该功能,建议用map自带函数,效率高一些。
  • 下面说下,map在空间上的特性,否则,估计你用起来会有时候表现的比较郁闷,由于map的每个数据对应红黑树上的一个节点,这个节点在不保存你的 数据时,是占用16个字节的,一个父节点指针,左右孩子指针,还有一个枚举值(标示红黑的,相当于平衡二叉树中的平衡因子),所以这些地方,很费内存…

三、map的基本使用

1.数据插入

  • 使用insert函数插入pair数据
  • 用insert函数插入value_type数据
  • 使用数组的方式插入数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <map>
#include <string>
#include <iostream>
using namespace std;

int main()

{
// 数据的插入--第一种:用insert函数插入pair数据
map<int, string> mapStudent;
mapStudent.insert(pair<int, string>(1, "student_one"));
mapStudent.insert(pair<int, string>(2, "student_two"));
mapStudent.insert(pair<int, string>(3, "student_three"));

// 第二种:用insert函数插入value_type数据

mapStudent.insert(map<int, string>::value_type(4, "student_four"));
mapStudent.insert(map<int, string>::value_type(5, "student_five"));
mapStudent.insert(map<int, string>::value_type(6, "student_six"));

// 第三种:用数组方式插入数据,map会自动排序
mapStudent[10] = "student_one";
mapStudent[8] = "student_two";
mapStudent[9] = "student_three";

map<int, string>::iterator iter;
for (iter = mapStudent.begin(); iter != mapStudent.end(); iter++)

cout << iter->first << ' ' << iter->second << endl;

}

程序运行的结果:

1
2
3
4
5
6
7
8
9
1 student_one
2 student_two
3 student_three
4 student_four
5 student_five
6 student_six
8 student_two
9 student_three
10 student_one

2.数据的遍历

  • 应用前向迭代器
  • 应用反相迭代器
  • 使用数组的形式

可以用size函数查看map中插入了多少数据,比如说:

Int nSize = mapStudent.size();

参考下面代码对数据进行遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <map>
#include <string>
#include <iostream>
using namespace std;

int main()

{

map<int, string> mapStudent;
mapStudent.insert(pair<int, string>(1, "student_one"));
mapStudent.insert(pair<int, string>(2, "student_two"));
mapStudent.insert(pair<int, string>(3, "student_three"));

// 数据的遍历--第一种:应用前向迭代器
map<int, string>::iterator iter;
for (iter = mapStudent.begin(); iter != mapStudent.end(); iter++)

cout << iter->first << ' ' << iter->second << endl;
// 数据的遍历--第二种:应用反向迭代器
map<int, string>::reverse_iterator r_iter;

for (r_iter = mapStudent.rbegin(); r_iter != mapStudent.rend(); r_iter++)

cout << r_iter->first << " " << r_iter->second << endl;
// 数据的遍历--第三种:使用数组的形式
int nSize = mapStudent.size();

// 此处应注意,应该是 for(int nindex = 1; nindex <= nSize; nindex++)
// 而不是 for(int nindex = 0; nindex < nSize; nindex++),这是因为定义的mapStudent中key是1,2,3
for (int nindex = 1; nindex <= nSize; nindex++)

cout << mapStudent[nindex] << endl;

return 0;
}

运行输出结果:

1
2
3
4
5
6
7
8
9
1 student_one
2 student_two
3 student_three
3 student_three
2 student_two
1 student_one
student_one
student_two
student_three

3.查找并获取map中的元素

同时也包括判定这个关键字是否在map中出现

在这里我们将体会,map在数据插入时保证有序的好处。

要判定一个数据(关键字)是否在map中出现的方法比较多,这里标题虽然是数据的查找,在这里将穿插着大量的map基本用法。

这里给出三种数据查找方法

  • 用count函数来判定关键字是否出现,其缺点是无法定位数据出现位置,由于map的特性,一对一的映射关系,就决定了count函数的返回值只有两个,要么是0,要么是1,出现的情况,当然是返回1了

  • 用find函数来定位数据出现位置,它返回的一个迭代器,当数据出现时,它返回数据所在位置的迭代器,如果map中没有要查找的数据,它返回的迭代器等于end函数返回的迭代器。查找map中是否包含某个关键字条目用find()方法,传入的参数是要查找的key,在这里需要提到的是begin()和end()两个成员,分别代表map对象中第一个条目和最后一个条目,这两个数据的类型是iterator.通过map对象的方法获取的iterator数据类型是一个std::pair对象,包括两个数据 iterator->first和 iterator->second分别代表关键字和存储的数据。

  • lower_bound函数用法,这个函数用来返回要查找关键字的下界(是一个迭代器),指向首个大于等于value的值

    upper_bound函数用法,这个函数用来返回要查找关键字的上界(是一个迭代器).指向首个大于value的值

    例如:map中已经插入了1,2,3,4的话,如果lower_bound(2)的话,返回的2,而upper_bound(2)的话,返回的就是3。

    Equal_range函数返回一个pair,pair里面第一个变量是Lower_bound返回的迭代器,pair里面第二个迭代器是Upper_bound返回的迭代器,如果这两个迭代器相等的话,则说明map中不出现这个关键字。

程序说明:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <map>
#include <string>
#include <iostream>
using namespace std;

int main()
{

map<int, string> mapStudent;

mapStudent.insert(pair<int, string>(1, "student_one"));

mapStudent.insert(pair<int, string>(3, "student_three"));

mapStudent.insert(pair<int, string>(5, "student_five"));

// 数据的查找--第一种:利用count函数查找,但无法定位数据的位置
if (mapStudent.count(1))
cout << " The Key 1 is present " << endl;
else
cout << " The Key 1 is not present " << endl;

// 数据的查找--第二种:利用find函数查找
map<int, string>::iterator iter;
iter = mapStudent.find(1);

if (iter != mapStudent.end())
cout << "Find, the value is " << iter->second << endl;
else
cout << "Do not Find" << endl;

// 数据的查找--第三种:利用equal_range
// lower_bound,指向首个大于等于value的值
// upper_bound,指向首个大于value的值
// https://www.cnblogs.com/cherishui/p/16924108.html
// 用于multimap中作用比较大
// https://blog.csdn.net/w_weixiaotao/article/details/107191365

iter = mapStudent.lower_bound(1);
// 返回的是下界1的迭代器
cout << iter->second << endl;
iter = mapStudent.lower_bound(2);
// 返回的是下界3的迭代器
cout << iter->second << endl;
iter = mapStudent.lower_bound(3);
// 返回的是下界3的迭代器
cout << iter->second << endl;
iter = mapStudent.upper_bound(2);
// 返回的是上界3的迭代器
cout << iter->second << endl;
iter = mapStudent.upper_bound(3);
// 返回的是上界5的迭代器
cout << iter->second << endl;
pair<map<int, string>::iterator, map<int, string>::iterator> mappair;
mappair = mapStudent.equal_range(2);
if (mappair.first == mappair.second)
cout << "Do not Find" << endl;
else
cout << "Find" << endl;
mappair = mapStudent.equal_range(3);
if (mappair.first == mappair.second)
cout << "Do not Find" << endl;
else
cout << "Find" << endl;
return 0;
}

运行输出结果:

1
2
3
4
5
6
7
8
9
The Key 1 is present 
Find, the value is student_one
student_one
student_three
student_three
student_three
student_five
Do not Find
Find

4.从map中删除数据

移除某个map中某个条目用erase()

该成员方法的定义如下:

iterator erase(iterator it);//通过一个条目对象删除

iterator erase(iterator first,iterator last)//删除一个范围

size_type erase(const Key&key);//通过关键字删除

clear()就相当于enumMap.erase(enumMap.begin(),enumMap.end());

这里要用到erase函数,它有三个重载了的函数,下面在例子中详细说明它们的用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <map>  

#include <string>

#include <iostream>

using namespace std;

void show(const char *msg, map<int, string> mp);
int main()

{

map<int, string> mapStudent;
mapStudent.insert(pair<int, string>(1, "student_one"));
mapStudent.insert(pair<int, string>(2, "student_two"));
mapStudent.insert(pair<int, string>(3, "student_three"));
mapStudent.insert(pair<int, string>(4, "student_four"));
mapStudent.insert(pair<int, string>(5, "student_five"));
show("Contents of mapStudent",mapStudent);

// 用迭代器删除4

map<int, string>::iterator iter;

iter = mapStudent.find(4);

mapStudent.erase(iter);
show("Contents of mapStudent delete 4",mapStudent);

// 用关键字删除1

int n = mapStudent.erase(1); // 如果删除了会返回1,否则返回0
cout <<n <<endl ;
show("Contents of mapStudent delete 1",mapStudent);
// 用迭代器,成片的删除

// 一下代码把整个map清空

mapStudent.erase(mapStudent.begin(), mapStudent.end());

// 成片删除要注意的是,也是STL的特性,删除区间是一个前闭后开的集合

show("Contents of mapStudent delte all",mapStudent);
}

// Display the contents of a map<string, int> by using an iterator.
void show(const char *msg, map<int, string> mp)
{
map<int, string>::iterator itr;

cout << msg << endl;
for (itr = mp.begin(); itr != mp.end(); ++itr)
cout << " " << itr->first << ", " << itr->second << endl;
}

运行输出结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Contents of mapStudent
1, student_one
2, student_two
3, student_three
4, student_four
5, student_five
Contents of mapStudent delete 4
1, student_one
2, student_two
3, student_three
5, student_five
1
Contents of mapStudent delete 1
2, student_two
3, student_three
5, student_five
Contents of mapStudent delte all

5.map中swap用法

map中的swap不是一个容器中的元素交换,而是两个容器所有元素的交换。是用来交换两个map中的内容。
程序说明:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <map>
#include <string>
#include <iostream>
using namespace std;
void show(const char *msg, map<string, int> mp);
int main()
{
map<string, int> m1, m2;

m1.insert(pair<string, int>("A", 100));
m1.insert(pair<string, int>("G", 300));
m1.insert(pair<string, int>("B", 200));

m2.insert(pair<string, int>("H", 500));
m2.insert(pair<string, int>("J", 600));
// Exchange the contents of m1 and m2.
cout << "Exchange m1 and m2.\n";
m1.swap(m2);
show("Contents of m2:", m2);
show("Contents of m1:", m1);
// Exchange the contents of m1 and m2.
cout << "Exchange m1 and m2 again.\n";
swap(m1, m2);
show("Contents of m2:", m2);
show("Contents of m1:", m1);
// Clear m1.
m1.clear();
if (m1.empty())
cout << "m1 is now empty.";

return 0;
}

// Display the contents of a map<string, int> by using an iterator.
void show(const char *msg, map<string, int> mp)
{
map<string, int>::iterator itr;

cout << msg << endl;
for (itr = mp.begin(); itr != mp.end(); ++itr)
cout << " " << itr->first << ", " << itr->second << endl;
cout << endl;
}

运行输出结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Exchange m1 and m2.
Contents of m2:
A, 100
B, 200
G, 300

Contents of m1:
H, 500
J, 600

Exchange m1 and m2 again.
Contents of m2:
H, 500
J, 600

Contents of m1:
A, 100
B, 200
G, 300

m1 is now empty.

###6.map使用中的一些注意事项
####map的插入注意事项:
上文中提到三种插入方式:

  • 用insert函数插入pair数据

  • 用insert函数插入value_type数据

  • 用数组方式插入数据

以上三种用法,虽然都可以实现数据的插入,但是它们是有区别的,当然了第一种和第二种在效果上是完成一样的,用insert函数插入数据,在数据的插入上涉及到集合的唯一性这个概念,即当map中有这个关键字时,insert操作是插入数据不了的,但是用数组方式就不同了,它可以覆盖以前该关键字对应的值。

1
2
mapStudent.insert(map<int, string>::value_type (1, "student_one"));
mapStudent.insert(map<int, string>::value_type (1, "student_two"));

上面这两条语句执行后,map中1这个关键字对应的值是“student_one”,第二条语句并没有生效,那么这就涉及到我们怎么知道insert语句是否插入成功的问题了,可以用pair来获得是否插入成功,程序如下

1
2
3
pair<map<int, string>::iterator, bool> Insert_Pair;

Insert_Pair = mapStudent.insert(map<int, string>::value_type (1, "student_one"));

我们通过pair的第二个变量来知道是否插入成功,它的第一个变量返回的是一个map的迭代器,如果插入成功的话Insert_Pair.second应该是true的,否则为false。

下面是代码进行验证:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// 验证插入函数的作用效果
#include <map>
#include <string>
#include <iostream>
using namespace std;

int main()

{
map<int, string> mapStudent;
pair<map<int, string>::iterator, bool> Insert_Pair;
Insert_Pair = mapStudent.insert(pair<int, string>(1, "student_one"));
if (Insert_Pair.second == true)
cout << "Insert Successfully" << endl;
else
cout << "Insert Failure" << endl;
Insert_Pair = mapStudent.insert(pair<int, string>(1, "student_two"));
if (Insert_Pair.second == true)
cout << "Insert Successfully" << endl;
else
cout << "Insert Failure" << endl;
map<int, string>::iterator iter;
for (iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
cout << iter->first << ' ' << iter->second << endl;
cout << endl;
// 数组插入在数据覆盖上的效果
mapStudent[1] = "student_five";
mapStudent[2] = "student_three";
for (iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
cout << iter->first << ' ' << iter->second << endl;
}

6.map中的sort问题

map中的元素是自动按Key升序排序,所以不能对map用sort函数;

这里要讲的是一点比较高深的用法了,排序问题,STL中默认是采用小于号来排序的,以上代码在排序上是不存在任何问题的,因为上面的关键字是int 型,它本身支持小于号运算,在一些特殊情况,比如关键字是一个结构体,涉及到排序就会出现问题,因为它没有小于号操作,insert等函数在编译的时候过 不去,下面给出两个方法解决这个问题。

  • 第一种:小于号重载。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <string>
#include <map>
using namespace std;

typedef struct tagStudentinfo
{
int niD;
string strName;
bool operator<(tagStudentinfo const &_A) const
{ // 这个函数指定排序策略,按niD排序,如果niD相等的话,按strName排序
if (niD < _A.niD)
return true;
if (niD == _A.niD)
return strName.compare(_A.strName) < 0;
return false;
}

} Studentinfo, *PStudentinfo; // 学生信息

int main()
{
int nSize; // 用学生信息映射分数
map<Studentinfo, int> mapStudent;
map<Studentinfo, int>::iterator iter;
Studentinfo studentinfo;
studentinfo.niD = 3;
studentinfo.strName = "student_three";
mapStudent.insert(pair<Studentinfo, int>(studentinfo, 98));
studentinfo.niD = 1;
studentinfo.strName = "student_one";
mapStudent.insert(pair<Studentinfo, int>(studentinfo, 90));
studentinfo.niD = 2;
studentinfo.strName = "student_two";
mapStudent.insert(pair<Studentinfo, int>(studentinfo, 80));
for (iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
cout << iter->first.niD << ' ' << iter->first.strName << ' ' << iter->second << endl;
return 0;
}

程序运行结果:

1
2
3
1 student_one 90
2 student_two 80
3 student_three 98
  • 第二种:仿函数的应用,这个时候结构体中没有直接的小于号重载。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
 #include <iostream>
#include <map>
#include <string>
using namespace std;

typedef struct tagStudentinfo
{
int niD;
string strName;
} Studentinfo, *PStudentinfo; // 学生信息

class sort
{
public:
bool operator()(Studentinfo const &_A, Studentinfo const &_B) const
{
if (_A.niD < _B.niD)
return true;
if (_A.niD == _B.niD)
return _A.strName.compare(_B.strName) < 0;
return false;
}
};

int main()
{ // 用学生信息映射分数
map<Studentinfo, int, sort> mapStudent;
map<Studentinfo, int>::iterator iter;
Studentinfo studentinfo;


studentinfo.niD = 3;
studentinfo.strName = "student_three";
mapStudent.insert(pair<Studentinfo, int>(studentinfo, 98));
studentinfo.niD = 1;
studentinfo.strName = "student_one";
mapStudent.insert(pair<Studentinfo, int>(studentinfo, 90));
studentinfo.niD = 2;
studentinfo.strName = "student_two";
mapStudent.insert(pair<Studentinfo, int>(studentinfo, 80));

for (iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
cout << iter->first.niD << ' ' << iter->first.strName << ' ' << iter->second << endl;
}

程序运行结果:

1
2
3
1 student_one 90
2 student_two 80
3 student_three 98

参考链接

本文整理和修改自以下的链接

https://blog.csdn.net/YGG12022/article/details/124042366
https://blog.csdn.net/shawn_hou/article/details/38035577#
std::map原理