C++标准库中map是一个关联容器,它按键值对进行存储和访问。map中的元素按照键自动排序,并且每个键必须是唯一的。map提供了高效的查找功能,可以通过键来访问对应的值。
一.使用前的准备工作:
#include<map>
using namespace std;
std::map<int, std::string> mymap; // 创建一个空的 map 对象
二.常用set类的成员函数:
1 | mymap.insert(std::make_pair(key, value)) | 在map 中插入键值对 |
2 | mymap[]或者mymap.find() |
|
3 | mymap.erase(key) | 删除指定键的键值对 |
4 | mymap.find(key) | 查找具有给定键的元素,并返回一个迭代器。 |
三.代码示例:
1.insert():
mymap.insert(std::make_pair(key, value)); // 插入一个键值对
// 或者使用下标运算符[]
myMap[key] = value;
2.[]或者find():
ValueType value = myMap[key]; // 通过键获取对应的值
// 或者使用find函数来判断键是否存在
auto it = myMap.find(key);
if (it != myMap.end())
{
// 键存在,通过 it->first 获取键,it->second 获取值
ValueType value = it->second;
}
else
{
// 键不存在
}
3.erase(key):
map<int, string> map = {
{1, "yuga"},
{2, "suga"},
{3, "john"},
};
map.erase(1);
if (map.find(1) == map.end())
{
printf("没有该键值对");
}
else
{
printf("%s\n", map.find(1)->second.c_str());
}
//输出:
没有该键值对
4.find(key):
#include <map>
#include <stdio.h>
#include <string>
using namespace std;
int main()
{
map<int, string> map = {
{1, "yuga"},
{2, "suga"},
{3, "john"},
};
printf("%s\n", map.find(1)->second.c_str());
printf("%s\n", map.find(2)->second.c_str());
printf("%s\n", map.find(3)->second.c_str());
return 0;
}
//输出:
yuga
suga
john
注意:
1.map.find(key)返回一个迭代器,该迭代器指向键为 key 的元素。
2.使用箭头运算符->对迭代器进行连续访问,获取该元素的second成员(即value值)。
first为key值,second为value的值
3.因为代码中value为string类的对象,若要获取字符串,使用c_str()方法将值转换为以 null 终止的 C 字符串。如果value是int就不用加c_str()了。
,