In this article we see how & why to use std::map in c++.

std::map Introduction

std::map is an associative container that store elements in key-value pair.

Benefits of using std::map :

  • It stores only unique keys and that too in sorted order based on its assigned sorting criteria.
  • As keys are in sorted order therefore searching element in map through key is very fast i.e. it takes logarithmic time.
  • In std::map there will be only one value attached with the every key.
  • std::map can be used as associative arrays.
  • It might be implemented using balanced binary trees.

Lets see an example,

Output:

earth :: 4
moon :: 2
sun :: 3
Element with key ‘earth’ not inserted because already existed
word ‘sun’ found
word ‘mars’ not found

Creating std::map objects

Creating a std::map of words i.e.

Key = Word (std::string)
Value = Word’s frequency count (int)

As no external sorting criteria for key(std::string) is specified in above std::map, therefore it will use default key sorting criteria i.e operator < and all elements will be arranged inside std::map in alphabetical sorted order of keys.

Inserting data in std::map :

Inserting data using insert member function,

We can also insert data in std::map using operator [] i.e.

Different between operator [] and insert function:

If specified key already existed in map then operator [] will silently change its value where as insert will not replace already added key instead it returns the information i.e. if element is added or not. e.g.

Where as for insert member function,

will return false.

Iterating through all std::map elements:

Each entry in std::map<std::string, int> is std::pair<std::string, int> therefore through iterator,
key can be accessed by it->first and value by it->second .

Searching element in std::map by key

find member function of std::map can be used to search element in std::map by key. If specified key is not present then it returns the std::map::end else an iterator to the searched element.

Searching element in std::map by Value

To search element in std::map by value we need to iterate through all of the elements and check for the passed value and return i.e.

Output:

sun :: 3

Deleting data from std::map

std::map’s erase member function is used to delete the element in std::map i.e.

Code example,