error: no operator "<" matches these operands

error: no operator "<" matches these operands

我收到的错误:

/usr/include/c++/7/bits/stl_function.h:386: 
error: no operator "<" matches these operands
operand types are: const QVector3D < const QVector3D
{ return __x < __y; }

我将 QVector3Dstd::setstd::hypot 一起使用。是否有任何方法可以为 QVector3D 实现重载 operator< 以便能够在我的代码中使用它?

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);

我觉得你有多种可能性。是的,您可以按照评论中的说明重载 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 (https://en.cppreference.com/w/cpp/container/unordered_set),只需要元素具有 operator == 和哈希函数即可。

编辑:另一种选择: 您可以使用 std::vector,然后使用带有自定义比较功能的自由函数 std::lower_boundstd::upper_bound,请参阅 https://en.cppreference.com/w/cpp/algorithm/lower_bound