STL(Standard Template Library)标准模板库,是一个高效的C++程序库。
map是关联式容器(Associated containers),元素位置取决于特定的排序顺序,和插入的顺序无关,map的元素是成对的键值/实值,内部的元素依据其值自动排序,map内的相同数值的元素只能出现一次。
1、map定义
头文件#include <map>
map是模板类,可以直接定义类对象
std::map<int, string> map_lesson;
这样就定义了一个int索引,关联string的map对象。
为了方便,可以typedef进行定义
typedef std::map<int, string> MAP_UDT;
MAP_UDT map_lesson;
2、map的插入
(1) map重载了下标运算符
map_lesson[0] = "math";
map_lesson[1] = "english";
(2) insert插入
map_lesson.insert(std::map<int, string>::value_type(1, "physical"));
使用下表运算符时,当map_lesson中存在这个键值对,这个值会覆盖先前的值。还有一个性能问题,当没有主键为1对应的值,插入一个map对象,键为1,对应的键值为空字符串,然后将“physical“赋值过去,如果插入的元素为类对象时,开销较大。
3、map的查找
(1) 直接查找
std::string name = map_lesson[1];
...
(2) find
查找主键为1对应的键值
std::map<int, string>::iterator it = map_lesson.find(1);
if (it == map_lesson.end())
{
// not find
}
else
{
// find
}
当采用下标进行操作时,当map_lesson中没有该值时,会自动插入一个初始化值,采用find方法更可靠。
4、map删除
map删除采用erase函数
erase函数删除当前元素后,会将it指针向后移动一位。
iterator erase(iterator it);
5、map输出
最简单的方法:
std::map<int , string>::iterator it = map_lesson.begin();
for (; it != map_lesson.end(); it++)
{
cout<<it->first<<" "<<it->second<<endl;
}
6、小例子
#include <map>
#include <string>
#include <iostream>
using namespace std;
void map_print(map<int, string> map_temp)
{
map<int, string>::iterator it = map_temp.begin();
for (; it != map_temp.end(); it++)
{
cout<<it->first<<" "<<it->second<<endl;
}
cout<<endl;
}
int main()
{
map<int, string> map_lesson;
// insert
map_lesson.insert(map<int, string>::value_type(0, "english"));
map_lesson.insert(map<int, string>::value_type(1, "math"));
map_lesson.insert(map<int, string>::value_type(6, "chemistry"));
map_lesson.insert(map<int, string>::value_type(2, "physical"));
map_lesson.insert(map<int, string>::value_type(3, "china"));
map_print(map_lesson);
map<int, string>::iterator it;
// find
it = map_lesson.find(2);
if (it != map_lesson.end())
{
cout<<"find:";
cout<<it->first<<" "<<it->second<<endl;
cout<<"------------------"<<endl;
map_lesson.erase(it);
map_print(map_lesson);
}
else
{
cout<<"not find!"<<endl;
}
return 0;
}
运行结果:
0 english
1 math
2 physical
3 china
6 chemistry
find:2 physical
------------------
0 english
1 math
3 china
6 chemistry