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

标签 c++ set overloading operator-keyword

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

两个问题:

  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
    }
    

最佳答案

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

关于c++ - C++中集合的运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22392208/

相关文章:

c++ - 处理可能依赖的顶点的创建/销毁时的 VBO/VAO 内存管理实践

Java - 使对象集合友好

Swift Set - "randomElement"和 "first"之间的差异

c++ - 继承函数的重载解决方案

c++ - const 成员函数的重载解析 C++

c++ - 为什么 new 没有用模板实现?

java.lang.UnsatisfiedLinkError : Native method not found: 错误

c++ - 从 GNU 上的新运算符调用类构造函数 - 使用无效类

java - 如何检测 URL 对象是否与 Collection 中的另一个 URL 对象指向相同的路径

c++ - 函数重载和方法重载的区别