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一定必不可少。