Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

map

stl

stdmap

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.

like image 595
jaykumarark Avatar asked Dec 24 '10 18:12

jaykumarark


People also ask

How do you update a map value in C++?

C++ map update – Simple program example to update value in map. To update an existing value in the map, first we will find the value with the given key using map::find() function. If the key exists, then will update it with new value.

How does map Find () work?

find() is used to search for the key-value pair and accepts the “key” in its argument to find it. This function returns the pointer to the element if the element is found, else it returns the pointer pointing to the last position of map i.e “map.

What does map return if key not found C++?

map find() function in C++ STL Return Value: The function returns an iterator or a constant iterator which refers to the position where the key is present in the map. If the key is not present in the map container, it returns an iterator or a constant iterator which refers to map. end().

How do I add items to a map in C++?

The standard solution to insert new elements into a map is using the std::map::insert function. It inserts the specified key-value pair into the map only if the key already doesn't exist. If the key already exists in the map, the element is not inserted.


2 Answers

std::map::find returns an iterator to the found element (or to the end() if the element was not found). So long as the map is not const, you can modify the element pointed to by the iterator:

std::map<char, int> m; m.insert(std::make_pair('c', 0));  // c is for cookie  std::map<char, int>::iterator it = m.find('c');  if (it != m.end())     it->second = 42; 
like image 111
James McNellis Avatar answered Sep 25 '22 08:09

James McNellis


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 } 
like image 44
Martin York Avatar answered Sep 23 '22 08:09

Martin York