任何人都可以建议我,如何在 C++ 中清除 2D 矢量。
我必须编写需要读取 Matrix 、 Process 和 Clear Matrix 的程序,并为下一次读取操作做好准备。我已经使用向量创建了二维数组>我正在填充但无法重置。下面是参考代码。
#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;
}
}
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);
您还可以使用常规的 for 循环,如下所示:
for (size_t y = 0; y < matrix.size(); y++)
{
for (size_t x = 0; x < matrix[y].size(); x++)
{
matrix[y][x] = 0;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)