本文介绍了为了在C ++代码中使用std :: set,需要重写哪个操作符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个面试问题。




 #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 <
 */

其实,我不明白为什么操作员需要在这里重写。 set不允许重复的元素,也许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 ?

推荐答案

您不 std :: set 类模板允许您提供比较函数作为模板参数。但是如果你要提供一个运算符,需要的是 bool operator<()。此运算符必须实现。请参阅此文档。

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.

这篇关于为了在C ++代码中使用std :: set,需要重写哪个操作符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 01:56