Search code examples
c++vectorstl

How do I clear 2D Vector in C++


Can any one please suggest me, How do I clear 2D vector in C++. I have to write program where I need to read in Matrix , Process and Clear Matrix and get ready for next read operation. I have created 2D array with vector> I am filling but failing to reset. Below is the code for reference.

#include<iostream>
#include<vector>
#include<algorithm>


using namespace std;


#define MAX 501
typedef std::vector<std::vector<int>> vec2d;
vec2d matrix(MAX , std::vector<int>(MAX, 0));

void main()
{
    int tc; 
    int N;

    for(tc =0 ; tc < 20;tc++)
    {
        int temp;
        scanf("%d",&N); 

        int result =0;

        for(int i = 0; i < N;i++)
        {
            for(int j=0; j<N;j++)
            {               
                scanf("%d",&temp);
                matrix[i][j]=temp;
            }
        }
        // Do Some processing with 2D vectory Array 

        matrix.clear(); // Now I want to clear 2D vector but only vector contents, and get ready for new input reading  
                    // How do I do it with 2d Vector ? 
        cout << result << endl;
    }
}

Solution

  • An other alternative is:

    matrix = vec2d(MAX , std::vector<int>(MAX, 0));
    

    And to avoid the allocation each time, you may cache the value:

    static const vec2d matrix_zero = vec2d(MAX , std::vector<int>(MAX, 0));
    

    And each time you want to reset matrix:

    matrix = matrix_zero;