初始化列表的2d数组

时间:2017-05-11 20:10:21

标签: c++ constructor

嗨我有写一个构造函数的问题巫婆创建我的2d数组看起来像

1 | 2 | 3 | 4
5 | 6 | 7 | 8
9 |10 | 11| 12
13|14 | 15| 0

这是我的表

的构造函数
fifteen::fifteen( ) : open_i{dimension-1}, open_j{dimension-1}
{
    size_t value = 1;
    for(size_t i = 0; i < dimension; ++i)
    {
        for(size_t j = 0; j < dimension; ++j)
            {table[i][j] = value;
            value++;}
    }

    table[dimension-1][dimension-1] = 0;
} 

但我也用初始化列表

写了这个
fifteen::fifteen( std::initializer_list< std::initializer_list< size_t > > init )

但是idk如何创建具有2d的列表

1 个答案:

答案 0 :(得分:1)

如何在类中创建2D数组:

#include <iostream>
#include <memory>
#include <cmath>

class My2DArray
{
    std::unique_ptr<int[]> data;
    size_t m_width = 0;
    size_t m_height = 0;
public:
    // Constructors
    My2DArray(size_t width, size_t height)
    {
        m_width = width;
        m_height = height;
        data = decltype(data)(new (std::nothrow) int[width*height]);
    }
    My2DArray()=default;
    My2DArray( const My2DArray&a )
    {
        *this = a;
    }
    My2DArray( const std::initializer_list<std::initializer_list<int>> &l)
    {
        size_t lSize = l.size();
        m_width = l.size();
        m_height = 0;
        if (m_width>0) m_height = l.begin()->size();
        data = decltype(data)(new (std::nothrow) int[m_width*m_height]);

        size_t counterW = 0;
        for (auto &row: l)
        {
            size_t counterH = 0;
            for (auto &elem: row) data[counterH++ * m_width+ counterW]=elem;
            counterW++;
        }
    }

    // Copy/move operators
    My2DArray& operator=( const My2DArray &a)
    {
        m_width = a.m_width;
        m_height = a.m_height;
        data = decltype(data)(new (std::nothrow) int[m_width*m_height]);
        for (size_t i=0; i<m_width*m_height; i++) data[i]=a.data[i];
    }


    // Access Operator
    class My2DArrayAccess
    {
        My2DArray &array;
        size_t posHor;
    public:
        My2DArrayAccess( My2DArray &a, size_t h): array(a), posHor(h){};
        int& operator[](size_t v)
        { 
            //TODO asserts for range
            return array.data[v*array.m_width+posHor];
        }
        //TODO const version of operators
    };
    My2DArrayAccess operator[](size_t h)
    { 
        // TODO asserts
        return My2DArrayAccess(*this, h);
    }
    //TODO const version of operators

    // Other access
    size_t width() const {return m_width;}
    size_t height() const {return m_height;}
};

int main()
{
    My2DArray a{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};

    // Display
    for (size_t i=0; i<a.width(); i++)
    {
        for (size_t j=0; j<a.height(); j++)
        {
            std::cout << i << "x" << j << " = " << a[i][j] << std::endl;
        }
    }
}

希望这有帮助。如果您有任何疑问,请发表评论。