[C++] Maps
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 mapend()
— Returns an iterator to the theoretical element that follows last element in the mapsize()
— Returns the number of elements in the mapmax_size()
— Returns the maximum number of elements that the map can holdempty()
— Returns whether the map is emptypair insert(keyvalue,mapvalue)
— Adds a new element to the maperase(iterator position)
— Removes the element at the position pointed by the iteratorerase(const g)
- Removes the key value ‘g’ from the mapclear()
— Removes all the elements from the mapkey_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 endcount(const g)
— Returns the number of matches to element with key value ‘g’ in the maplower_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 mapupper_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;
}
}