本文介绍了套装超载算子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用std :: set来实现特定的算法.该集合中有重复项,因此我认为我必须重载运算符.重载看起来像这样.

I am using a std::set to implement a specific algorithm. The set had duplicates in it, so I assume I had to overload the operator. The overload looks like this.

class Vec3f {
    ...

    bool operator () ( const Vector3f& v0, const Vector3f& v1 ) const {
    float epsilon = 1e-7;
    return ((v1[0] - v0[0]) > epsilon) &&  ((v1[1] - v0[1]) > epsilon) && ((v1[2] - v0[2]) > epsilon);
}       ...


"Vec3f.h"

int main(){
    ...
    std::set<Vec3f,Vec3f> visited;
    ...
}

我超载了它,所以我可以使用< std :: set中需要的运算符.如果v0<,则此函数返回true. v1达到一定程度.它删除重复项,但同时也删除集中的有效值.我知道我的设备应该有12个Vec3fs.与重复项一样,它具有24个Vec3fs.通过我的比较功能,它只有3个Vec3f.我考虑使用绝对差,但这违反了严格的弱排序准则.我的问题是:如何编写比较功能以删除重复项并仅保留唯一项?

I overloaded it so I could use the < operator needed in std::set. This function returns true if v0 < v1 to some margin. It removes the duplicates, but it also removes valid values in the set. I know my set is supposed have to 12 Vec3fs. With the duplicates, it has 24 Vec3fs. With my comparison function, it only has 3 Vec3f. I considered using absolute difference, but that violates strict weak ordering criterion. My question is: how do I write the comparison function to remove duplicates and keepd only the unique items?

推荐答案

现在,v0中的每个组件都必须小于v1中的每个组件.这不是严格的弱排序.您应该一次检查一个组件.如果您当前检查的组件相等,则仅检查后续组件.另外,您应该放下epsilon.虽然这对于检查浮点计算结果的等效性很有用,但对排序没有用,因为它也违反了严格的弱排序.最简单的方法是将operator<用于std::tuple

As you have it now, every component in v0 needs to be less than every component in v1. This is not a strict weak ordering. You should check one component at a time. Only checking subsequent components if the component you are currently checking is equal. Also, you should drop the epsilon. While that's useful for checking equivalence of results of floating point calculations, it is not useful for ordering, because it too violates strict weak ordering. The easiest way to do this is to use operator< for std::tuple

return std::tie(v0[0], v0[1], v0[2]) < std::tie(v1[0], v1[1], v1[2]);

否则,如果要手动实现此功能,则如下所示:

Otherwise, if you want to implement this manually, it's something like this:

if (v0[0] < v1[0]) return true;
if (v0[0] > v1[0]) return false;
if (v0[1] < v1[1]) return true;
if (v0[1] > v1[1]) return false;
if (v0[2] < v1[2]) return true;
if (v0[2] > v1[2]) return false;
return false;

这篇关于套装超载算子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 09:43