Inserting elements in multidimensional Vector

前端 未结 2 981
悲&欢浪女
悲&欢浪女 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 22:54

    Don't think of it as a multidimentional vector, think of it as a vector of vectors.

    int n = 4;
    std::vector<std::vector<int>> vec(n, std::vector<int>(n));
    
    // looping through outer vector vec
    for (int i = 0; i < n; i++) {
      // looping through inner vector vec[i]
      for (int j = 0; j < n; j++) {
        (vec[i])[j] = i*n + j;
      }
    }
    

    I included parentheses in (vec[i])[j] just for understanding.

    Edit:

    If you want to fill your vector via push_back, you can create a temporary vector in the inner loop, fill it, and then push_back it to your vector:

    for (int i = 0; i < n; i++) {
      std::vector<int> temp_vec;
    
      for (int j = 0; j < n; j++) {
        temp_vec.push_back(j);
      }
    
      vec.push_back(temp_vec);
    }
    

    However, push_back calls result in slower code, since not only you need to reallocate your vector all the time, but also you have to create a temporary and copy it.

    0 讨论(0)
  • 2020-12-01 23:08

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

    template<typename T>
    class array_2d {
        std::size_t data;
        std::size_t col_max;
        std::size_t row_max;
        std::vector<T> 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<int> a(2,2);
    a(0,0) = 1;
    cout << a(0,0) << endl;
    

    This solution is similar to the one described here.

    0 讨论(0)
提交回复
热议问题