gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 08:28:40 28 4
gpt4 key购买 nike

我有一个简单的结构,我将其用作 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com