【发布时间】:2020-04-22 13:29:26
【问题描述】:
我正在使用for loop 在C++ 中迭代map,但它陷入了无限循环。我已经搜索过其他类似的问题,最接近的问题是this question,但对该问题的回答并未回答我的查询,因为在该问题中作者正在对地图对象进行更改,但我没有对地图进行任何更改for loop 期间的对象。
我的代码如下(我尝试注释不同的行并发现无限循环是由第 11 行(else statement)引起的,但我无法弄清楚确切的问题):
int main(){
map<int,int> dic; //dic is the relevant map object
dic[0]=1; dic[1]=1; dic[2]=1; dic[3]=1; //dic = {0:1, 1:1, 2:1, 3:1}
int k=1;
int sol=0;
for(map<int,int>::iterator iter=dic.begin(); iter!=dic.end(); iter++){
int a=iter->first; int b=iter->second;
if(k==0) sol+=b*(b-1)/2;
else sol+=b*dic[a+k]; //after some trials, I found that problem is in this line but I couldn't figure out the problem
}
return sol;
}
【问题讨论】:
标签: c++ dictionary infinite-loop