View source code Display the source code in std/algorithm/comparison.d from which this page was generated on github. Improve this page Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone. Page wiki View or edit the community-maintained wiki page associated with this page.

Function std.algorithm.comparison.cmp

Performs three-way lexicographical comparison on two input ranges according to predicate pred. Iterating r1 and r2 in lockstep, cmp compares each element e1 of r1 with the corresponding element e2 in r2. If one of the ranges has been finished, cmp returns a negative value if r1 has fewer elements than r2, a positive value if r1 has more elements than r2, and 0 if the ranges have the same number of elements.

If the ranges are strings, cmp performs UTF decoding appropriately and compares the ranges one code point at a time.

Prototypes

int cmp(alias pred, R1, R2)(
  R1 r1,
  R2 r2
)
if (isInputRange!R1 && isInputRange!R2 && !(isSomeString!R1 && isSomeString!R2));

int cmp(alias pred, R1, R2)(
  R1 r1,
  R2 r2
)
if (isSomeString!R1 && isSomeString!R2);

Parameters

NameDescription
pred The predicate used for comparison.
r1 The first range.
r2 The second range.

Returns

0 if both ranges compare equal. -1 if the first differing element of r1 is less than the corresponding element of r2 according to pred. 1 if the first differing element of r2 is less than the corresponding element of r1 according to pred.

Example

int result;

result = cmp("abc", "abc");
assert(result == 0);
result = cmp("", "");
assert(result == 0);
result = cmp("abc", "abcd");
assert(result < 0);
result = cmp("abcd", "abc");
assert(result > 0);
result = cmp("abc"d, "abd");
assert(result < 0);
result = cmp("bbc", "abc"w);
assert(result > 0);
result = cmp("aaa", "aaaa"d);
assert(result < 0);
result = cmp("aaaa", "aaa"d);
assert(result > 0);
result = cmp("aaa", "aaa"d);
assert(result == 0);
result = cmp(cast(int[])[], cast(int[])[]);
assert(result == 0);
result = cmp([1, 2, 3], [1, 2, 3]);
assert(result == 0);
result = cmp([1, 3, 2], [1, 2, 3]);
assert(result > 0);
result = cmp([1, 2, 3], [1L, 2, 3, 4]);
assert(result < 0);
result = cmp([1L, 2, 3], [1, 2]);
assert(result > 0);

Authors

Andrei Alexandrescu

License

Boost License 1.0.

Comments