繁体   English   中英

C++ Map 迭代器陷入无限循环

[英]C++ Map iterator stucks in infinite for loop

我正在使用for loopC++中迭代map ,但它陷入了无限循环。 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在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;
}

这一行:

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

如果键a+k不存在,确实会向map添加一个新元素。

a这里一个键,所以dic[a]可以正常工作。 但是,当k不为0时,您将面临访问不存在的 map 元素的风险。

如果要检查特定键是否存在,请使用map::find

此外,您观察到此代码导致无限循环是有效的,但在技术上是不正确的。 键类型只能具有有限数量的值,因此最终循环将终止。 不过可能需要相当长的时间。 这假设您只使用不会溢出int的键。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM