Sunday, February 9, 2014

STL map

Map is another STL container and is aother good way of keeping data. We declare map like this.
map<type1 , type2> m;
Basically this map means that we keep data of type 2 with indexses of data type1. This sounds complicated but I will try to be more clear. For example we want to keep a list of names and surnames. We can do that with map.
If we assign map<string,string> m;
this emans that the following expression is legal m["Smith"]="John"; We can consider the first data type we assign to map as the index data type. So in our example "Smith" is the index and "John" is the value. When we are declaring an ordinary array int a[10000]. then we can use the following expression a[10],a[1] but not a[-25] because the indexing starts with 0. You can imagin map as a little more enhanced version of array. So , one more time map<type1 /*index data type*/ , type2 /*value data type*/> m;
examples
map<string,int> m;
m["John"]=0;

map<int, int > m;
m[-10000]=902;

map<unsigend int,int> m;
m[10]=34; //Note that map<unsigend int,int> m has the same effect as the regular array because the indexing starts with non negative numbers

And one more important question, the memory usage. When we first declare the map it is using almost no memory. When the first value is attached, ( for example we have map<string,string> m; and we write m["John"]="Smith") some memoryis being taken only for storing one elment and somehow keep its index. When we assign another value , it checks if the index we use has already been used he just replaces already taken memory with anotehr value if its new than he take memory again. Example
map<string,string> m;
m["John"]="Smith";
takes memory for storing the value "Smith" under the index "John";
m["Johny"]="Smith";
Takes memory because the index "Jonhy" was unused.
m["John"]="Brown";
Already has a memory for the idnex "John" so just replaces the value "Smith" with teh value "Brown";

Looping over maps is being done with iterators.
Now some important functions

m.begin()
return the value for iterator which shows the beginning of the map. IMPORTANT map always starts looping from teh lowest index to the highest.

m.clear()
clears the map completely.

b.empty()
boolean function which returns true if the map is empty and false if it is not.

m.end()
returns the end of the map for iterator.
Looping over map is accomplished like this.
map<type1,type2> m;
........................
........................
........................
map<type1,type2>::iterator it;
for(it=m.begin();it!=m.end();it++)
{
}
m.erase()
This function ca be used in more than 1 ways. If you give a single iterator to it it will remove the element which has that iterator. If you give 2 iterators it will remove all teh elements between these 2 iterators.

m.find( value)
retuns and iterator, needs a value to find it.

m.size()
returns the size of the map= the number of elements in the map.

No comments:

Post a Comment