Friday, February 22, 2013

C++: 3 Dimensional STL Vector with dynamic Re-sizing

Problem:

I want to create a 3 Dimensional Array whose dimensions are not known a priori. Let us that our 3 dimensional array is A[NP][NR][NC].  In my case, I know NP and NC a priori (before the execution of the program), but NR will be known only during run time.

Well I could make this array using pointers and using dynamic allocation functions like new/delete to get the desired effect. That is something I do regularly.

STL Vectors provide much better interface with several useful functions that can make your life lot easier. For instance, it is possible to resize these vectors during runtime. You can check for index bounds while accessing the elements etc.

So, I want to use STL vector to solve this problem.

Solution:

The following code demonstrates two ways by which you can accomplish the above objective.


  size_t np = 5; // no of pages
  size_t nc = 2; // no. of columns
  

  Method 1: Keep pushing the matrices into the page


  std::vector > matrix;
  std::vector > >page;

  for(size_t i = 0; i < np; ++i)
  {
    matrix.resize(i+1, std::vector(nc));
    for(size_t j = 0; j < matrix.size(); ++j)
    {
      for(size_t k = 0; k < matrix[j].size(); ++k)
        matrix.at(j).at(k) = rand()/(double)RAND_MAX;
    }
    page.push_back(matrix);
  }   


Method 2: Dynamically re-sizing 3D Array

  std::vector < std::vector > > page;

  page.resize(np); //np is known

  for(size_t i = 0; i < np; ++i)
  {
    page[i].resize(i+1, std::vector(nc));
    for(size_t j = 0; j < page[i].size(); ++j)
      for(size_t k = 0; k < page[i][j].size(); ++k)
        page[i][j][k] = rand()/(double)RAND_MAX;
  }        

           

                                


No comments: