简体   繁体   English

std :: map :: find()

[英]std::map::find()

I have a simple struct which i'm using as a key in a std::map 我有一个简单的结构,我正在将其用作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;
        }   
};

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. 我想实现的是使用find()与具有其XP一键进入地图,YP一中的属性side的距离。 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 换句话说,如果我有一个(x,y)元组,我想在地图内找到第一个满足operator ==函数内部条件的PpointKey

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

Is this possible using find? 使用find可以吗? I'm getting map.end(), so I would like to check wheter the find () function uses the operator==. 我正在获取map.end(),所以我想检查一下find()函数是否使用operator ==。 Maybe the search algorithm would be better? 也许搜索算法会更好?

Thanks in advance. 提前致谢。

The find function of map does not use the operator== . mapfind函数不使用operator==

However you can use std::find , passing in the begin() and end() iterator of map . 但是,您可以使用std::find ,传入mapbegin()end()迭代器。 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: 这里的问题是operator==的常见定义是:

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. 请注意, mapstd::find允许您传递合适的谓词对象,您无需使运算符重载即可使用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM