Re: using a float as the index in an STL map?
* Greg Herlihy:
On Apr 21, 2:51 am, James Kanze <james.ka...@gmail.com> wrote:
On Apr 21, 3:07 am, red floyd <no.s...@here.dude> wrote:
James Kanze wrote:
On Apr 21, 12:36 am, zeppethef...@gmail.com wrote:
I think a good alternative would be to manually define the comparison
operator "less" considering that the equality
(a == b)
on a map is given by
!less(a,b) && !less(b,a)
it should be sufficient to write less() as something like
less(a, b){
if (a - b > threshold)
return false;
else
return true;
}
with threshold a proper small number.
That's a nice way to get undefined behavior. Since such a
function doesn't define an ordering relationship (which must be
transitive), it doesn't meet the requirements for std::map or
std::set.
On the other hand, assuming a reasonable threshold (EPSILON), what's
wrong with:
less(float a, float b)
{
if (fabs(a - b) > EPSILON) // difference big enough to be
return a < b; // significant
else
return false; // elements are "equal"
}
What have you changed? You still haven't defined a strict
ordering relationship, so you have undefined behavior.
There is no undefined behavior. The less() function does produce a
total ordering:
For any a, b, and c such that less(a, b) returns true and less(b, c)
returns true, then it is the case that less( a, c) also returns true.
For a std::map the 'less' operation must define a strict weak ordering.
"Strict" means that !(a op a) holds for all a. This is true of the
'less' above.
Exactly what "weak" means I'm not sure, but the standard's requirement
(in ?25.3/4) is that 'less' should define an equivalence relation, via
bool eq(a,b) { return !less(a,b) && !less(b,a); }
which must be transitive,
eq(a,b) && eq(b,c) implies eq(a,c)
This requirement is not met for the 'less' above.
You can have (a,b) such that their difference is less than EPSILON, and
(b,c) such that their difference is less than EPSILON, but such that the
difference for (a,c) is greater than EPSILON.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?