我需要创建 std::map<cv::Point, double>
. cv::Point
是 OpenCV 库中的一种点。它具有以下字段:x
和 y
.
cv::Point
没有 <
当然是运营商。你知道如何定义它以最佳地访问 std::map
中的元素吗? ?
换句话说。例如,我有 20000 点。我需要非常快速地访问每个点。
例如:
std::map<cv::Point, double> myMap;
Point p(10, 234);
int value = 777;
myMap[p] = value; // I need this operation quite fast so I decided to use std::map
但是 cv::Point 没有 <
运算符(operator)。我可以准备<
运算符喜欢(例如仅比较 x 坐标):
bool operator<(const cv::Point a, const cv::Point b)
{
return a.x < a.x;
}
但我猜它不是好的运算符(operator)。许多点具有相同的 x 值。
在这种情况下如何准备高效的运算符(operator)?
最佳答案
根据 this documentation , cv::Point
代表二维数据点。为此,您可以定义运算符 <
通过标准词典排序:
bool operator<(cv::Point const& a, cv::Point const& b)
{
return (a.x < b.x) || (a.x == b.x && a.y < b.y);
}
编辑:正如您考虑使用 unordered_map
: 虽然在这里可能更合适,但实现起来有点复杂,因为您必须组合 x
的两个哈希值。和 y
.为此,您可以使用 boost::hash_combine
或者自己想出一些合理的东西,但你发现它变得更加复杂。
关于c++ - 以 cv::Point 为键的 std::map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26483306/