c++ - 需要覆盖哪个运算符才能在 C++ 代码中使用 std::set?

标签 c++ class set overriding

这是一道面试题。

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

其实我不明白这里为什么要重写一个operator。 “set”不允许重复的元素,也许 operator != 需要被覆盖?

最佳答案

没有覆盖任何运算符,std::set类模板允许您提供比较函数作为模板参数。但是如果你要提供一个运算符(operator),需要的是 bool operator<() .此运算符(operator)必须实现 strict weak ordering .看这个std::set文档。

使用严格弱排序的原因是因为集合是一个有序的容器,通常实现为一个自平衡的二叉树。所以仅仅知道两个元素是否相同是不够的。该集合必须能够订购它们。小于运算符或比较器仿函数也用于测试元素是否相等。

关于c++ - 需要覆盖哪个运算符才能在 C++ 代码中使用 std::set?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10872279/

相关文章:

c++ - C++提高了检查BST是否高度平衡的效率?

javascript - 如何使用 JavaScript 选择多个类之一?

python - 什么是python中的抽象类?

c++ - 如何在数组中初始化此类?

Python set Union 和 set Intersection 的操作方式不同?

c++ - 在 MFC 上单击按钮时显示文本

c++ - NCurses “mvwaddch”需要澄清

c++ - 如何在 C++ 中编写可维护、快速、编译时的位掩码?

CMake设置函数

optimization - 什么是快速查找集合列表的非空交集的数据结构?