STL库map
发表于:2024-12-21 | 分类: C++
字数统计: 766 | 阅读时长: 4分钟 | 阅读量:

map

构造

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <map> // 头文件

using namespace std;

int main()
{
// 初始化空 map
map<int, string> m1;

// 使用初始化列表
map<int, string> m2 = {{1, "one"}, {2, "two"}, {3, "three"}};

// 使用拷贝构造函数
map<int, string> m3(m2);

// 使用范围构造函数
map<int, string> m4(m2.begin(), m2.end());

return 0;
}

api

基本

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
#include <iostream>
#include <map>

using namespace std;

int main()
{
// 使用初始化列表
map<int, int> m2 = {{1, 1}, {2, 2}, {3, 3}};

// 插入元素,pair需要指定类型,make_pair自动推导类型
m2.insert(pair<int, int>(4, 4));
m2.insert(make_pair(5, 5));

// 查看容量
cout << "当前容量: " << m2.size() << endl;

// 访问元素,如果不存在,会插入默认值,[key]
cout << m2[1] << endl;
cout << m2[2] << endl;
cout << m2[3] << endl;
cout << m2[4] << endl;
cout << m2[5] << endl;
cout << m2[6] << endl; // 不存在,a[6]=0

cout << "当前容量: " << m2.size() << endl;

// 单纯访问元素,会越界检查,传入key
cout << m2.at(6) << endl; // 0
// cout << m2.at(7) << endl; // 越界

// 删除元素,参数为key
m2.erase(6);

// find查找元素,返回值为迭代器(可以访问元素)
auto it = m2.find(3);
if (it != m2.end())
{
cout << "find查找存在,key为:" << it->first << ",value为:" << it->second << endl;
}
else
{
cout << "find查找不存在" << endl;
}

// count查找元素,只能返回0或1
if (m2.count(3))
{
cout << "m2.count(3)查找存在" << endl;
}
return 0;
}

遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <map>

using namespace std;

int main()
{
// 使用初始化列表
map<int, int> m2 = {{1, 1}, {2, 2}, {3, 3}};

// c++11遍历
for (auto &item : m2)
{
cout << item.first << " " << item.second << endl;
}
cout << endl;

// 迭代器遍历
for (auto it = m2.begin(); it != m2.end(); it++)
{
cout << it->first << " " << it->second << endl;
}
return 0;
}

排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <map>
using namespace std;

// 自定义比较函数,降序排列
struct CustomCompare {
bool operator()(int a, int b) const {
return a > b; // 降序
}
};

int main() {
map<int, int, CustomCompare> m = {{1, 10}, {2, 20}, {3, 30}};

for (const auto& pair : m) {
cout << pair.first << ": " << pair.second << endl;
}
return 0;
}

并发修改

问题依旧在,参考vector和list,it也不能运算。下方是正确方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <map>

using namespace std;

int main()
{
// 使用初始化列表
map<int, int> m2 = {{1, 1}, {2, 1}, {3, 1}, {4, 2}};

// 迭代器遍历删除
for (auto it = m2.begin(); it != m2.end();)
{
if (it->second == 1)
{
it = m2.erase(it); // 注意返回
}
else
{
++it;
}
}
return 0;
}

底层原理

红黑树

上一篇:
STL库set
下一篇:
STL库list