map介绍
- 使用map得包含map类所在的头文件#include
- 定义一个mao对象
- map<string,int> mapTest;//用string作为索引,存储int对象
插入数据
- mapTest[“aaa”] = 100;
- mapTest.insert(map<string,int>::value_type(“bbb”,200));
- mapTest.insert(paif<string,int>(“ddd”,400));
- mapTest.insert(make_pair<string,int>(“ccc”,300));
查找与修改
- mapTest[“aaa”] = 100;
- map<string,int>::iterator it = mapTest.find(“aaa”);
- it->second = 666;
删除
- mapTest.erase(“aaa”);
- mapTest.erase(it);
#include <map>
#include <iostream>
using namespace std;
int main()
{
map<string,int> mapTest;
mapTest["aaa"] = 100;
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>::const_iterator it;
for(it=mapTest.begin();it!=mapTest.end();++it)
{
cout<<it->first<<" "<<it->second<<endl;
}
int n = mapTest["bbb"];
cout<<n<<endl;
mapTest["bbb"] = 2000;
map<string,int>::iterator it1;
it1 = mapTest.find("ccc");
if(it1 != mapTest.end())
{
it1->second = 3000;
}else{
cout<<"not found"<<endl;
}
for(it=mapTest.begin();it!=mapTest.end();++it)
{
cout<<it->first<<" "<<it->second<<endl;
}
mapTest.erase("bbb");
for(it=mapTest.begin();it!=mapTest.end();++it)
{
cout<<it->first<<" "<<it->second<<endl;
}
map<string,int>::iterator it2;
it2 = mapTest.find("ccc");
if(it2 != mapTest.end())
{
mapTest.erase(it2);
}else{
cout<<"not found"<<endl;
}
for(it=mapTest.begin();it!=mapTest.end();++it)
{
cout<<it->first<<" "<<it->second<<endl;
}
}