Function compare

Compares element-wise two ranges for ordering.

int compare(alias pred, R1, R2) (
  R1 r1,
  R2 r2
)
if (allSatisfy!(isInputRange, R1, R2) && is(typeof(pred(r1.front, r2.front)) == bool) && is(typeof(pred(r2.front, r1.front)) == bool));

int compare(R1, R2) (
  R1 r1,
  R2 r2
)
if (allSatisfy!(isInputRange, R1, R2) && is(typeof(r1.front < r2.front || r2.front < r1.front)));

compare returns a negative value if r1 is less than r2, a positive value if r2 is less than r1, or 0 if r1 and r2 equal.

compare iterates both ranges in lockstep. Whichever of them contains an element that is greater than the respective element at the same position in the other range is the greater one of the two.

If one of the ranges becomes empty when iterating, but all elements equal so far, the range with more elements is the greater one.

If pred is given, it is used for comparison. pred is called as pred(r1.front, r2.front) and pred(r2.front, r1.front) to perform three-way comparison. pred should return a bool.

If pred is not given, but the element type of R1 defines opCmp() for the element type of R2, opCmp() is used.

Otherwise the comparison is perfomed using the basic comparison operators.

Parameters

NameDescription
pred Predicate used for comparison.
R1 First range type.
R2 Second range type.
r1 First range.
r2 Second range.

Returns

A negative value if r1 is less than r2, a positive value if $D(PARAM r2) is less than r1, 0 otherwise.

Example

assert(compare("abc", "abc") == 0);
assert(compare("abcd", "abc") > 0);
assert(compare("ab", "abc") < 0);
assert(compare("abc", "abcd") < 0);
assert(compare("abc", "ab") > 0);
assert(compare("aec", "abc") > 0);
assert(compare("aac", "abc") < 0);
assert(compare("abc", "aec") < 0);
assert(compare("abc", "aab") > 0);
assert(compare("aacd", "abc") < 0);
assert(compare("abc", "aacd") > 0);

assert(compare!((a, b) => a > b)("aec", "abc") < 0);
assert(compare!((a, b) => a > b)("aac", "abc") > 0);