Home >Backend Development >C++ >How to Initialize a C 11 `constexpr` Array from 0 to N?

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

DDD
DDDOriginal
2024-12-11 05:19:10259browse

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 <iostream>

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

int main() {
    constexpr auto a = Array<5>();
    for (auto x : a.arr)
        std::cout << x << '\n';
}

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<5> is created, and its elements are printed to the console. This should output 0, 1, 2, 3, 4.

The above is the detailed content of How to Initialize a C 11 `constexpr` Array from 0 to N?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn