Which operator needs to be overridden in order to

2019-03-03 16:37发布

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 ?

4条回答
Evening l夕情丶
2楼-- · 2019-03-03 17:09

A set keeps out the duplicates without needing operator= or operator!= by using the notion of equivalence. Two items are equivalent if neither is less than the other:

if (!(a < b || b < a))
    // equivalent!
查看更多
萌系小妹纸
3楼-- · 2019-03-03 17:16

To speed up the enforcement of no duplicate elements and generally checking if element is in its usually some sort of a tree and only needs operator <. (The only usage of less is enforced by the standard, the rest is just the avarage implementation)

查看更多
乱世女痞
4楼-- · 2019-03-03 17:19

You need to implement operator< for your type. The implementation must follow strick weak ordering to be able to use with associative containers from Standard library such as std::set and std::map.

Read about:

An example here:

查看更多
爷的心禁止访问
5楼-- · 2019-03-03 17:32

You don't have to override any operator, the std::set class template allows you to provide a comparison function as a template parameter. But if you were to provide an operator, the one needed is bool 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.

查看更多
登录 后发表回答