Sandeep
Sandeep

Reputation: 420

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

Upvotes: 2

Views: 20322

Answers (3)

Neil Kirk
Neil Kirk

Reputation: 21813

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 like this:

for (size_t y = 0; y < matrix.size(); y++)
{
    for (size_t x = 0; x < matrix[y].size(); x++)
    {
        matrix[y][x] = 0;
    }
}

Upvotes: 4

Meshkat Shadik
Meshkat Shadik

Reputation: 337

Sorry for the late here, actually I didn't know about coding back in 2014. I have got a result, I hope you can try with memset.

 memset(matrix,0,sizeof(matrix));

Upvotes: -2

Jarod42
Jarod42

Reputation: 218343

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;

Upvotes: 2

Related Questions