Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c++ Overloaded operator () change std::set.find()

I’m learning std::set . Here is my codes:

#include <set>
#include <iostream>
using namespace std;
struct cmp{
    bool operator () (const int & a,const int & b) const {
        if(abs(a-b)<=3)
            return false;
        return a < b;
    }
};
set<int,cmp> q{1, 2, 10};
int main(){
    if(q.find(4)!=q.end())
        cout << 1;
    else
        cout << 2;
}

Output: 1

I use struct cmp to custom elements’s sort rules,if abs(a-b)<=3 the new element will be delete.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But what surprised me was that q.find() had been changed.

I want to know why the output is 1,there is no 4 in q.

q.find(4) is to get a iterator where the element equals
4 in q , isn’t it?

>Solution :

The output is 1 because your custom comparator function is being used not only for sorting the elements in the set, but also for determining equality between elements. In other words, the find function is using the comparator to determine if an element is equal to the value you’re searching for (4 in this case).

When the find function encounters the element 1 in the set, it compares it to 4 using your custom comparator function. In your comparator function, abs(1-4) <= 3 is true, so the function returns false. This causes the find function to think that 1 and 4 are equal, so it returns an iterator pointing to 1.

To fix this, you should make sure that your comparator function only compares the relative ordering of elements, not their equality. This can be done by adding a separate equality check in the comparator function, or by using a different container, such as std::unordered_set which uses the == operator to check equality of elements.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading