#include <iostream>#include <map>#include <unordered_map>#include <string>usingnamespacestd;structNode{intid;intval;Node(intid,intval):id(id),val(val){}};structcompare{booloperator()(constNode&a,constNode&b)const{returna.val<b.val;}};booloperator<(constNode&a,constNode&b){returna.val<b.val;}intmain(intargc,constchar*argv[]){cout<<"初始化一个map,有序的,默认是升序"<<endl;map<string,int>test_map;cout<<"添加数据方式一,插入key值一样的pair,不会改变原本pair"<<endl;test_map.insert(pair<string,int>("a",2));test_map.insert(pair<string,int>("b",3));test_map.insert(pair<string,int>("d",4));test_map.insert(pair<string,int>("c",6));cout<<"添加数据方式二,可以通过[]来修改key对应的值"<<endl;test_map["a"]=2;test_map["b"]=3;test_map["d"]=4;test_map["c"]=6;cout<<"传入key值删除元素"<<endl;test_map.erase("a");cout<<"map的大小"<<endl;cout<<test_map.size()<<endl;cout<<"遍历map"<<endl;for(autopos=test_map.begin();pos!=test_map.end();pos++){cout<<"key:"<<pos->first<<" value:"<<pos->second<<endl;}cout<<endl;cout<<"计算key为d的元素个数,为1即有,为0即没有"<<endl;if(test_map.count("d")==1){cout<<"find d"<<endl;}else{cout<<"no find"<<endl;}cout<<"寻找key为d的元素,若找到的返回对象元素的迭代器,否则返回最后一个元素的迭代器"<<endl;if(test_map.find("d")!=test_map.end()){cout<<"find d value is "<<test_map.find("d")->second<<endl;}else{cout<<"no find"<<endl;}cout<<"自定义类型的map,需要重新compare函数或者重载<运算符,其他用法参照上面"<<endl;map<Node,int,compare>node_map;//需要重载<运算符,系统默认的compare是less//map<Node, int> node_map;Noden1(1,2);Noden2(3,1);Noden3(4,5);node_map.insert(pair<Node,int>(n1,1));node_map.insert(pair<Node,int>(n2,2));node_map.insert(pair<Node,int>(n3,3));for(autopos=node_map.begin();pos!=node_map.end();pos++){cout<<"Node value is "<<pos->second<<endl;}cout<<endl;return0;}