Which operator needs to be overridden in order to use std::set in the C++ code?

前端 未结 4 684
滥情空心
滥情空心 2021-01-27 09:34

This is an interview question.

Referring to the sample code, which one of the operators needs to be overridden in order to use st

4条回答
  •  借酒劲吻你
    2021-01-27 10:19

    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.

提交回复
热议问题