在编译时获取静态constexpr数组的最小/最大值

时间:2023-01-06 22:57:13

Let's say I have an array of integers defined like that:

假设我有一个这样定义的整数数组:

static constexpr int IntArray[] = {1, 5, 10, 12, 17};

Is there a way to get the minimum or maximum value at compile time?

有没有一种方法可以在编译时获得最小值或最大值?

1 个解决方案

#1


61  

Let's get the C++17 solution out of the way for future search-landers:

让我们为未来的搜索用户提供c++ 17解决方案:

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 is more picky with constexpr functions, so we have to roll out a recursive algorithm. This one is a simple, linear one:

c++ 11对于constexpr函数更加挑剔,所以我们必须推出一个递归算法。这是一个简单的线性方程

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);

See it live on Coliru

在Coliru上看

#1


61  

Let's get the C++17 solution out of the way for future search-landers:

让我们为未来的搜索用户提供c++ 17解决方案:

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 is more picky with constexpr functions, so we have to roll out a recursive algorithm. This one is a simple, linear one:

c++ 11对于constexpr函数更加挑剔,所以我们必须推出一个递归算法。这是一个简单的线性方程

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);

See it live on Coliru

在Coliru上看