Qt 使用自定义的数据类型作为QMap的Key(Class)

由于项目需要,有大量数据需要存入QMap中进行调用,而每个存入的数据包含:方位角度、距离、高度

因此我自定义数据类型PointData,为了让自定义数据能放入QVariant中,因此对自定义的数据类型PointData使用宏Q_DECLARE_METATYPE

QMap<key,value>中数据存入时会对存入数据进行比较,并按照比较后的顺序进行排序存储,因此需要重载运算<

为方便调试输入调试信息,我同时重载了运算符<<,输入QDebug信息。

先看PointData数据类型:

PointData.h

#ifndef POINTDATA_H
#define POINTDATA_H
#include <QMetaType>
#include <QDebug>
class PointData
{
public:
    PointData();
    PointData(const PointData& other);
    ~PointData();
    PointData(const int &azimuth, const int &distance,const int& height);

    int azimuth() const;
    int distance() const;
    int height() const;

    int Azimuth;
    int Distance;
    int Height;


private:
};

Q_DECLARE_METATYPE(PointData);
//! [custom type meta-type declaration]

//! [custom type streaming operator]
QDebug operator<<(QDebug dbg, const PointData &pointdata);

inline bool operator<(const PointData &p1,const PointData &p2){
    if(p1.Azimuth!=p2.Azimuth){
        return p1.Azimuth<p2.Azimuth;
    }
    else if (p1.Distance != p2.Distance) {
        return p1.Distance<p2.Distance;
    }else{
        return p1.Height<p2.Height;
    }
}

#endif // POINTDATA_H

排序方式优先级为:方位>距离>高度

PointData.cpp

#include "pointdata.h"

PointData::PointData(){

}

PointData::PointData(const PointData& other){
    Azimuth = other.Azimuth;
    Distance = other.Distance;
    Height = other.Height;
}

PointData::PointData(const int &azimuth, const int &distance,const int& height){
    Azimuth = azimuth;
    Distance = distance;
    Height = height;
}

PointData::~PointData(){

}


QDebug operator<<(QDebug dbg, const PointData &pointdata){
    dbg.space()<<"Azimuth:"<<pointdata.azimuth()<<"Distance:"<<pointdata.distance()<<"Height:"<<pointdata.height();
    return dbg.maybeSpace();
}

int PointData::azimuth() const{
    return Azimuth;
}

int PointData::distance() const{
    return Distance;
}

int PointData::height() const{
    return Height;
}

此时PointData可直接当做QVariant一般作为QMap的Key键值。使用方法举例:

    PointData p;
    p.Azimuth = 180;//方位值
    p.Distance = 300;//距离值
    p.Height = heightLevel;//高度值

    QMap<PointData,int>map;
    map[p]=10;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喵喵叫的猴

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值