一道OJ算法题中有关迭代器错误的原因求解


   
  #include<iostream>
  
#include<map>
#include<vector>

using namespace std;

int main()
{
int n,a,b;
int count1 = 0,count2 = 0;
map<int ,int> p;
vector<int> xm;
vector<int> xy;
while(scanf("%d",&n) != EOF)
{
for(int i = 0;i < n;++i)
{
scanf("%d%d",&a,&b);
p[a] = b;
}
vector<int>::iterator iter1;
xm.push_back(p[1]);
iter1 = xm.begin();
while(p.count(*iter1))
{
xm.push_back(p[*iter1]);
++iter1;
}
vector<int>::iterator iter2;
xy.push_back(p[2]);
iter2 = xy.begin();
while(p.count(*iter2))
{
xy.push_back(p[*iter2]);
++iter2;
}
iter1 = xm.begin();
iter2 = xy.begin();
int flag = 0;
for(;iter1 != xm.end();++iter1,++count1)
{
if(flag)
break;
for(;iter2 != xy.end();++iter2,++count2)
{
if(*iter1 == *iter2)
{
if(count1 == count2)
{
printf("%s\n","You are my brother");
flag = 1;
}
else if(count1 > count2)
{
printf("%s\n","You are my elder");
flag = 1;
}
else
{
printf("%s\n","You are my younger");
flag = 1;
}
}
}
count2 = 0;
}
}

return 0;
}

大家好,我想问一下为什么在我执行代码执行到++iter1的时候,总是出现Debug Assertion Failed的错误,出现的是对话框,提示是:Expression:("this->_Has_container()",()),这事什么原因了?该如何解决呢?

c C++

逼人吃精无压力 10 years, 7 months ago

C++ 标准容器中有很多的“潜规则”,其中之一就是:在容器大小变化之后,之前取得的迭代器不可用。对于 vector 容器尤其如此。

设想一下,iter 指向 vector 中某元素,然后给 vector 追加一个元素,导致重新分配内存,vector 的内容全部“搬家”,然后再来使用 iter ……

事实上,出错信息已经很明显了:迭代器没有对应的容器。

天朝围观群众 answered 10 years, 7 months ago

Your Answer