如何解决在带有自定义比较器的 std::map 中使用自定义类时 -> 错误:静态断言失败
你好每个人,他们会发现这篇文章很有帮助。我有这个自定义类 Position
,我想在 std::map
class Position
{
public:
int x;
int y;
Position(const int &pos_x,const int &pos_y)
: x(pos_x),y(pos_y) {}
};
但是我有错误,因为它无法将类相互比较。所以我创建了这个比较类:
class PosComparator
{
public:
bool operator()(const ConsoleRenderer::Position &A,const ConsoleRenderer::Position &B)
{
if (A.x < B.x)
return true;
else if (A.x == B.x && A.y < B.y)
return true;
return false;
}
};
但是我收到了这个错误:
静态断言失败:比较对象必须作为常量调用
解决方法
正如错误所暗示的那样,在末尾添加 const
可以解决问题:
class PosComparator
{
public:
bool operator()(const ConsoleRenderer::Position &A,const ConsoleRenderer::Position &B) const
{
if (A.x < B.x)
return true;
else if (A.x == B.x && A.y < B.y)
return true;
return false;
}
};
或者通过使用 std::tie
来缩短它,创建可用于 compare 的元组:
class PosComparator
{
public:
bool operator()(const ConsoleRenderer::Position &A,const ConsoleRenderer::Position &B) const
{
return std::tie(A.x,A.y) < std::tie(B.x,B.y);
}
};
,
我通过简单地在行尾添加 const
解决了这个问题。
class PosComparator
{
public:
bool operator()(const ConsoleRenderer::Position &A,const ConsoleRenderer::Position &B) const
{
if (A.x < B.x)
return true;
else if (A.x == B.x && A.y < B.y)
return true;
return false;
}
};
希望这有帮助。 :)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。