[C++] Maps

Mayank Shekhar
2 min readDec 9, 2017

--

Maps in C++ are data structures in which each value stored is related to a unique key, just like dictionaries in Python. They are also known as associative arrays.

Maps can be used by importing map header file:

#include <map>

A map variable with key and value of type int can be declared as follows:

map <int, int> mapName;

Functions associated with maps are:

begin() — Returns an iterator to the first element in the map
end() — Returns an iterator to the theoretical element that follows last element in the map
size() — Returns the number of elements in the map
max_size() — Returns the maximum number of elements that the map can hold
empty() — Returns whether the map is empty
pair insert(keyvalue,mapvalue) — Adds a new element to the map
erase(iterator position) — Removes the element at the position pointed by the iterator
erase(const g)- Removes the key value ‘g’ from the map
clear() — Removes all the elements from the map
key_comp() / value_comp() — Returns the object that determines how the elements in the map are ordered (‘<’ by default)
find(const g) — Returns an iterator to the element with key value ‘g’ in the map if found, else returns the iterator to end
count(const g) — Returns the number of matches to element with key value ‘g’ in the map
lower_bound(const g) — Returns an iterator to the first element that is equivalent to mapped value with key value ‘g’ or definitely will not go before the element with key value ‘g’ in the map
upper_bound(const g) — Returns an iterator to the first element that is equivalent to mapped value with key value ‘g’ or definitely will go after the element with key value ‘g’ in the map

A key value pair can be inserted as follows:

mapName.insert(pair <int, int> (1, 3));

To erase pairs in between:

mapName.erase(mapName.begin(), mapName.find(4));

In the above code all the pairs from beginning to the pairs having key with value less than 4 are removed.

Example:

#include <map>
#include <iterator>
#include <iostream>
using namespace std;
int main(){
//map to store name and age
map <string, int> info;
map["Mayank"] = 22;
map["Ram"] = 30;
map <string, int>::iterator ptr;
for(ptr = info.begin(); ptr < info.end(); ptr++){
cout<<"NAME\t"<<"AGE"<<endl;
cout<<ptr->first<<ptr->second<<endl;
}
}

--

--

Mayank Shekhar
Mayank Shekhar

Written by Mayank Shekhar

Sharing my experiences (programming and life).

No responses yet