Thursday, July 16, 2015

Ways of access the first and second item in MAP class in C++

Here is an example that can help quickly understand how to access the items in map. Here a simple example is given:
/////////////////////////////////////////
       map<const char*, int> months;

       months["january"] = 31;// Notes: months["january"] = 31; first item can be considered as index and the second is the value. 
                              
       months["february"] = 28;
       months["march"] = 31;
       months["april"] = 30;
       months["may"] = 31;
       months["june"] = 30;
       months["july"] = 31;
       months["august"] = 31;
       months["september"] = 30;
       months["october"] = 31;
       months["november"] = 30;
       months["december"] = 31;

       cout << "june -> " << months["june"] << endl; //so the second value can be accessed as //months["december"], and you get result is 31


       map<const char*, int>::iterator cur = months.find("june"); //the iterator here works like a special pointer that points to a pair of value (the first and second value)


       map<const char*, int>::iterator prev = cur;
       map<const char*, int>::iterator next = cur;
       ++next;
       --prev;

//So, the second value can also be accessed by the 'pointer' 
like '(*cur).second' or cur->second, and you get value 30. 
       cout << "Previous (in alphabetical order) is " << (*prev).first << endl;

//But the first item can only accessed by iterator like '(*cur).first' or 'cur->first', and you get value june.
       cout << "Next (in alphabetical order) is " << (*next).first << endl;

---------------------------------------------------------------------------

In summary, we have one method to access the first item like:
 (*cur).first or cur->first;

And two methods can be used to access the second item:
months["december"]
~~~~~~~~~and~~~~~~~~~
(*cur).second or cur->second;

And the iterator can be changed like prev++ or prev-- to access values in other pairs. The best way to have a full understand of the use of map is to read the reference of map somewhere like cplusplus.com.




No comments:

Post a Comment