Inserting elements in multidimensional Vector

前端 未结 2 988
悲&欢浪女
悲&欢浪女 2020-12-01 22:17
vector> sort_a;
vector v2;
vector v3;

for (int i=0; i<4; ++i) {
v2.push_back(i);

  for (int j=0; j<4; ++j) {
           


        
2条回答
  •  自闭症患者
    2020-12-01 23:08

    a vector> is not the best implementation for a multidimensional storage. The following implantation works for me.

    template
    class array_2d {
        std::size_t data;
        std::size_t col_max;
        std::size_t row_max;
        std::vector a;
    public:
        array_2d(std::size_t col, std::size_t row) 
             : data(col*row), col_max(col), row_max(row), a(data)
        {}
    
        T& operator()(std::size_t col, std::size_t row) {
            assert(col_max > col && row_max > row)
            return a[col_max*col + row];
        }
    };
    

    use case:

    array_2d a(2,2);
    a(0,0) = 1;
    cout << a(0,0) << endl;
    

    This solution is similar to the one described here.

提交回复
热议问题