1 #include<iostream> 2 #include<map> 3 using namespace std; 4 struct dian{ 5 int x,y; 6 /*bool operator<(const dian &a) const 7 { 8 return a.x>x; 9 }*/ 10 /*自定义类型,使用带排序效果的容器需要提前自己写好排序函数*/ 11 }; 12 bool operator<(const dian &a,const dian &b) 13 { 14 return a.x<b.x; 15 } 16 /* 这个排序函数既可以写在里面,也可以写在外面*/ 17 void swap(map<dian,int> &m,map<dian,int> &p) 18 { 19 map<dian,int> mp; 20 mp=m; 21 m=p; 22 p=mp; 23 } 24 int main() 25 { 26 map<dian,int> m,p; 27 dian a; 28 a.x=5; 29 a.y=6; 30 m[a]=6; 31 dian b; 32 b.x=7; 33 b.y=8; 34 m[b]=9; 35 dian c; 36 c.x=6; 37 c.y=9; 38 m.insert(pair<dian,int>(c,10)); 39 /* map可以直接用pair构造一个新的键值对*/ 40 // m.swap(p); 41 // swap(m,p); 42 // p=m; 43 map<dian,int> mp(m); 44 /* map仍然可以直接=赋值,或者直接swap以及自己写swap函数*/ 45 for(auto i:mp) 46 { 47 cout<<i.first.x<<" "<<i.first.y<<" "<<i.second<<endl; 48 } 49 50 }
为什么排序函数里面非得用const呢,这是因为map装载类型的需要,可以不需要“&”,但是const一定必不可少。