Binary '<' : 'const_Ty' does not define this operator or a conversion to a type acceptable to the predefined operator

Viewed 720

I am getting the same error in my own code. This is a small example. Where is the problem?

#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
}
1 Answers

std::set is an ordered container. For custom types you are expected to provide an ordering for your type. The simple way to do that is to define operator< for your type.

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

Because you didn't do that (or any of the other options) you get the error. The standard library doesn't know how to order your tables within the set.

Related