自定义 Class std::map 奇怪的行为
Custom Class std::map Weird Behavior
在使用我创建的自定义 class 作为键的地图中搜索键时,我遇到了一个奇怪的行为。
虽然地图上有钥匙,但它似乎找不到钥匙。
有人知道这是什么原因吗?
代码(可以运行呢here):
#include <iostream>
#include <map>
using namespace std;
typedef short int dimension;
class Point {
public:
Point() : m_x(0), m_y(0) {}
Point(const Point &other) : m_x(other.m_x), m_y(other.m_y) {};
Point(dimension x, dimension y) : m_x(x), m_y(y) {}
bool operator<(const Point &other) const {
if (m_x < other.m_x) return true;
return (m_y < other.m_y);
}
private:
dimension m_x;
dimension m_y;
};
int main() {
map<Point, bool> points = {{Point(0, 2), true},
{Point(1, 1), true},
{Point(2, 4), true}};
cout << (points.find(((points.begin())->first)) == points.end()) << endl;
cout << (points.find((next(points.begin()))->first) == points.end()) << endl;
cout << (points.find((next(next(points.begin())))->first) == points.end()) << endl;
cout << (points.find(Point(0, 2)) == points.end()) << endl;
cout << (points.find(Point(1, 1)) == points.end()) << endl;
cout << (points.find(Point(2, 4)) == points.end()) << endl;
return 0;
}
输出:
1
0
0
0
1
0
你的 operator<
有缺陷:
bool operator<(const Point &other) const {
if (m_x < other.m_x) return true;
return (m_y < other.m_y);
}
例如
{0, 3} < {1, 2} -> true
但是
{1, 2} < {0,3} -> true
operator<
必须实现 strict weak ordering。你忘了考虑 (m_x > other.m_x)
应该导致 false
.
的情况
避免此类问题的一个巧妙技巧是使用 std::tie
并利用 std::tuple::operator<
:
bool operator<(const Point &other) const {
return std::tie(m_x,m_y) < std::tie(other.m_x,other.m_y);
}
在使用我创建的自定义 class 作为键的地图中搜索键时,我遇到了一个奇怪的行为。
虽然地图上有钥匙,但它似乎找不到钥匙。
有人知道这是什么原因吗?
代码(可以运行呢here):
#include <iostream>
#include <map>
using namespace std;
typedef short int dimension;
class Point {
public:
Point() : m_x(0), m_y(0) {}
Point(const Point &other) : m_x(other.m_x), m_y(other.m_y) {};
Point(dimension x, dimension y) : m_x(x), m_y(y) {}
bool operator<(const Point &other) const {
if (m_x < other.m_x) return true;
return (m_y < other.m_y);
}
private:
dimension m_x;
dimension m_y;
};
int main() {
map<Point, bool> points = {{Point(0, 2), true},
{Point(1, 1), true},
{Point(2, 4), true}};
cout << (points.find(((points.begin())->first)) == points.end()) << endl;
cout << (points.find((next(points.begin()))->first) == points.end()) << endl;
cout << (points.find((next(next(points.begin())))->first) == points.end()) << endl;
cout << (points.find(Point(0, 2)) == points.end()) << endl;
cout << (points.find(Point(1, 1)) == points.end()) << endl;
cout << (points.find(Point(2, 4)) == points.end()) << endl;
return 0;
}
输出:
1
0
0
0
1
0
你的 operator<
有缺陷:
bool operator<(const Point &other) const {
if (m_x < other.m_x) return true;
return (m_y < other.m_y);
}
例如
{0, 3} < {1, 2} -> true
但是
{1, 2} < {0,3} -> true
operator<
必须实现 strict weak ordering。你忘了考虑 (m_x > other.m_x)
应该导致 false
.
避免此类问题的一个巧妙技巧是使用 std::tie
并利用 std::tuple::operator<
:
bool operator<(const Point &other) const {
return std::tie(m_x,m_y) < std::tie(other.m_x,other.m_y);
}