AIM: Write a program to illustrate map and map operations.
THEORY:
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values.
Functions associated with Map:
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
SOURCE CODE:
#include<iostream>
#include<map>
#include<string>
using namespace std;
typedef map<string,int>item_map;
int main()
{
int sz;
string item_name;
int code_no;
item_map item;
for(int i=0;i<2;i++)
{
cout<<“Enter item name: “;
cin>>item_name;
cout<<“Enter code number: “;
cin>>code_no;
item[item_name]=code_no;
}
item[“PC”]=2510;
item.insert(pair<string,int>(“Printer”,211));
sz=item.size();
cout<<“Size of map “<<sz<<endl;
cout<<“List of items name and code:\n”;
item_map::iterator t;
for(t=item.begin();t!=item.end();t++)
{
cout<<(*t).first<<” “<<(*t).second<<“\n”;
}
cout<<“ENter item name: “;
cin>>item_name;
code_no=item[item_name];
cout<<“code_no:”<<code_no<<“\n”;
return 0;
}
OUTPUT:
Enter item name: Soap
Enter item code: 111
Enter item name: Sugar
Enter item code: 112
Size of map 4
List of items name and code:
PC 2510
Printer 211
Soap 111
Sugar 112
Enter item name: soap
Code_no: 111