Wednesday, March 28, 2018

Write a C++ program to illustrate map and map operations.


AIM: Write a C++ 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<<"\n Enter item name";
                        cin>>item_name;
                        cout<<"\n 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<<"\n size of map"<<sz<<"int n";
            cout<<"\n list of item name and code:";
            item_map::iterator t;
            for(t=item.begin();t!=item.end();t++)
            {
                        cout<<(*t).first<<" "<<(*t).second<<"\n";
                        cout<<"\n";
            }
            cout<<"\n ENter item name";
            cin>>item_name;
            code_no=item[item_name];
            cout<<"\n code_no:"<<code_no<<"\n";
            return 0;
}

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home