Skip to content

Instantly share code, notes, and snippets.

@utilForever
Last active June 15, 2017 03:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save utilForever/2c97fd784aad399a67513c671eedd413 to your computer and use it in GitHub Desktop.
Save utilForever/2c97fd784aad399a67513c671eedd413 to your computer and use it in GitHub Desktop.
Implement AbsMin(), AbsMax() function for std::array
//!
//! \brief Returns the absolute minimum value among the elements in std::array.
//!
//! \param[in] arr The array.
//!
//! \tparam T Value type.
//!
//! \return The absolute minimum.
//!
template <typename T, int N>
inline T AbsMin(std::array<T, N> arr)
{
T min = std::numeric_limits<T>::max();
T absMin = std::numeric_limits<T>::max();
for (T& value : arr)
{
T absValue = (T{} < value) ? value : -value;
if (absMin > absValue)
{
min = value;
absMin = absValue;
}
}
return min;
}
//!
//! \brief Returns the absolute maximum value among the elements in std::array.
//!
//! \param[in] arr The array.
//!
//! \tparam T Value type.
//!
//! \return The absolute maximum.
//!
template <typename T, int N>
inline T AbsMax(std::array<T, N> arr)
{
T max = std::numeric_limits<T>::min();
T absMax = std::numeric_limits<T>::min();
for (T& value : arr)
{
T absValue = (T{} < value) ? value : -value;
if (absMax < absValue)
{
max = value;
absMax = absValue;
}
}
return max;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment