【问题标题】:Operator overloading for a set in c++c++中集合的运算符重载
【发布时间】:2014-03-13 22:20:05
【问题描述】:

所以我创建了一个名为 Tuples 的新类,其中 Tuples 接受一个称为 tupleVector 的字符串向量。然后我创建了一组元组,这意味着我需要重载对元素进行排序所需的运算符并禁止重复。

两个问题:

  1. 需要哪个运算符重载?我是否超载
  2. 假设我必须在我的 Tuples 类中执行此重载(以便我可以在其他类中使用 Tuples 集),以下代码是否正确?

    include "Tuples.h"
    Tuples::Tuples(vector<string> tuple){
        tupleVector = tuple;
    }
    vector<string> Tuples::getStrings()
    {
        return tupleVector;
    }
    bool Tuples::operator<(Tuples& other){
        return this->tupleVector<other.tupleVector;
    }
    bool Tuples::operator==(const Tuples& other)const{
        return this->tupleVector==other.tupleVector;
    }
    Tuples::~Tuples() {
        // TODO Auto-generated destructor stub
    }
    

【问题讨论】:

  • Tuples 这个名字听起来像一个Tuples 实例代表一组元组。

标签: c++ set overloading operator-keyword


【解决方案1】:

您只需提供operator&lt;。容器通过反身比较来检查两个项目是否等价:如果!(a&lt;b) &amp;&amp; !(b&lt;a),它们是等价的

【讨论】:

    【解决方案2】:

    这取决于您喜欢在哪些类中使用自己的类型。如果您计划在许多地方使用该类,则应该重载整个运算符集。但是您可以通过调用一些自己的运算符来实现大多数其他运算符:

    bool operator==( const T &t ) const {
        // Implementation
    }
    

    要实现!= 运算符,只需调用您的== 运算符即可。

    bool operator!=( const T &t ) const {
        return !operator==(t);
    }
    

    同样,您可以通过调用==&lt; 运算符轻松实现&lt;=&gt;&gt;= 运算符。

    【讨论】:

      【解决方案3】:

      假设您想使用std::sort 对内存中的一个连续区域(Tuples 类型的对象的数组或标准容器)进行排序:

      template< class RandomIt >
      void sort( RandomIt first, RandomIt last );
      

      您应该为您的班级Tuples 重载operator&lt;,或者提供适当的仿函数。

      按升序对范围 [first, last) 中的元素进行排序。这 不保证保留相等元素的顺序。首先 version 使用 operator

      不需要operator==,因为它很容易被标准排序算法模拟,调用operator&lt;

      !( a < b) && !( b < a)
      

      【讨论】:

        猜你喜欢
        • 2013-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多