I'm having trouble with this "strict weak ordering". Consider a class Point with members x and y. I tried to make the comparison "If both the x values are less than each other and the y values are less than each other, the Point's are less than each other". However, in the example below I create two points: (10,10) and (10,11) and the second insert fails.

Can someone please explain my blunder?

``````#include <iostream>
#include <set>

struct Point
{
float x,y;
};

struct MyComparison
{
bool operator()(const Point p1, const Point p2) const
{
if((p1.x < p2.x) && (p1.y < p2.y))
{
return true;
}
else
{
return false;
}
}
};

int main(int argc, char* argv[])
{
typedef std::set<Point, MyComparison> SetType;
SetType s;
std::pair<SetType::iterator, bool> result;
Point p1;
p1.x=10;
p1.y=10;
result = s.insert(p1);
std::cout << result.second << std::endl;

Point p2;
p2.x=10;
p2.y=11;
result = s.insert(p2);
std::cout << result.second << std::endl;

return 0;
}``````

Thanks,

David

## All 3 Replies

It doesn't work because for an element n to be less than m, both x and y fields of n has to be lower than of m's( by your construct). You should test x first then y. Like so :

``````if(p1.x < p2.x) return true;
else return p1.y < p2.y``````

By your < operator, p1 isn't less than p2 and p2 isn't less than p1, so... they must be equal, so p2 cannot be inserted since it would be a duplicate.

Here is what I ended up with (I believe it is the same as what FirstPerson said):

``````struct MyComparison
{
bool operator()(const Point p1, const Point p2) const
{
if((p1.x < p2.x))
{
return true;
}

if(p1.x == p2.x)
{
if(p1.y < p2.y)
{
return true;
}
}

return false;
}
};``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.