In this tutorial we are going to learn how to iterate map in c++. Let us see a very basic example uses of c++ map.

#include <iostream>
#include <map>
#include <iterator>
using namespace std;

int main()
{
    map<int , string> m;
    m.insert(make_pair(12,"Mr. X"));
    m.insert(make_pair(14,"Mr. Y"));
    m.insert(make_pair(15,"Mr. Z"));
    m.insert(make_pair(17,"Ms. X"));

    // print some value from map
    cout << m[17];

    return 0;
}

map in c++ is an associative container. It stores a key value with a mapped objects. For example

m.insert(make_pair(12,"Mr. X"));

The key is 12 and its corresponding mapped value is “Mr. X”. we can access “Mr. X” by using its key like m[12].  cout << m[17] will print “Ms. X”.

how to iterate map in c++

There are different ways , we can iterate over map in c++. Let us discuss one by one.

Iterate over a map using STL Iterator

  • Declare an c++ stl iterator and initialize it using begin() method.
// declare an iterator for map
map<int,string>::iterator it;
// make it point to first element of map
it = m.begin();
  • m.end() method will point to end of map.
  • We can access pair of map using it.first and it.second. it.first gives key and it.second gives mapped value.
#include <iostream>
#include <map>
#include <iterator>
using namespace std;

int main()
{
    map<int, string> m;
    m.insert(make_pair(12, "Mr. X"));
    m.insert(make_pair(14, "Mr. Y"));
    m.insert(make_pair(15, "Mr. Z"));
    m.insert(make_pair(17, "Ms. X"));

    // declare an iterator for map
    map<int, string>::iterator it;
    // make it point to first element of map
    it = m.begin();

    for (;it != m.end(); it++)
    {
        cout << it->first << " " << it->second << endl;
    }

    return 0;
}

iterate map using C++11 range based for loop and auto keyword in c++11

#include <iostream>
#include <map>
#include <iterator>
using namespace std;

int main()
{
    map<int, string> m;
    m.insert(make_pair(12, "Mr. X"));
    m.insert(make_pair(14, "Mr. Y"));
    m.insert(make_pair(15, "Mr. Z"));
    m.insert(make_pair(17, "Ms. X"));

    for (auto &p:m)
    {
        cout << p.first << " " << p.second << endl;
    }

    return 0;
}

To compile above program use c++11 switch like “gcc -std=c++11 sample.cpp -o sample”

 



Related Contents to follow