set关联容器去除重复地图点出现问题 error: no match for ‘operator<’ (operand types are ‘const Point’ and ‘const Point

8 篇文章 0 订阅
本文介绍了在C++编程中遇到的一个错误:尝试将自定义类型Point插入set时,由于缺少`<`操作符重载,导致编译错误。为了解决这个问题,我们需要为Point类定义`<`运算符,以便set可以正确地对元素进行排序和查找。通过添加`<`运算符重载,使set能够根据指定的比较准则对Point对象进行比较,从而修复了错误。
摘要由CSDN通过智能技术生成

set中每个元素只包含一个关键字,set支持高效关键字查询---检查一个关键字是否在set中。

vector<sweep::MetricPoint2D> carpetPoint;
set<Point> gridPoint;

void DealMap::onRobotPoseReceived(const geometry_msgs::PoseStampedPtr ptrRobotPose)
{
    if (robot_state->device_state.carpet_check == 1)
    {
        sweep::MetricPoint2D tempPoint; //米制坐标点
        tempPoint.x = ptrRobotPose->pose.position.x;
        tempPoint.y = ptrRobotPose->pose.position.y;

        Point intPoint;
        intPoint.x = (int)(tempPoint.x / mapResolution);
        intPoint.y = (int)(tempPoint.y / mapResolution); 
        
        if (gridPoint.find(intPoint) == gridPoint.end())
        {
            gridPoint.insert(intPoint);
            carpetPoint.push_back(tempPoint);
        }
    }
}

if调用返回一个迭代器,如果关键字在set中,迭代器指向该关键字,否则find返回尾后迭代器。

运行的时候出现错误

error: no match for ‘operator<’ (operand types are ‘const Point’ and ‘const Point’)

{ return __x < __y; }

原因分析:

if (gridPoint.find(intPoint) == gridPoint.end())条件执行会对key的大小作比较,作为自定义类型Point,本身无法做大小比较。

解决方法:使set的key能比较大小

自定义类型增加<操作符重载函数:

class Point
{
 public:
    int x;
    int y;
    Point()
    {
        x = 0;
        y = 0;
    }
    Point(int x, int y)
    {
        this->x = x;
        this->y = y;
    }
    bool operator<(const Point& point)
    {
        if(this->x < point.x)
        {
            return true;
        }else if (this->x == point.x)
        {
            if (this->y < point.y)
            {
                return true;
            }
        }
        return false;
    }

    friend bool operator<(const Point&point1,const Point&point2)
    {
        if(point1.x < point2.x)
        {
            return true;
        }else if (point1.x == point2.x)
        {
            if (point1.y < point2.y)
            {
                return true;
            }
        }
        return false;
    }
};

set容器有其特定的排序准则,缺省情况下以operator<进行比较,也就是默认升序排列。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Maccy37

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

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

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

打赏作者

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

抵扣说明:

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

余额充值