开发者

std::map::find()

I have a simple struct which i'm using as a key in a 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;
        }开发者_JS百科   
};

What I would like to achieve is to use the find() to access the map with a key that has its xp,yp attributes within a side distance. In other words, if I have an (x,y) tuple, I would like to find inside the map the first PpointKey that fulfils the condition inside the operator== function

return ((x>=xp && x<=xp+side) && (y>=yp && y<=yp+side));

Is this possible using find? I'm getting map.end(), so I would like to check wheter the find () function uses the operator==. Maybe the search algorithm would be better?

Thanks in advance.


The find function of map does not use the operator==.

However you can use std::find, passing in the begin() and end() iterator of map. It will simply iterate through the sequence one at a time and yield the first object that matches (complexity is linear).

The issue you encounter is due to the fact that you have abused operator overload. The problem here is that the common definition of operator== is:

T operator==(T lhs, T rhs)
{
  return !(lhs < rhs) && !(rhs < lhs);
}

And this is not the case with your definition, thus you cannot substitute one for the other.

It would be best if you used traditional functions with expressive names rather than operator overloading, it would be less misleading. Note that map and std::find allow you to pass suitable predicate objects, you don't need to overload the operators to use them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜