std::less<> 不适用于我的 std::map
std::less<> not working with my std::map
我想用我自己的结构"Point2"作为键制作一个映射,但我遇到了错误,我不知道是什么原因造成的,因为我声明了一个"operator<"对于Point2结构。
代码:
std::map<Point2, Prop*> m_Props_m;
std::map<Point2, Point2> m_Orders;
struct Point2
{
unsigned int Point2::x;
unsigned int Point2::y;
Point2& Point2::operator= (const Point2& b)
{
if (this != &b) {
x = b.x;
y = b.y;
}
return *this;
}
bool Point2::operator== (const Point2& b)
{
return ( x == b.x && y == b.y);
}
bool Point2::operator< (const Point2& b)
{
return ( x+y < b.x+b.y );
}
bool Point2::operator> (const Point2& b)
{
return ( x+y > b.x+b.y );
}
};
错误:
1>c:program files (x86)microsoft visual studio 10.0vcincludexfunctional(125): error C2678: binary '<' : no operator found which takes a left-hand operand of type 'const Point2' (or there is no acceptable conversion)
1>c:testingprojectpoint2.h(34): could be 'bool Point2::operator <(const Point2 &)'
1>while trying to match the argument list '(const Point2, const Point2)'
1>c:program files (x86)microsoft visual studio 10.0vcincludexfunctional(124) : while compiling class template member function 'bool std::less<_Ty>::operator ()(const _Ty &,const _Ty &) const'
1> with
1> [
1> _Ty=Point2
1> ]
有人能看到问题的原因吗?
std::map
需要operator <
:的常量版本
// note the final const on this line:
bool Point2::operator< (const Point2& b) const
{
return ( x+y < b.x+b.y );
}
有operator==
、operator>
的非常量版本是没有意义的,它们也应该是const
。
正如ildjarn在下面指出的那样,这是一个明显的例子,您可以将这些运算符实现为自由函数,而不是成员函数。通常,您应该更喜欢将这些运算符作为自由函数,除非它们需要作为成员函数。这里有一个例子:
bool operator<(const Point2& lhs, const Point2& rhs)
{
return (lhs.x + lhs.y) < (rhs.x + rhs.y);
}
operator<
应该定义为const
,事实上,您的其他比较运算符也应该定义为,通常,任何不会改变其类的方法:
bool Point2::operator== (const Point2& b) const
{
return ( x == b.x && y == b.y);
}
bool Point2::operator< (const Point2& b) const
{
return ( x+y < b.x+b.y );
}
bool Point2::operator> (const Point2& b) const
{
return ( x+y > b.x+b.y );
}
相关文章:
- 为什么我的 std::ref 无法按预期工作?
- 如何使 std::sort 在 std::swap 和我的命名空间的模板化交换之间没有名称冲突?
- 为什么我不能将引用作为 std::async 的函数参数传递
- 为什么我的函数接受"std::string"进行排序不会改变它?
- 我的自定义使用 std::unordered_map 的性能非常慢
- 为什么只有当我的容器有超过 32 个元素时才由 std::sort 调用交换?
- std::我不明白的矢量元素错误
- 为什么我不必从 std::string 的函数中释放字符串c_str?
- 我可以制作一个std::set的constexpr对象吗
- 为什么我的 std::set 不存储唯一值?
- 为什么我的 std::atomic<int> 变量不是线程安全的?
- 试图让我的枚举等同于 std::error_code
- 将 std::文件系统头文件添加到我的程序时出现编译错误
- std::ifstream.read() 不会向我的缓冲区返回任何内容
- 为什么我可以将 std::map 的键传递给一个期望非常量的函数?
- 为什么我的类 std::vector 成员总是抛出段错误?
- 使用 std::is_same,为什么我的函数仍然不能用于 2 种类型
- 为什么我的std :: Map失去了价值
- 调整我的std :: string时,角色缓冲区会发生什么
- std::sort 在我的自定义迭代器上不起作用