Obtener el valor mínimo / máximo de una matriz constexpr estática en tiempo de compilación
Digamos que tengo una matriz de enteros definida así:
static constexpr int IntArray[] = {1, 5, 10, 12, 17};
¿Hay alguna manera de obtener el valor mínimo o máximo en tiempo de compilación?
42
Author: Rakete1111, 2016-10-27
1 answers
Quitemos la solución de C++17 del camino para futuros buscadores:
constexpr int IntArray[] = {1, 5, 10, 12, 17};
constexpr int min = *std::min_element(std::begin(IntArray), std::end(IntArray));
static_assert(min == 1);
C++11 es más exigente con las funciones constexpr
, por lo que tenemos que desplegar un algoritmo recursivo. Este es uno simple, lineal:
template <class T>
constexpr T &constexpr_min(T &a, T &b) {
return a > b ? b : a;
}
template <class T>
constexpr T &arrayMin_impl(T *begin, T *end) {
return begin + 1 == end
? *begin
: constexpr_min(*begin, arrayMin_impl(begin + 1, end));
}
template <class T, std::size_t N>
constexpr T &arrayMin(T(&arr)[N]) {
return arrayMin_impl(arr, arr + N);
}
constexpr int IntArray[] = {1, 5, 10, 12, 17};
constexpr int min = arrayMin(IntArray);
61
Author: Quentin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-21 12:36:25
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-21 12:36:25