"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Initialize a C++11 `constexpr` Array from 0 to N?

How to Initialize a C++11 `constexpr` Array from 0 to N?

Published on 2024-12-22
Browse:238

How to Initialize a C  11 `constexpr` Array from 0 to N?

Initializing a Constexpr Array from 0 to N in C 11

In C 11, creating a constexpr array that spans from 0 to a specified integer n requires a bit more effort than in later C versions. Here's how it can be done:

Using a Constexpr Constructor and a Loop:

#include 

template
struct Array {
    constexpr Array() : arr() {
        for (auto i = 0; i != N;   i)
            arr[i] = i;
    }
    int arr[N];
};

int main() {
    constexpr auto a = Array();
    for (auto x : a.arr)
        std::cout 

In this code:

  • The Array struct template represents the constexpr array.
  • The constexpr constructor initializes the array elements from 0 to N-1, using a loop.
  • In main(), an instance of Array is created, and its elements are printed to the console. This should output 0, 1, 2, 3, 4.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3