Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

Because operator== is not invoked at all. Comparing elements is like:

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

In other words, it uses operator<.

As you haven't assigned a value to findDistance.distance the result of the less then comparison is undefined.

Note that your definitions of the equality and less then comparison operators is dangerous, because it is easy to define instances of distance_t where their result is inconsistent. One example is two instances with the same distance but different id's.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top