我是否可以构建一个
vector<vector<int> >使用重复序列构造器?
我知道我可以造一个像这样的
vector<int> v(10, 0);但我不知道如何使用同样的方法构建向量的向量。谢谢!
发布于 2011-06-12 12:56:53
只需向它传递一个向量作为第二个参数:
// 10 x 10 elements, all initialized to 0
vector<vector<int> > v(10, vector<int>(10, 0));发布于 2011-06-12 12:57:30
vector<vector<int> > v(10, vector<int>(30, 0));将创建10个向量,每个向量有30个零。
发布于 2011-06-12 12:57:51
explicit vector ( size_type n, const T& value= T(), const Allocator& = Allocator() );重复序列构造器:通过将其内容设置为value副本的重复n次来初始化向量。
vector< vector<int> > vI2Matrix(3, vector<int>(2,0)); 创建3个向量,每个向量有2个零。
从本质上讲,我们将使用向量的向量来表示二维数组。
下面是一个源代码示例:
#include <iostream>
#include <vector>
using namespace std;
main()
{
// Declare size of two dimensional array and initialize.
vector< vector<int> > vI2Matrix(3, vector<int>(2,0));
vI2Matrix[0][0] = 0;
vI2Matrix[0][1] = 1;
vI2Matrix[1][0] = 10;
vI2Matrix[1][1] = 11;
vI2Matrix[2][0] = 20;
vI2Matrix[2][1] = 21;
cout << "Loop by index:" << endl;
int ii, jj;
for(ii=0; ii < 3; ii++)
{
for(jj=0; jj < 2; jj++)
{
cout << vI2Matrix[ii][jj] << endl;
}
}
return 0;
}https://stackoverflow.com/questions/6320195
复制相似问题