信奥竞赛

系列

剑指信奥 | C++ 之 STL - map

剑指信奥 | C++ 之 STL - map

独特的数据形式

到今天为止,我们已经学习了很多的 STL 容器模版:

  • string
  • vector
  • stack
  • queue
  • list
  • set

这些容器模版都可以存储数据,而且这些模版类里存储的数据都是某一种数据类型的单一值的形式。

今天,我们继续学习容器模版类,但这个模版类中的数据形式却有些特别,我们先来看三个单词的含义:

  1. map 映射
  2. key
  3. value

这里,第一个词 map 就是我们今天要学习的模版类。

那么 keyvalue 是什么意思呢,看下这张图:

map 的语法 | Educative

这张图解析了 map 容器的语法,放在  map 中的每一个数据都分成了两个部分,一个部分是 key ,我们称之为 ,另外一个部分是 value,我们称之为

一个键总是和一个值是对应的关系,我们称之为 键值对 key-value pair,多个键值对放在一起,就构成了 映射 这样一个数据容器,这就是  map


map 的例子 | Educative

map 的初始化

先来看下  map 的初始化:

#include <iostream>
#include <map>

using namespace std;

int main() {

// map 声明
map<string, int> si;

cout << si.size() << endl;

return 0;
}

/*
output:
0
*/

这里,我们声明一个 map,通过声明,我们指定 key 是字符串,而 value 是整型,每个字符串都指向一个整型的数值。

map 的数据添加

现在,我们向这个 map 中存放几组数据。

#include <iostream>
#include <map>

using namespace std;

int main() {

map<string, int> si;

// insert 函数添加数据
si.insert(pair<string, int>("apple", 3));
si.insert(pair<string, int>("banana", 1));

// 键值表达式
si["watermelon"] = 3;

cout << si.size() << endl;

return 0;
}

/*
output:
3
*/

map 的添加数据很特别,需要先构造出一个 pair 对象,每个 pair 对象就是一个键值对,然后再使用 insert() 函数把键值对存放到 map 中。

或者可以采用键值对表达式的方式添加数据。

map 的数据访问

map 中有了数据后,怎么来访问数据呢,我们看示例代码:

#include <iostream>
#include <map>

using namespace std;

int main() {

map<string, int> si{{"apple", 3},
{"banana", 1},
{"watermelon", 3}};

// 输出键对应的值
cout << "watermelon: " << si.find("watermelon")->second << endl;

// map 的循环输出
for (const auto &item : si) {
cout << item.first << " : " << item.second << endl;
}

return 0;
}

/*
output:
watermelon: 3
apple : 3
banana : 1
watermelon : 3
*/

在这里,我们先是根据键访问了它所对应的值,然后又使用循环的方式输出了这个 map 中的每一对数据。

map 的数据修改

#include <iostream>
#include <map>

using namespace std;

int main() {

map<string, int> si{{"apple", 3},
{"banana", 1},
{"watermelon", 3}};

cout << "watermelon 1 : " << si.find("watermelon")->second << endl;

// 修改键对应的值
si["watermelon"] = 5;

cout << "watermelon 2 : " << si.find("watermelon")->second << endl;

return 0;
}

/*
output:
watermelon 1 : 3
watermelon 2 : 5
*/

在这里,我们把原来西瓜的数量 3 修改为了 5。

通过这个例子,不难发现在 map 中,键是唯一的,再次添加一个键值对,如果键是存在的,实际上是修改了这个键对应的值。

map 的数据删除

#include <iostream>
#include <map>

using namespace std;

int main() {

map<string, int> si{{"apple", 3},
{"banana", 1},
{"watermelon", 3}};

// 删除一个键值对
si.erase("watermelon");

cout << si.size() << endl;

// 清空 map
si.clear();

if (si.empty()) { // 判断 map 是否为空
cout << "map is empty." << endl;
}

return 0;
}

/*
output:
2
*/

在这里,我们使用 erase() 函数删除一个键值对,使用 clear() 清空这个 map,然后使用 empty() 判断这个 map 是否为空。

map 容器是 C++ STL 中关联容器中最为常用的一种,它提供了高效的数据存储和数据访问的功能。