c++ - 比较器 - 重载运算符 <

标签 c++ visual-c++ operator-overloading set

我正在尝试使用 std::set 来包含三个成员变量的结构。

 struct blah{
       int  a,b,c;
       bool operator < ( const blah& blo  ) const{
           return ( a < blo.a || (a == blo.a && (b != blo.b || c != blo.c ) ) );
       }
 };

但我不断收到错误消息,提示我的运算符 < 无效。我的方法有什么问题? enter image description here

    struct blah {
           int  a,b,c;
                blah(int aa,int bb,int cc){ a=aa; b=bb; c=cc; }
           bool operator < ( const blah& blo  ) const{
               return ( a < blo.a 
                              || (a == blo.a && b < blo.b  )
                              || (a == blo.a && b == blo.b && c < blo.c  ) 
                      );
           }
     };

    int main() {
            std::set<blah> st;

            st.insert(blah(1,2,3));
            st.insert(blah(1,1,1));
            st.insert(blah(1,3,2));
            return 0;
    }

按照@paxdiablo 代码更改代码后,效果很好。谢谢大家!

最佳答案

在下面的完整程序中,该代码编译对我来说很好:

#include <iostream>

struct blah {
       int  a,b,c;
       bool operator < ( const blah& blo  ) const{
           return ( a < blo.a || (a == blo.a && (b != blo.b || c != blo.c ) ) );
       }
 };

int main (void) {
    blah x, y;
    x.a=2; x.b=2; x.c=2;
    y.a=2; y.b=2; y.c=2;
    if (x < y) std::cout << "x<y\n";
    if (y < x) std::cout << "x>y\n";
    if (!(y < x) && !(x < y)) std::cout << "x=y\n";
    return 0;
}

更改 x 的字段和 y输出不同的信息。

但我发现该功能存在一个主要问题。它可以告诉你 x < y y < x ,在两个a的情况下字段相同,但 b两者之间的字段不同。如果同时设置 a字段为 1 并设置 b字段到 21 ,你看:

x<y
y<x

这不会有好结果:-)

事实上,您得到的是一个调试断言(专门为捕获大多数调试代码中的运行时错误而构建的东西)让我相信运行时库可能会明确检查不正确的 operator<通过检测后一种情况来重载(即 x < y y < x 都为真)。

你真的应该解决这个问题,因为它会导致集合的各种问题(例如)在你需要保持事物排序的地方。

举例来说,假设您想使用 a , bc作为该优先级的关键。执行此操作的函数将包含类似以下内容:

// Check primary key.

if (a < blo.a) return true;
if (a > blo.a) return false;

// Primary key equal here, use secondary key.

if (b < blo.b) return true;
if (b > blo.b) return false;

// Primary and secondary keys equal here, use tertiary key.

return (c < blo.c);

关于c++ - 比较器 - 重载运算符 <,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16620580/

相关文章:

c++ - 模板 <class T> 的特化 模板 <class T> 的定义

c++ - 我无法理解类型转换的表达

c++ - 在 Visual C++ 中通过 TCP 发送字符串数据

c++ - g++ : linker issue on Mac OS X - Undefined symbols for architecture x86_64

c++ - 没有#pragma comment lib 命令的 Unresolved external symbol 错误

visual-studio - 在cmake中指定pdb符号文件的路径

c - 为什么我收到 C2059 错误?

c++ - 重载运算符 << : too many parameters for this operator function

c++ - 重载流插入运算符错误,无法编译

C++从编译时多态性中隐藏模板习语