我在 reachability.cpp
中遇到了这一行在 Coursera 上图算法的作业 1 中 n
是顶点数和m
是来自 cin
的边数.
vector<vector<int> > adj(n, vector<int>());
第二个参数是什么?我认为这会生成一个带有 n
的二维 vector 行,每行都有一个 vector(int)
但是这里的其他答案都没有提到第二个论点,我在 cpp 引用和其他来源上找不到任何内容。
我试图明确说明列的大小并像这样用 0 初始化:
vector<vector<int> > adj(n, vector<int>(n, 0));
因为我想用下面的函数打印出形状来确认我有一个邻接矩阵。
void print(vector<vector<int> > &a)
{
std::cout<<"Vec elements:\n";
for(unsigned int j =0; j<a.size(); j++)
{
for(unsigned int k =0; k<a[j].size(); k++)
{
std::cout<<a[k][j]<<" ";
}
}
}
我还有其他代码,我只需要像这样制作一个 2D vector :
vector<vector<int> > graph;
然后我将每一行的大小调整为 n
带有循环的列以构成邻接矩阵。
for(i=0;i<n;i++)
graph[i].resize(n); //resize 2d array
因为这是讲师提供的样板代码,所以他们所做的一定有一些优点。所以我想知道它是什么。
编辑:
在 Gaddis 的书中看到这个:
所以我猜它正在制作 n
的 vector 元素,每个元素都是一个 vector<int>
.
最佳答案
What is that second argument? I think this makes a 2D vector with n rows, each having a vector(int)
是的,没错。
第二个参数是 [outer] vector 的每个元素的“初始值”。在这里你说的是每个元素,这又是一个 vector<int>
, 将只是默认构造的。 (好吧,从这个默认构造的临时构造的拷贝!)
请注意,与其他答案中的声明相反,您使用的构造函数不是 vector( const vector& other, const Allocator& alloc )
,但是 vector( size_type count, const T& value, const Allocator& alloc = Allocator())
(第三个参数保留为默认值)。这个问题与分配器无关。
但是,您确实也可以使用 explicit vector( size_type count, const Allocator& alloc = Allocator() )
并依赖于内部 vector 的默认构造:
vector<vector<int> > adj(n);
关于c++ - cpp 二维 vector 参数(大小,?)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57222115/