c++ map 结构体作为key关键词
结构体的定义:
这里的结构体是三个值 int x; int y; int label;
当三个值作为KEY值时,你需要重新定义它的对比操作operator,这样才能对map进行查找操作;
//数据结构声明;并且对key的查找操作进行定义,这样才能进行find等操作
struct point
{
int x;
int y;
point(const int A,const int B) :
x(A), y(B) {}
friend bool operator < (const point &A, const point &B);
};
inline bool operator < (const point& A,const point& B)
{
return A.x < B.x || (A.x==B.x && A.y<B.y) ;
}
struct Point_Label
{
int x;
int y;
int label;
Point_Label(const int A,const int B, const int C) :
x(A), y(B) , label(C){}
friend bool operator < (const Point_Label &A, const Point_Label &B);
};
inline bool operator < (const Point_Label& A,const Point_Label& B)
{
return A.label < B.label || (A.label==B.label && A.x<B.x) || (A.label==B.label && A.x==B.x && A.y<B.y);
}
map的使用:
std::map<Point_Label, float > PRM;
int i = 1;
int j = 2;
int cl = 12;
//当前结构就是point(i,j),cl 作为key值
Point_Label pointLabel(i, j, cl);
std::map<Point_Label, float>::iterator it;
//查找操作,是否存在pointLabel,不存在,构建make_pair插入
it = PRM.find(pointLabel);
if (it !=PRM.end()){
it -> second += 1 ;
} else{
PRM.insert(std::make_pair(pointLabel, 1));
}