Thursday 21 January 2016

STL map example

#include <iostream>
#include <map>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
        //Initialize
        map<string, int> m;// = {{"Sundar", 1}, {"Priyanka", 2}};
        m["Sundar"] = 1;
        m["Priyanka"] = 2;
        map<string, int> m2(m);
        map<string, int> m3(m2.begin(), m2.end());

        map<string, int> m4;
        m4["Ambi"] = 10;
        m4["jay"] = 11;

        //Insert
        m.insert(pair<string, int>("Leela", 3));
        m.insert(m.begin(), pair<string, int>("Paramesh", 4));
        m.insert(m.begin(), pair<string, int>("Revanth", 5));
        m.insert(m4.begin(), m4.end());

        //Delete
        m.erase(m.begin());
        m.erase(m.begin(), ++m.begin());

        //Search
        map<string, int>::iterator it1 = m.find("Revanth");
        cout<<"Found: "<<it1->first<<" "<<it1->second<<endl;

        //Traverse
        for(map<string, int>::iterator it = m.begin(); it != m.end(); it++)
                cout<<it->first<<" : "<<it->second<<" ";
        cout<<endl;

        //Clear
        m.clear();
}

No comments:

Post a Comment