How to update std::map after using the find method?

后端 未结 6 1342
自闭症患者
自闭症患者 2020-12-12 12:11

How to update the value of a key in std::map after using the find method?

I have a map and iterator declaration like this:

         


        
6条回答
  •  [愿得一人]
    2020-12-12 13:07

    If you already know the key, you can directly update the value at that key using m[key] = new_value

    Here is a sample code that might help:

    map m;
    
    for(int i=0; i<5; i++)
        m[i] = i;
    
    for(auto it=m.begin(); it!=m.end(); it++)
        cout<second<<" ";
    //Output: 0 1 2 3 4
    
    m[4] = 7;  //updating value at key 4 here
    
    cout<<"\n"; //Change line
    
    for(auto it=m.begin(); it!=m.end(); it++)
        cout<second<<" ";
    // Output: 0 1 2 3 7    
    

提交回复
热议问题