c++ map 结构体作为key关键词

10 篇文章 0 订阅
1 篇文章 0 订阅

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

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值