This is an interview question.
Referring to the sample code, which one of the operators needs to be overridden in order to use
std::set<Value>
#include<iostream>
class Value
{
std::string s_val;
int i_val;
public:
Value(std::string s, int i): s_val(s) , i_val(i){}
};
// EOF
/*
a operator !=
b operator >
c operator <=
d operator >=
e operator <
*/
Actually, I do not understand why an operator needs to be overridden here. “set” does not allow duplicated elements, maybe operator != needs to be overridden ?
You don’t have to override any operator, the
std::setclass template allows you to provide a comparison function as a template parameter. But if you were to provide an operator, the one needed isbool operator<(). This operator has to implement strict weak ordering. See this std::set documentation.The reason strict weak ordering is used is because set is an ordered container, typically implemented as a self-balancing binary tree. So it is not enough to know whether two elements are the same or not. The set must be able to order them. And the less than operator or the comparator functor are also used to test for element equality.