C++容器的迭代器失效规则是什么?
优选地以摘要列表格式.
(注意:这是Stack Overflow的C++常见问题解答的一个条目.如果你想批评在这种形式下提供常见问题解答的想法,那么发布所有这些的元数据的发布将是这样做的地方.这个问题在C++聊天室中受到监控,其中FAQ的想法一开始就出现了,所以你的答案很可能被那些提出想法的人阅读.)
我在STL中使用了std :: map.在将一些其他元素插入地图后,我可以使用迭代器吗?它仍然有效吗?
请考虑以下情形:
map(T,S*) & GetMap(); //Forward decleration
map(T, S*) T2pS = GetMap();
for(map(T, S*)::iterator it = T2pS.begin(); it != T2pS.end(); ++it)
{
if(it->second != NULL)
{
delete it->second;
it->second = NULL;
}
T2pS.erase(it);
//In VS2005, after the erase, we will crash on the ++it of the for loop.
//In UNIX, Linux, this doesn't crash.
}//for
Run Code Online (Sandbox Code Playgroud)
在我看来,在VS2005中,在"擦除"之后,迭代器将等于end(),因此在尝试增加它时崩溃.在这里呈现的行为中,编译器之间是否存在真正的差异?如果是这样,"擦除"之后的迭代器将在UNIX/Linux中等于什么?
谢谢...
让我们考虑以下 C++ 代码
#include <iostream>
#include <vector>
class A {
int x, y;
public:
A(int x, int y) : x(x), y(y){}
friend std::ostream & operator << (std::ostream & os, const A & a){
os << a.x << " " << a.y;
return os;
}
};
int main(){
std::vector<A> a;
std::vector<const A*> b;
for(int i = 0; i < 5; i++){
a.push_back(A(i, i + 1));
b.push_back(&a[i]);
}
while(!a.empty()){
a.pop_back();
}
for(auto x : b)
std::cout << *x << std::endl;
return 0; …Run Code Online (Sandbox Code Playgroud)