HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Absolute-difference function for std::size_t

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
stdfunctionabsolutedifferenceforsize_t

Problem

Because std doesn't provide an overloaded version of std::abs for std::size_t, I built a version to calculate distance between unsigned numbers.

It subtracts the smaller one from the larger one, to prevent a negative result, since in unsigned integer it would wrap around.

std::size_t size_type_abs(std::size_t a, std::size_t b)
{
    return std::max(a, b) - std::min(a, b);
}


Is this implementation correct and efficient?

Solution

This function computes absolute difference, not absolute value, so it shouldn't be called abs. absolute_difference? size_diff?

What will you use this function for? Are you using size_t for something other than sizes, so an absolute difference is meaningful?

std::max(a, b) - std::min(a, b) is harder to read than a simple conditional:

return a > b ? a - b : b - a;


This function isn't specific to size_t; it can be defined for any type that supports comparison and subtraction:

template
T abs_diff(T a, T b) {
  return a > b ? a - b : b - a;
}


If you do want to define it only for size_t, using std::size_t would save some repetitions of std::.

Code Snippets

return a > b ? a - b : b - a;
template<typename T>
T abs_diff(T a, T b) {
  return a > b ? a - b : b - a;
}

Context

StackExchange Code Review Q#51179, answer score: 9

Revisions (0)

No revisions yet.