带有==操作符的struct vector的上界

C++ upper_bound on struct vector with == operator

本文关键字:vector struct 带有 操作符      更新时间:2023-10-16

我有以下结构体,

struct cube
{
    int  index l , b , h;
    bool operator<(const cube & c2) const
    {
        if (l == c2.l && b == c2.b && h == c2.h)
            return index < c2.index;
        if (l == c2.l && b == c2.b)
            return h < c2.h;
        if (l == c2.l )
            return b < c2.b;
        return l < c2.l;
    }
    bool operator==(const cube  c2) 
    {
        return index != c2.index && l == c2.l && b == c2.b;
    }
};

现在我想在这个结构体的vector上应用upper_bound作为==操作符中的条件。
然而,它仍然返回那些索引相同的迭代器

int pos2 = upper_bound(v.begin(),v.end(),v[i]) - v.begin();

。e v[我]。Index = v[pos2].index

对于两个cube实例foobar,当foo == bar也是true时,foo < bar可能是true。您可以通过将index == c2.index && l == c2.l && b == c2.b写入operator==中的返回表达式来修复此问题。

这个矛盾是你的问题的根本原因,尽管注意std::upper_bound本身只要求operator<被适当地实现;

难道index不是cube s的集合而不是给定的cube的属性吗?也就是说,它不应该出现在cube类?