Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

less verbose way to declare multidimensional std::array

Short question: Is there a shorter way to do this

array<array<atomic<int>,n>,m> matrix;

I was hoping for something like

array< atomic< int>,n,m> matrix;    

but it doesnt work...

like image 221
NoSenseEtAl Avatar asked Oct 07 '11 15:10

NoSenseEtAl


People also ask

Can C language handle multidimensional arrays?

In C programming, you can create an array of arrays. These arrays are known as multidimensional arrays. For example, float x[3][4];


2 Answers

A template alias might help out:

#include <array>

template <class T, unsigned I, unsigned J>
using Matrix = std::array<std::array<T, J>, I>;

int main()
{
    Matrix<int, 3, 4> matrix;
}
like image 151
Howard Hinnant Avatar answered Oct 20 '22 05:10

Howard Hinnant


A palatable workaround for compilers that don't support template aliases yet is to use a simple metafunction to generate the type:

#include <cstddef>
#include <array>

template<class T, std::size_t RowsN, std::size_t ColumnsN>
struct Matrix
{
    typedef std::array<std::array<T, ColumnsN>, RowsN> type; // row major

private:
    Matrix(); // prevent accidental construction of the metafunction itself
};

int main()
{
    Matrix<int, 3, 4>::type matrix;
}
like image 22
ildjarn Avatar answered Oct 20 '22 03:10

ildjarn