How do I clear 2D Vector in C++

14,694

Solution 1

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;

Solution 2

Here are two ways in C++11

std::for_each(matrix.begin(), matrix.end(), [](std::vector<int>& v)
{
    std::fill(v.begin(), v.end(), 0);
});

or

for(auto elem& : matrix) std::fill(elem.begin(), elem.end(), 0);

You could also use a regular for loop

for (size_t y = 0; y < matrix.size(); y++)
{
    for (size_t x = 0; x < matrix[y].size(); x++)
    {
        matrix[y][x] = 0;
    }
}
Share:
14,694
Sandeep
Author by

Sandeep

Updated on June 04, 2022

Comments

  • Sandeep
    Sandeep almost 2 years

    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;
        }
    }