Map in C++ :
STL in C++ are of great use when it comes to competitive programming. So here were are going to have look at the map stl. This post is based on what I learned about maps and I have tried in simple english.
How to declare a map :
First include the header file #include <map>
then you are ready to go with your map!!!
Declaration syntax :
map<type,type> name;
Examples :
- map<string,int> a;
- map<int,int> b;
- map<char,int> mymap;
How to insert into the map :
You can simply insert like arrays for example
map<string,int> a;
a["hello"]=2;
Or else you can use the
insert function of map like as follows :
map<string,int> a;
a.insert(pair<char,int>("a",10));
How to iterate through all the values in map :
we have to create a map iterator and use begin() and end() functions to iterate through the map,.
map<string,int> a;
a["hello"]=2;
a["hi"]=3;
map<string,int>::iterator it;
for(it=a.begin();it!=a.end();it++)
cout<<it->first<<" "<<it->second;
How to delete a value in map :
We can use
erase() function to delete any values as follows :
a.erase("hello");
How to find whether a value is there are not :
we can use find() or count() method to find whether a key is there are not.
using count() method :
if(a.count(key))
//key exists
using find() method :
cout<<a.find(key)->second;
find() returns 0 if there is no such key otherwise it prints the key's value.
How to print map in reverse order :
we can use reverse iterator function to print the map in reverse order as follows
std::map<string,int>::reverse_iterator it;
for(it=m.rbegin();it!=r.rend();it++)
cout<<it->second<<" ";