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<进行比较,也就是默认升序排列。