//使用自定义类做map的key.方式一: 重载operator<()操作符
//by 鸟哥
//有疑问请留言或加群 1032082534
#include <iostream>
#include <map>
#include <string>
using namespace std;
class Tree{
public:
int height;
int diameter;
Tree(int h,int d){
height=h;
diameter=d;
}
bool operator<(const Tree &t) const
{
return (height <t.height)||(height==t.height&&diameter<t.diameter);
}
};
int main(){
map<Tree, int> treemap;
treemap[Tree(6,2)] = 12;
treemap[Tree(6,1)] = 13;
treemap[Tree(6,3)] = 14;
treemap[Tree(5,1)] = 15;
for (auto ii = treemap.begin() ; ii != treemap.end() ; ii++)
cout <<"key:"<< ii->first.height
<< " " << ii->first.diameter
<< " value: " << ii->second
<< endl;
return 0;
}
运行结果:
key:5 1 value: 15
key:6 1 value: 13
key:6 2 value: 12
key:6 3 value: 14