我收到的错误:
/usr/include/c++/7/bit/stl_function.h.h:386: error: no操作符"<“匹配这些操作数操作数类型为: const QVector3D < const QVector3D {返回__x < __y;}
我用的是QVector3D和std::set和std::hypot。是否有任何方法来实现重载的operator<以便QVector3D能够在我的代码中使用它?
std::pair<QVector3D, QVector3D> NearestNeighbor::nearest_pair(std::vector<QVector3D> points)
{
// // Sort by X axis
std::sort( points.begin(), points.end(), [](QVector3D const &a, QVector3D const &b) { return a.x() < b.x(); } );
// // First and last points from `point` that are currently in the "band".
auto first = points.cbegin();
auto last = first + 1;
// // The two closest points we've found so far:
auto first_point = *first;
auto second_point = *last;
std::set<QVector3D> band{ *first, *last };
// // Lambda function to find distance
auto dist = [] (QVector3D const &a, QVector3D const &b) { return std::hypot(a.x() - b.x(), a.y() - b.y()); };
float d = dist(*first, *last);
while (++last != points.end()) {
while (last->x() - first->x() > d) {
band.erase(*first);
++first;
}
auto begin = band.lower_bound({ 0, last->y() - d, 0 });
auto end = band.upper_bound({ 0, last->y() + d, 0 });
assert(std::distance(begin, end) <= 6);
for (auto p = begin; p != end; ++p) {
if (d > dist(*p, *last)) {
first_point = *p;
second_point = *last;
d = dist(first_point, second_point);
}
}
band.insert(*last);
}
return std::make_pair(first_point, second_point);
}更新
使用@CuriouslyRecurringThoughts帮助解决问题,方法是替换:
std::set<QVector3D> band{ *first, *last };通过以下方式:
auto customComparator = [](QVector3D const &a, QVector3D const &b) { return a.y() < b.y(); };
std::set<QVector3D, decltype (customComparator)> band({ *first, *last }, customComparator);我也可以这样做:
auto customComparator = [](QVector3D const &a, QVector3D const &b) { return a.y() < b.y(); };
std::set<QVector3D, decltype (customComparator)> band(customComparator);
band.insert(*first);
band.insert(*last);发布于 2019-07-06 06:46:32
我觉得你有各种各样的可能性。是的,如注释中所述,您可以重载operator<,但我建议您不要这样做:对于这个特定的用途,您需要一个特定的比较函数,可能在其他地方需要不同的排序。除非一种类型的排序关系很明显,否则我建议避免重载操作符。
您可以提供一个自定义比较函数,如下所示
auto customComparator = [](QVector3D const &a, QVector3D const &b) { return a.x() < b.x(); };
std::set<QVector3D, decltype(customComparator)> set(customComparator);
set.insert(*first)对我来说,还不清楚band集试图实现什么,但是由于您正在调用y()坐标的上、下界,也许您希望在y()上进行比较,但这意味着具有相同y()的两个点将被视为相等,而std::set不允许重复。
否则,您可以查看std::unordered_set (set),它不需要排序,只需要元素具有operator ==和哈希函数。
编辑:另一种选择:您可以使用std::vector,然后使用带有自定义比较函数的免费函数std::lower_bound和std::upper_bound,请参阅bound
https://stackoverflow.com/questions/56911430
复制相似问题