C++ Program To Get All Keys From Map
In this tutorial, we will learn how to retrieve all keys from a map in C++.
A Map is a container that stores an element in a map fashion. Each element has a key and a corresponding map value.No two map values can have the same key.
In the following segment, I have assumed that we have not made a map already and we will start from very basic i.e. from how to create a map until retrieval of keys from a map in c++.
Get All Keys From a Map In C++
So Let’s Start.
Firstly we will include three header files which are iostream, map and iterator.
#include <iostream> #include <iterator> #include <map> using namespace std;
Now we will declare an empty <int, int> map container in which we will later insert values.<int,int> signifies that both the key value and mapped value will be an integer.
map<int,int> m1;
So, we will now insert values into the map. Here we have inserted values in random order. We can insert values in any way we want.
m1.insert(pair<int,int>(1,100)); m1.insert(pair<int,int>(2,200)); m1.insert(pair<int,int>(3,400)); m1.insert(pair<int,int>(4,300)); m1.insert(pair<int,int>(5,500)); m1.insert(pair<int,int>(6,700)); m1.insert(pair<int,int>(7,1000));
After, inserting values we will now go for declaring an iterator. Iterators are similar to pointers: they point to elements in a container.
map<int,int>::iterator itr1;
Now we will run a for loop from the beginning of the container to the end of the container incrementing the value of iterator by one each time.
Then we can print the first value(key) in the container by printing iter1->first and second value(mapped value) by printing iter1->second.
But as we only want to print keys, so we will useĀ iter1->first.
cout<<"KEYS present in map m1 are :\n"; for (itr1=m1.begin();itr1!=m1.end();++itr1) { cout<<itr1->first<<'\n'; } return 0; }
Output upon execution of above code segment is:-
KEYS present in map m1 are : 1 2 3 4 5 6 7
We have come to the end of this post. I hope you all have enjoyed coding and executing it.
Thank You!
Before you go, please do check these amazing posts also:
Leave a Reply