Rahul Iyer
Rahul Iyer

Reputation: 21005

Why does my object not get inserted into std::set?

I have the following struct for comparing Rect object's..

struct rectcomp {
    bool operator() (const Rect& lhs, const Rect& rhs) const{
        return lhs.size.width<rhs.size.width;
    }
};

I have the following set where I wish to store my Rect's

std::set<Rect,rectcomp> _availableRects; 

I insert it with the following code;

void insertPairOfRects(const Rect rect1,const Rect rect2){
    _availableRects.insert(rect1); //first line
    _availableRects.insert(rect2); //second line
}

The problem is, that rect1 always gets inserted, but rect2 doesn't. When I step through the debugger, after the first line of the function insertPairOfRects, I can clearly see the increase in number of objects in insertPairOfRects....but for the second I can't.

What mistake am I making ?

EDIT: I suspect it is because of a mistake in my comparator function. I have never written one before for a set, so I imagine it is probably a fundamental misunderstanding here...

Upvotes: 0

Views: 51

Answers (1)

Hatted Rooster
Hatted Rooster

Reputation: 36463

I'm just going to assume that rect1.size.width == rect2.size.width, this makes the comparator return false for both cases in which case the object doesn't get inserted into the set because a set doesn't allow duplicates. Either change your rectangles or make a more detailed comparator.

Upvotes: 1

Related Questions