[c++] How to update std::map after using the find method?

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:

map <char, int> m1;
map <char, int>::iterator m1_it;
typedef pair <char, int> count_pair;

I'm using the map to store the number of occurrences of a character.

I'm using Visual C++ 2010.

This question is related to c++ map stl stdmap

The answer is


I would use the operator[].

map <char, int> m1;

m1['G'] ++;  // If the element 'G' does not exist then it is created and 
             // initialized to zero. A reference to the internal value
             // is returned. so that the ++ operator can be applied.

// If 'G' did not exist it now exist and is 1.
// If 'G' had a value of 'n' it now has a value of 'n+1'

So using this technique it becomes really easy to read all the character from a stream and count them:

map <char, int>                m1;
std::ifstream                  file("Plop");
std::istreambuf_iterator<char> end;

for(std::istreambuf_iterator<char> loop(file); loop != end; ++loop)
{
    ++m1[*loop]; // prefer prefix increment out of habbit
}

You can use std::map::at member function, it returns a reference to the mapped value of the element identified with key k.

std::map<char,int> mymap = {
                               { 'a', 0 },
                               { 'b', 0 },
                           };

  mymap.at('a') = 10;
  mymap.at('b') = 20;

You can update the value like following

   auto itr = m.find('ch'); 
     if (itr != m.end()){
           (*itr).second = 98;
     }

You can also do like this-

 std::map<char, int>::iterator it = m.find('c'); 
 if (it != m.end())
 (*it).second = 42;

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<int, int> m;

for(int i=0; i<5; i++)
    m[i] = i;

for(auto it=m.begin(); it!=m.end(); it++)
    cout<<it->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<<it->second<<" ";
// Output: 0 1 2 3 7    

Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to map

Using array map to filter results with if conditional In Java 8 how do I transform a Map<K,V> to another Map<K,V> using a lambda? UnmodifiableMap (Java Collections) vs ImmutableMap (Google) Convert JSONObject to Map Convert Map<String,Object> to Map<String,String> iterate through a map in javascript Iterator over HashMap in Java Simple dictionary in C++ Create Map in Java Map with Key as String and Value as List in Groovy

Examples related to stl

Why is it OK to return a 'vector' from a function? How to remove all the occurrences of a char in c++ string How to use the priority queue STL for objects? use std::fill to populate vector with increasing numbers What does iterator->second mean? How to set initial size of std::vector? Sorting a vector in descending order How do I reverse a C++ vector? Recommended way to insert elements into map Replace an element into a specific position of a vector

Examples related to stdmap

How can I get a value from a map? Recommended way to insert elements into map How can I create my own comparator for a map? How to update std::map after using the find method? What is the preferred/idiomatic way to insert into a map? Use of for_each on map elements How can I use std::maps with user-defined types as key? How to iterate over a std::map full of strings in C++ In STL maps, is it better to use map::insert than []? Initializing a static std::map<int, int> in C++