0

首先,是的,我是 C++ 向量的新手。

现在我的问题是,为什么你认为我的向量是空的?

我有一个全局变量:

vector<int> parentVector;

现在,由于它是一个全局变量,而且我不知道它应该是什么大小,只是稍后进入程序,我在某个时候这样做:

//numberOfNodes = 8 in current example
parentVector.reserve(numberOfNodes);

稍后,我尝试为向量的第一个元素赋值,但它不起作用:

parentVector[0] = -1;

而且我还执行以下操作,这也没有分配任何值:

//nextNode.node and currentNode.node is between the range of 1 - 8, thus the - 1.
parentVector[nextNode.node - 1] = currentNode.node - 1;

编辑:感谢您的回答, resize() 有效。

4

1 回答 1

3

在向量中保留空间 usingstd::vector::reserve与向其添加元素不同。保留后,向量仍然是空的。改为使用std::vector::resize

于 2013-10-27T12:57:58.330 回答