15.map映射
1 #include <iostream> 2 #include <map> 3 #include <cstring> 4 using namespace std; 5 6 //map常规用法 7 void main1() 8 { 9 //映射 10 map<char *, int> mymap; 11 mymap.insert(pair<char *, int>("司令6", 16)); 12 mymap.insert(pair<char *, int>("司令2", 11)); 13 mymap.insert(pair<char *, int>("司令3", 12)); 14 mymap.insert(pair<char *, int>("司令4", 13)); 15 //第一个字段不允许重复 16 mymap.insert(pair<char *, int>("司令4", 1323)); 17 18 for (auto i : mymap) 19 { 20 cout << i.first << " " << i.second << endl; 21 } 22 23 for (auto cb = mymap.cbegin(), ce = mymap.cend(); cb != ce; cb++) 24 { 25 cout << (*cb).first << " " << (*cb).second << endl; 26 } 27 28 auto it = mymap.find("司令2"); 29 //删除一个 30 //mymap.erase(it); 31 //删除一段 32 //mymap.erase(it, mymap.end()); 33 //链式存储 34 //auto ifind = mymap.begin()++; 35 //cout << mymap["司令2"] << endl; 36 //清空 37 mymap.clear(); 38 cout << it->first << " " << it->second << endl; 39 cin.get(); 40 } 41 42 struct strless 43 { 44 //仿函数 45 bool operator()(const char *str1, const char *str2) 46 { 47 //字符串比较 48 return (strcmp(str1, str2) < 0); 49 } 50 }; 51 52 void main() 53 { 54 //根据strless进行排序插入 55 map<char *, int, strless> mymap; 56 mymap.insert(pair<char *, int>("司令6", 16)); 57 mymap.insert(pair<char *, int>("司令2", 11)); 58 mymap.insert(pair<char *, int>("司令3", 12)); 59 mymap.insert(pair<char *, int>("司令4", 13)); 60 61 62 63 for (auto i : mymap) 64 { 65 cout << i.first << " " << i.second << endl; 66 } 67 68 69 cin.get(); 70 }