一、C++ map类型简介
map【即:映射】是C++中的常见数据类型,其功能是创建从一种数据类型到另一种数据类型之间的映射关系(一对一),有点类似python中的字典。
定义map类型:
#include <map> // 类型头文件
using namespace std; // 标准命名空间
int main ()
{
// 开头的std::可省略
std::map<char,int> mymap; // 定义map类变量,char到int
std::map<int,int> mymap2; // 可以是相同数据类型间的映射
......
向map中添加新的映射对(两种方法):
// 添加映射对
mymap['a']=50;
mymap['b']=100;
mymap['c']=150;
mymap['d']=200;
mymap['e']=250;
// 继续插入映射对
mymap.insert({'f', 300});
mymap.insert({'g', 350});
二、map类型的常用方法
1、find() 方法
find()方法用于访问特定映射的值。
// 使用find()和->second访问映射的值
cout << "a => " << mymap.find('a')->second << endl;
cout << "b => " << mymap.find('b')->second << endl;
cout << "c => " << mymap.find('c')->second << endl;
cout << "d => " << mymap.find('d')->second << endl;
cout << "e => " << mymap.find('e')->second << endl;
cout << "f => " << mymap.find('f')->second << endl;
cout << "g => " << mymap.find('g')->second << endl;
2、size() 方法
size()方法返回map的大小(长度,即映射对的数量)。
// map的大小:size()方法
cout << mymap.size() << endl;
3、迭代器(iterator())方法
std::map<char,int>::iterator it; // 定义适配mymap数据类型的迭代器
// 使用迭代器访问映射的值
for(it = mymap.begin();it != mymap.end();it ++){
cout << it->first << " 映射到 ";
cout << it->second << endl;
}
三、相关代码
// 引用头文件
#include <iostream> // 输入输出流
#include <map> // 类型头文件
using namespace std; // 标准命名空间
int main ()
{
std::map<char,int> mymap; // 定义map类变量,char到int
std::map<int,int> mymap2; // 可以是相同数据类型间的映射
std::map<char,int>::iterator it; // 迭代器
// 添加映射对
mymap['a']=50;
mymap['b']=100;
mymap['c']=150;
mymap['d']=200;
mymap['e']=250;
// 继续插入映射对
mymap.insert({'f', 300});
mymap.insert({'g', 350});
// 使用find()和->second访问映射的值
cout << "a => " << mymap.find('a')->second << endl;
cout << "b => " << mymap.find('b')->second << endl;
cout << "c => " << mymap.find('c')->second << endl;
cout << "d => " << mymap.find('d')->second << endl;
cout << "e => " << mymap.find('e')->second << endl;
cout << "f => " << mymap.find('f')->second << endl;
cout << "g => " << mymap.find('g')->second << endl;
// map的大小:size()方法
cout << mymap.size() << endl;
// 使用迭代器访问映射的值
for(it = mymap.begin();it != mymap.end();it ++){
cout << it->first << " 映射到 ";
cout << it->second << endl;
}
return 0;
}
输出结果: