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));

}


Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐