Search code examples
c++setstdset

C++ std::set Find function overloading == operator


I am using sets. I use a custom struct as the key. I am inserting a value and trying to find the inserted value. But it never seems to find the element.

I have overridden both the == operator and the < operator.

Here is the code of the structure:

struct distance_t
{
 public:
int id;
double distance;

bool operator<(const distance_t& rhs) const
{
    if(distance < rhs.distance)
        return true;
    else 
        return false;
}

bool operator==( const distance_t& rhs) 
{
    if(id == rhs.id)
        return true;
    else
        return false;
}
};

And this is the code of main

int main()
{
    set<distance_t> currentSet;

    distance_t insertDistance;
    insertDistance.id =1;
    insertDistance.distance = 0.5;

    currentSet.insert(insertDistance);

    distance_t findDistance;
    findDistance.id = 1;

    assert(currentSet.find(findDistance) != currentSet.end());
}

It always fails in the assert statement. What am I doing wrong?

Edit -Ok now I understand that it does not use the == operator at all. Here is what I want. I need the data structure to be ordered by distance. But I should be able to remove it using the id. Is there any clean way or already existing datastructure to do this?


Solution

  • It fails because your less-than comparison uses distance_t::distance, which you are not setting in findDistance:

    distance_t findDistance;
    findDistance.id = 1;
    

    std::set does not use operator== for anything. It only uses operator<. So you would have to change it's logic to use distance_t::id.

    If you want to search by id without changing the set's ordering, you can use std::find:

    set<distance_t>::iterator it = std::find(currentSet.begin(), 
                                             currentSet.end(), 
                                             findDistance);
    

    This will use your operator==. Bear in mind that this has linear time complexity.