C++ 中集合的运算符重载

Ada*_*dam 4 c++ overloading set operator-keyword

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

两个问题:

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

    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
    }
    
    Run Code Online (Sandbox Code Playgroud)

Bla*_*nic 8

您只需提供operator<. 容器通过反射性地比较两个项目来检查它们是否相等:如果!(a<b) && !(b<a)