【问题标题】:std::map::find()std::map::find()
【发布时间】: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 &lt;。如果两个键都不小于另一个,则认为两个键相等。

标签: c++ map find operator-overloading


【解决方案1】:

map 的find 函数不使用operator==。

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

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

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

您的定义并非如此,因此您不能用一个代替另一个。

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

【讨论】:

  • 但std::find() 将在std::pair&lt;const Key,Value&gt;:: 上运行,而不是在Key 上单独运行。所以std::find_if()应该使用适当的谓词,对吧?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-18
  • 2012-02-05
  • 1970-01-01
  • 1970-01-01
  • 2022-08-24
  • 1970-01-01
  • 2012-04-15
相关资源
最近更新 更多