Traversing a map (or unordered_map) in C++ STL

C++Server Side ProgrammingProgramming

Here we will see the map container and its use in C++. The maps are defined as associative containers that store elements in a hash-mapped fashion. Each element is associated with a key and value. No two mapped values can have identical keys. These are some fundamental methods that are present inside the map container in C++.

begin(): This returns an iterator to the first element in the map.

end()− This returns an iterator to the theoretical element that follows last element in the map.

size() − This returns the number of elements in the map.

max_size() − This returns the maximum number of elements that the map can hold.

empty() − This returns whether the map is empty or not.

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main() {
   int A[] = { 2, 2, 3, 2, 2, 4, 5, 4 };
   int num = sizeof(A) / sizeof(A[0]);
   map<int, int> my_map;
   for (int p = 0; p < num; p++)
      my_map[A[p]]++;
   cout <<"Item Frequency"<< endl;
   for (auto p : my_map)
      cout << p.first <<" : "<< p.second << endl;
}

Output

Item Frequency
2 : 4
3 : 1
4 : 2
5 : 1

The unordered_map is another type of map container present in C++ STL. This is an associated container that collects or stores elements formed by combination of key value pair. The key is used to uniquely identify the value. In this case, both key and value can be of any type predefined or user-defined.

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main() {
   int A[] = { 2, 2, 3, 2, 2, 4, 5, 4 };
   int num = sizeof(A) / sizeof(A[0]);
   unordered_map<int, int> my_map;
   for (int p = 0; p < num; p++)
      my_map[A[p]]++;
   cout <<Item Frequency"<< endl;
   for (auto p : my_map)
      cout << p.first <<" : "<< p.second << endl;
}

Output

Item Frequency
5 : 1
4 : 2
2 : 4
3 : 1
raja
Published on 27-Aug-2020 13:50:41
Advertisements