djuwaste
djuwaste

Reputation: 21

What is the best way to initalize 2D std::array along with its rows and cols?

I want to find the best possible way of initializing std:array in the below configuration (a better way would be able to use the cols and rows variables while declaring the array size):

class Engine {
protected:
    const int rows = 30;
    const int cols = 100;
    std::array<std::array<int, 100>, 30> arr;
}

How do initialize it properly? I mean, my rows and cols are going to be const, so:

Anyway, I want to find the best possible (ie golden standard) way of initializing it, while I know how my array will look like at compile time.

Upvotes: 1

Views: 90

Answers (2)

Chris
Chris

Reputation: 36621

It would seem reasonable to make these template parameters.

template <std::size_t rows = 30, std::size_t cols = 100>
class Engine {
protected:   
    std::array<std::array<int, cols>, rows> arr;
};

Upvotes: 2

Alan
Alan

Reputation: 1

Anyway, I want to find the best possible (ie golden standard) way of initializing it, while I know how my array will look like at compile time.

You can use static constexpr as shown below:

class Engine {
protected:
    static constexpr std::size_t rows = 30;
    static constexpr std::size_t cols = 100;
    std::array<std::array<int, cols>, rows> arr;
};

Upvotes: 3

Related Questions