I am iterating a map
in C++
using a for loop
but it is stucking in an infinite loop. I have searched for other similar questions and the closest one is this question, but answer to that question doesn't answer my query because in that question the author is making changes to the map object but I am not making any changes to the map object during the for loop
.
My code is follows (I tried commenting different lines and figured out that infinite loop is caused by 11th line (else statement
) but I couldn't figure out the exact problem ):
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;
}