1 map的本质
(1)关联式容器,键值对应
(2)增加和删除节点对迭代器的影响很小。
(3)对于迭代器来说不可以修改键值,只能修改对应的实值。
(4)map内部数据的祖居是自建一颗红黑树(或者说是平衡二叉树),具有自动排序的功能。
2 map的查增删
(1)map的插入
1 #include <map> 2 #include <string> 3 #include <iostream> 4 using namespace std; 5 6 int main() 7 { 8 //方式一 pair 9 map<int,string> mapStudent; 10 mapStudent.insert(pair<int,string>(1,"lan")); 11 mapStudent.insert(pair<int,string>(2,"ji")); 12 mapStudent.insert(pair<int,string>(1,"kjh")); 13 map<int,string>::iterator iter; 14 map<int,string>::iterator iter1; 15 //方式二 16 map<int string> mapStudent1; 17 mapStudent1.insert(map<int,string>::value_type(1,"nihao")); 18 mapStudent1.insert(map<int,string>::value_type(1,"ben")); 19 for(iter=mapStudent.begin();iter!=mapStudent.end();iter++) 20 { 21 cout<<iter->first<<" "<<iter->second<<endl; 22 } 23 for(iter=mapStudent1.begin();iter!=mapStudent1.end();iter++) 24 { 25 cout<<iter->first<<" "<<iter->second<<endl; 26 27 } 28 return 0; 29 }
2 map的遍历
1 #include <map> 2 #include <string> 3 #include <iostream> 4 using namespace std; 5 6 int main() 7 { 8 map<int,string> mapStudent; 9 mapStudent[1]="stu_one"; 10 mapStudent[1]="stu_two"; 11 mapStudent[1]="stu_three"; 12 map<int,string>::iterator iter = mapStudent.find(1); 13 if(iter!=mapStudent.end()) 14 { 15 cout<<"找到了 value="<<iter->second<<endl; 16 }else 17 { 18 cout<<"没有找到"<<endl; 19 } 20 return 0; 21 }
3 map的删除
1 #include <map> 2 #include <string> 3 #include <iostream> 4 using namespace std; 5 6 int main() 7 { 8 map<int,string> mapStudent; 9 mapStudent[1]="stu_one"; 10 mapStudent[1]="stu_two"; 11 mapStudent[1]="stu_three"; 12 map<int,string>::iterator iter = mapStudent.begin(); 13 for(;iter!=mapStudent.end();) 14 { 15 if((*iter).sencond=="stu_one") 16 { 17 mapStudent.erase(iter++);//iter被erase以后就会失效 所以后面不能再有iter++ 18 }else 19 { 20 ++iter; 21 } 22 } 23 for(iter=mapStudent1.begin();iter!=mapStudent1.end();iter++) 24 { 25 cout<<iter->first<<" "<<iter->second<<endl; 26 27 } 28 return 0; 29 }
4 map排序
默认按照key从小到大。从大到小greater 相反less
1 #include <map> 2 #include <string> 3 #include <iostream> 4 using namespace std; 5 int main() 6 { 7 map<string,int,greater<string>> mapStudent; 8 mapStudent['nisan']=90; 9 mapStudent['nisan']=70; 10 mapStudent['nisan']=80; 11 map<string,int>::iterator iter = mapStudent.begin(); 12 for(iter=mapStudent.begin();iter!=mapStudent.end();iter++) 13 { 14 cout<<iter->first<<" "<<iter->second<<endl; 15 } 16 return 0; 17 }
自定义排序方式
1 #include <string> 2 #include <iostream> 3 using namespace std; 4 struct CmpByKeyLength 5 { 6 bool operator()(const string &k1,const string&k2){ 7 return k1.length()<k2.length(); 8 } 9 }; 10 int main() 11 { 12 map<string,int,CmpByKeyLength>mapStudent; 13 mapStudent['nisan']=90; 14 mapStudent['nisan']=70; 15 mapStudent['nisan']=80; 16 map<string,int>::iterator iter = mapStudent.begin(); 17 for(iter=mapStudent.begin();iter!=mapStudent.end();iter++) 18 { 19 cout<<iter->first<<" "<<iter->second<<endl; 20 } 21 return 0; 22 }
------>加油美好的一天