如何清除 C++ 中的 2D 矢量 [英] How do I clear 2D Vector in C++

查看:33
本文介绍了如何清除 C++ 中的 2D 矢量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

另一种选择是:

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

每次你想重置矩阵时:

matrix = matrix_zero;

这篇关于如何清除 C++ 中的 2D 矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆