Adam
Adam

Reputation: 79

Operator overloading for a set in c++

So I've created a new class called Tuples where Tuples takes in a vector of strings known as tupleVector. I then create a set of Tuples, meaning I need to overload the operators necessary to order elements and disallow duplicates.

Two questions:

  1. which operator overload is necessary? Do I overload < or ==?
  2. Assuming I must perform this overload within my Tuples class (so I can use the set of Tuples in other classes), is the following code correct?

    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
    }
    

Upvotes: 4

Views: 6331

Answers (3)

4pie0
4pie0

Reputation: 29724

Assuming you would like to use std::sort to sort a contiguous area in memory (array or standard container of the objects of Tuples type):

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

You should overload operator< for your class Tuples or provide appropriate functor alternatively.

Sorts the elements in the range [first, last) in ascending order. The order of equal elements is not guaranteed to be preserved. The first version uses operator< to compare the elements, the second version uses the given comparison function object comp.

operator== is not needed, because it is easily emulated by standard sort algorithm with calls to operator< :

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

Upvotes: 0

Blaz Bratanic
Blaz Bratanic

Reputation: 2279

You only need to provide operator<. The container checks whether two items are equivalent by comparing them reflexively: they are equivalent if !(a<b) && !(b<a)

Upvotes: 8

Flovdis
Flovdis

Reputation: 3095

It depends in which classes you like to use your own type. If you plan to use the class at many places you should overload the whole set of operators. But you can implement most other operators by calling a few own one:

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

To implement the != operator, just call your == operator.

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

Similar you can easily implement the <=, >, >= operators by calling the == and < operator.

Upvotes: 0

Related Questions