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

只谈情不闲聊 提交于 2019-12-02 10:39:49

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.

Nawaz

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:

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!

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!