为什么变量在局部范围内声明,并放入范围外可见的向量中
Why is a variable declared in a local scope, and put into a vector visible outside the scope?
我的问题是关于以下代码段的:
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;
}
它是否被推到向量上似乎并不重要,leftIndex、rightIndex、p 和 i 都在循环范围之外保持可见。有人能解释一下吗?
我正在使用禁用优化的英特尔 c++ 15.0 编译器。
您在向量中插入完全构造的对象,因此在调用 push_back
时,您实际上是将对象复制(或移动,如果启用)到位于向量中的新对象。然后,这个新对象的作用域与其中一个向量相关联。
相关文章:
- 尝试通过多个向量访问变量时,向量下标超出范围
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- C++ - 使用基于范围的 for 循环将字符值分配给向量中的字符串不会分配值
- 布尔值向量的基于范围 for 循环
- 如何使用count_if计算向量中的可变数字范围
- 范围 v3 的和向量
- 关于在向量向量上使用基于范围的 for 循环
- 使用基于范围的指针循环和向量时出现C++错误
- 用基于范围的for循环填充指针向量
- 创建结构体向量,表达式:向量下标超出范围
- 代码超出范围.如何动态分配此向量?
- 无法取消引用超出范围的向量迭代器 - 有什么问题?
- 非常量对象的向量似乎在基于范围的 for 循环中被视为常量
- 从给定范围内的向量中查找最大元素
- 向量向量的范围范围
- 将局部变量保存到全局向量中,为什么离开局部范围后可以得到这些局部变量?
- 指针范围问题和返回类中封装的指针向量内的指针引用
- 在 c++ 中检查 if 条件中的向量位置范围
- 向量下标超出向量向量的范围
- C++选项定价函数..单独工作很好,但对于股票价格的范围(向量)来说不行