C++ static map

·

3 min read

##Where can we find map?

Map is found at STL (standard template library). In C++, STL is a collection of generic classes and functions. Because of STL, reusability of developed code increased. No rewriting of code. Image description

##Container and set Knowing the definitions of container and set are very important before defining map.

  • Container: is an object. It is used to store multiple elements. Those elements can be same type or different.

  • Set: is a special container or data structure that store unique elements of the same type in order. It is a collection of elements with no duplicates. Operations like add, contains, and remove are fast.

The code shown below is used for creating new empty set.

#include

#include // std::set

using namespace std;

int main ()

{

// new set created by the name of set_a

}

##Map / static map / std::map Maps: are part of the C++ STL (Standard Template Library) which are associative containers, contains stored key-value pairs with unique keys. In simple words; Map is a collection of pairs (k, v), sometimes called key/value pairs, where v can be found quickly if you know k. Comparison function compare used to store keys. Each key may occur only and only once, thus duplicate keys are not allowed. Operations which have logarithmic complexity are Search, removal, and insertion.

map example_one;

simple example to create map shown on below:

#include

#include

#include

using namespace std;

int main()

{

  map example_one;

  example_one.insert(pair(1, "wonderful"));

  example_one.insert(pair(2, "day"));

  cout << example_one[1] << " " << example_one[2] << endl;</code>

  return 0;

}

Output for the above code is:

wonderful day

##Use of std::map The main two uses of std::map is Faster access of data & No duplication of data. Through keys there is a fast access of elements. And every key is unique in the maps so duplication is not an issue.

##Types of maps There are three types of Maps. Let us see them one by one.

  • Regular Map: this type of map has a simple key type and value. Keys on regular map must be unique as well as ordered.
  • Multi-Map: this type of map uses multiple type of elements with the same key. It allows multiple key/value pairs with same key to be stored in the map.
  • Hash-Map: it is similar to regular map but the only difference is on hash map there is no storing of elements with respect to key. It uses quick access for the needed K-V pair.

##Summary

    • Container is used to store multiple elements
    • Sets is a special container or data structure that store unique elements of the same type in order.
    • Map is a collection of pairs (k, v), sometimes called key/value pairs.
    • When defining maps two types (K & V) are mandatory. i.e. Map
    • The main use of map is Fasts access of data & No duplication of data.
    • There are three types of maps: regular, multi and hash map.