gpt4 book ai didi

c++ - 错误 : no operator "<" matches these operands

转载 作者:行者123 更新时间:2023-11-30 04:46:12 26 4
gpt4 key购买 nike

我收到的错误:

/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 .有什么方法可以实现重载 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);

最佳答案

我认为你有多种可能性。是的,你可以重载 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 是什么set 正在尝试实现,但由于您在 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

关于c++ - 错误 : no operator "<" matches these operands,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56911430/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com