我似乎在使用迭代器显示 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/