ATK
ATK

Reputation: 368

C++ Map iterator stucks in infinite for loop

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;
}

Upvotes: 0

Views: 477

Answers (1)

cigien
cigien

Reputation: 60430

This line:

sol+=b*dic[a+k];

does add a new element to the map if the key a+k doesn't exist.

a here is a key, so dic[a] would work fine. However, when k is not 0, you run the risk of accessing an element of the map that doesn't exist.

Use map::find if you want to check whether a particular key exists.

Also, your observation that this code results in an infinite loop, is valid, but technically incorrect. There are only a finite number of values that the key type can have, so eventually the loop will terminate. It might take quite a while though. This assumes that you are only ever using keys that don't overflow an int.

Upvotes: 6

Related Questions