Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator< and strict weak ordering

How to define operator< on n-tuple (for example on 3-tuple) so that it satisfy strict weak ordering concept ? I know that boost library has tuple class with correctly defined operator< but for some reasons I can't use it.

like image 785
Konstantin Avatar asked Jun 11 '09 07:06

Konstantin


People also ask

What is a strict weak ordering?

A Strict Weak Ordering is a Binary Predicate that compares two objects, returning true if the first precedes the second. This predicate must satisfy the standard mathematical definition of a strict weak ordering.

What is meant by weak ordering?

In mathematics, especially order theory, a weak ordering is a mathematical formalization of the intuitive notion of a ranking of a set, some of whose members may be tied with each other.

What is weak ordering in economics?

Weak ordering implies that the consumer chooses a position and rejects others open to him, then the rejected positions need not be inferior to the position actually chosen but may have been indifferent to it. Hence, under weak ordering, actual choice fails to reveal definite preference.


1 Answers

strict weak ordering

This is a mathematical term to define a relationship between two objects.
Its definition is:

Two objects x and y are equivalent if both f(x, y) and f(y, x) are false. Note that an object is always (by the irreflexivity invariant) equivalent to itself.

In terms of C++ this means if you have two objects of a given type, you should return the following values when compared with the operator <.

X    a; X    b;  Condition:                  Test:     Result a is equivalent to b:       a < b     false a is equivalent to b        b < a     false  a is less than b            a < b     true a is less than b            b < a     false  b is less than a            a < b     false b is less than a            b < a     true 

How you define equivalent/less is totally dependent on the type of your object.

Formal Definition:
Strict Weak ordering

Computer Science:
Strict Weak Ordering

How it relates to operators:
Comparator


As a side note we can implement strict weak ordering manually. But we can do it simply using the std::tuple which has implemented it for you. You simply need to create a tuple without copying the objects.

struct S {      ThingA   a;      ThingB   b; }; bool operator<(S const& lhs, S const& rhs) {     return std::tie(lhs.a, lhs.b) < std::tie(rhs.a, rhs.b); } 

Note: This assumes that thingA and thingB already implement strict weak ordering themselves.

We can also implement equality the same way:

bool operator==(S const& lhs, S const& rhs) {     return std::tie(lhs.a, lhs.b) == std::tie(rhs.a, rhs.b); } 

Note again: This assumes that thingA and thingB already implement equality.

like image 61
Martin York Avatar answered Oct 03 '22 01:10

Martin York