我的问题是关于下面的一段代码:
pairVectors.push_back(new vector<CompactPair>());
for (int i = 0; i < generationVectors[0].size(); ++(i))
{
//Find the new indices of the two symbols in this pair
long leftIndex = ((terminalIndices)[(generationVectors[0])[i].leftSymbol]);
long rightIndex = ((terminalIndices)[(generationVectors[0])[i].rightSymbol]);
//Make a pair out of the indices we found, then push it to the vector
CompactPair p(leftIndex, rightIndex);
pairVectors[0]->push_back(p);
//Record the index of this symbol
if (indices[(generationVectors[0])[i].leftSymbol].empty())
{
indices[(generationVectors[0])[i].leftSymbol].set_empty_key(-1);
indices[(generationVectors[0])[i].leftSymbol].set_deleted_key(-2);
}
((indices)[(generationVectors[0])[i].leftSymbol])[(generationVectors[0])[i].rightSymbol] = i + terminals.size();
}
CompactPair p 是使用以下构造函数创建的:
CompactPair::CompactPair(long left, long right)
{
leftSymbol = left;
rightSymbol = right;
}
它是否被推到 vector 上似乎并不重要,leftIndex、rightIndex、p 和 i 在循环范围之外都保持可见。谁能解释一下?
我正在使用禁用优化的英特尔 C++ 15.0 编译器。
最佳答案
您在 vector 中插入完全构建的对象,因此在调用 push_back
时,您实际上是在将对象复制(或移动,如果启用)到位于 vector 中的新对象。然后将这个新对象的范围绑定(bind)到 vector 之一。
关于c++ - 为什么在局部范围内声明一个变量,并放入范围外可见的 vector 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28984874/