c++ - 迭代器和 vector 的段错误

标签 c++ vector

我似乎在使用迭代器显示 vector 中的项目时遇到问题。可能,我只是需要另一双眼睛来看它。

vector<string> tempVector;
vector<string>::iterator it;


it = tempVector.begin();
tempVector.push_back("1");
cout << *it;

我知道这不是完整的代码,但它是唯一运行的部分。输出是段错误。迭代器不是指向 vector 的开头吗?我期待得到“1”来计算。

最佳答案

如果碰巧需要重新分配,则调用 vector::reserve() 会使所有现有的迭代器失效。

引用C++标准,23.3.6.3[vector.capacity]

Reallocation happens at this point if and only if the current capacity is less than the argument of reserve(). [...] Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence.

编辑:编辑后,您调用了 vector::push_back(),如果它需要重新分配,它也会使所有迭代器失效。 Iterator invalidation rules可能会有帮助。

关于c++ - 迭代器和 vector 的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12505401/

相关文章:

c++ - libsigc++ 并将一个函数作为信号连接到另一个函数作为槽

c++ - 使用 stringstream 将整数分配给 char 指针

c++ - 使用 constexpr 或 struct 进行元编程

c++ - 有什么方法可以将两个或多个不同的类链接到一个类中(然后在 vector 上使用)?

c++ - 修改元组 vector 中的元组 C++

c++ - 纳米 : "U" The symbol is undefined

c++ - 奇怪的段错误

java - vector/泛型搜索 java

c++ - 模型观察矩阵 - C++、OpenGL

c++ - std::vector 的范围 View