c++ - std::map::find()

标签 c++ dictionary find operator-overloading

我有一个简单的结构,我将其用作 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() 访问 map ,该 map 的键具有 side 距离内的 xp、yp 属性。换句话说,如果我有一个 (x,y) 元组,我想在映射中找到满足 operator== 函数内条件的第一个 PpointKey

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

这可以使用查找吗?我正在获取 map.end(),所以我想检查一下 find() 函数是否使用了运算符==。也许搜索算法会更好?

提前致谢。

最佳答案

mapfind 函数没有使用operator==

但是您可以使用 std::find,传入 map< 的 begin()end() 迭代器。它将一次简单地遍历序列并产生第一个匹配的对象(复杂性是线性的)。

您遇到的问题是由于您滥用了运算符重载。这里的问题是 operator== 的常见定义是:

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

而您的定义不是这种情况,因此您不能用一个代替另一个。

最好使用具有表达性名称的传统函数而不是运算符重载,这样会减少误导。请注意,mapstd::find 允许您传递合适的谓词对象,您无需重载运算符即可使用它们。

关于c++ - std::map::find(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3090925/

相关文章:

c++ - 为什么 Boost Format 和 printf 在相同的格式字符串上表现不同

c++ - 通用成员函数定义

ios - 从可变数组中移除 MKPointAnnotation 对象

c++ - openCL:如何将 uint4 转换为 uchar4?

python - 一次遍历 Python 字典 N 项以进行 CSV 写入

c++ - 节省内存的 map<pair<int,int>, set<int>> 替代方案

mysql - Rails 3 - find_all_by_car_id 和 nil 对象

bash - 为什么带有后缀的基本名称与 find 一起使用时在子 shell 中不起作用?

jquery - 选择 DOM 中某个元素之后的所有 div 元素?

c++ - YUV420 到 RGB 的转换没有给出相同的图像?