map是STL的一个关联容器,它提供一对一的hash(哈希表,即一个关键字对应一个值)。如下图
- 第一个可以称为关键字(key),每个关键字只能在map中出现一次;
- 第二个可称为该关键字的值(value);

#include <map>
// 定义一个map对象
map<int, string> mapStudent;
// 第一种 用insert函數插入pair
mapStudent.insert(pair<int, string>(000, "student_zero"));
// 第二种 用insert函数插入value_type数据
mapStudent.insert(map<int, string>::value_type(001, "student_one"));
// 第三种 用"array"方式插入
mapStudent[123] = "student_first";
mapStudent[456] = "student_second";
map中count与find?
int mapstudent.sort(keyvalue);//关键字出现的次数,因map中关键字没有重复,所以只会返回0或1
iterator mapstudent.find(keyvalue);//关键字在map内的位置,以迭代器的形式返回,不存在则返回i
//end(),一般作以下用:
map<string,int>::iterator iter=mapstudent.find("China");//查找是否有关键字"China",返回一个迭代器
if(iter!=mapstudent.end())
cout<<iter->second<<endl;//找到了,输出关键字"China"对应的int值
|