c++ - 二进制 '<' : 'const_Ty' does not define this operator or a conversion to a type acceptable to the predefined operator

标签 c++ class struct c++14

<分区>

我在自己的代码中遇到了同样的错误。这是一个小例子。问题出在哪里?

#include <set>
using namespace std;

class Table{};

struct MyStruct
{
    set<Table> arr;
};

int main()
{
    MyStruct a;
    Table t;
    a.arr.insert(t); // Here it gives C2676 error
}

最佳答案

std::set 是一个有序容器。对于自定义类型,您需要为您的类型提供排序。做到这一点的简单方法是为您的类型定义 operator<。

// return true if table x should go before table y in the set
bool operator<(const Table& x, const Table& y)
{
    ...
}

因为您没有这样做(或任何其他选项),所以会出现错误。标准库不知道如何在集合中对您的表进行排序。

关于c++ - 二进制 '<' : 'const_Ty' does not define this operator or a conversion to a type acceptable to the predefined operator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65489524/

相关文章:

c++ - 编译时生成常量类型 ID

USB 上的 C++ IDE?

c++ - "' SpaceShip ' does not name a type"即使 SpaceShip 肯定是一种类型

python - 将支持功能放在类中的最佳位置在哪里?

c++ - 如何完全减少/简化分数 (C++)

C - 结构段错误

c++ - 我可以在C/C++中(在Linux上)将`a.out`文件转换为“可执行文件”吗?

Python 类 : method has same name as property

struct - 我将如何创建一个函数局部静态 `HashSet<char>` 并初始化一次?

c++ - SFML 2.1 程序在 Debug模式下运行良好,但在 Release模式下崩溃