[STL]map的使用

map是一种类型对另外一种类型的映射,主要用于快速查找。STL普通的map是用红黑树实现的,最坏的查找复杂度为log2n。STL也提供使用hashtable实现的map,hash_map。

1、创建

map<string,int> stringint;

2、插入

stringint["abc"]=5;

3、查找,查看元素是否存在

if(stingint.end()!=stingint.find("xx")){  //STL一贯风格
            cout<<"has xx"<<endl;
}

也可以简单的使用count来判断元素是否存在,在map,count的结果只能是0或者1

stringint.count("xx");

4、删除元素

map<string,int>::iterator it=stringint.find("xx");
if(it!=stringint.end()){  //STL一贯风格
        stringint.erase(it);
}

5、交换两个map,注意是两个都交换

map1.swap(map2);

6、map的遍历

map可以通过size来得到总元素个数,然后使用for循环遍历

int i=stringint.size();

也可以使用STL的迭代器形式

map<string,int>::iterator it;
for(it=stringint.begin();it!=stringint.end();++it){
}

  总结来说,map就是一个映射,可以当做hashtable使用,它的效率比hash稳定。hash最好是O1,最坏是On。它的使用格式符合STL的一贯习惯。

原文地址:https://www.cnblogs.com/iyjhabc/p/3281565.html