如何在C ++中清除2D矢量

时间:2021-06-29 20:56:34

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.

任何人都可以建议我,如何在C ++中清除2D矢量。我必须编写需要在Matrix,Process和Clear Matrix中读取的程序,并为下一次读操作做好准备。我用矢量创建了2D数组>我正在填充但是没有重置。以下是供参考的代码。

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

2 个解决方案

#1


2  

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;

#2


4  

Here are two ways in C++11

以下是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循环

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

#1


2  

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;

#2


4  

Here are two ways in C++11

以下是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循环

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