【发布时间】:2010-06-22 06:58:11
【问题描述】:
我有一个简单的结构,我将其用作 std::map 中的键
struct PpointKey{
unsigned int xp,yp; //pixel coordinates
unsigned int side;
PpointKey(unsigned xp,unsigned yp,unsigned side=5):xp(xp),yp(yp),side(side)
{}
bool operator==(const PpointKey& other) const{
const unsigned int x = other.xp;
const unsigned int y = other.yp;
return ((x>=xp && x<=xp+side) && (y>=yp && y<=yp+side));
}
bool operator<(const PpointKey& other) const{
const unsigned int x = other.xp;
const unsigned int y = other.yp;
const unsigned other_distance_2 = x*x + y*y;
const unsigned this_distance_2 = this->xp*this->xp + this->yp * this->yp;
return this_distance_2 < other_distance_2;
}
};
我想要实现的是使用 find() 访问带有 xp,yp 属性的键在side 距离内的地图。换句话说,如果我有一个 (x,y) 元组,我想在地图中找到满足 operator== 函数内部条件的第一个 PpointKey
return ((x>=xp && x<=xp+side) && (y>=yp && y<=yp+side));
这可以使用 find 吗?我得到了 map.end(),所以我想检查 find() 函数是否使用 operator==。也许搜索算法会更好?
提前致谢。
【问题讨论】:
-
请记住
std::map仅使用operator <。如果两个键都不小于另一个,则认为两个键相等。
标签: c++ map find operator-overloading