C++ vector > reserve size at beginning

后端 未结 4 1532
轮回少年
轮回少年 2021-01-23 21:52

in c++ I have

vector > table;

How can I resize vector so that it has 3 rows and 4 columns, all zeros?

Someth

4条回答
  •  被撕碎了的回忆
    2021-01-23 22:46

    Don't! You'll have complex code and rubbish memory locality.

    Instead have a vector of twelve integers, wrapped by a class that converts 2D indices into 1D indices.

    template
    struct matrix
    {
       matrix(unsigned m, unsigned n)
         : m(m)
         , n(n)
         , vs(m*n)
       {}
    
       T& operator()(unsigned i, unsigned j)
       {
          return vs[i + m * j];
       }
    
    private:
       unsigned m;
       unsigned n;
       std::vector vs;
    };
    
    int main()
    {
       matrix m(3, 4);   // <-- there's your initialisation
       m(1, 1) = 3;
    }
    

提交回复
热议问题