标准库的map类型
使用map得包含map类所在的头文件
include < map >
定义一个map对象:
map
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
//插入到map容器内部的元素默认是按照key从小到大来排序。
//key类型一定要重载<运算符
map <string, int> mapTest;
mapTest["aaa"] = 100;
mapTest["eee"] = 500;
mapTest.insert(map<string, int>::value_type("bbb", 200));
mapTest.insert(pair<string,int>("ccc",300));
mapTest.insert(make_pair("ddd",400));
map<string, int>::iterator it;//const_iterator,则下面3000不能修改
it = mapTest.find("ccc");
if (it != mapTest.end())
{
it->second = 3000;
}
mapTest.erase("bbb");
//map<string, int>::const_iterator it;
it = mapTest.find("ccc");
if (it != mapTest.end())
{
mapTest.erase(it);
}
//map<string, int>::const_iterator it;
for (it = mapTest.begin(); it != mapTest.end(); ++it)
{
cout << it->first << " " << it->second << endl;
}
return 0;
}
输出:
aaa 100
ddd 400
eee 500