How to Declare a Map in C++?
Last Updated :
28 Feb, 2024
In C++, 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 the same key values. In this article, we will learn how to declare a map in C++.
How to declare a map in C++?
In C++, you can declare a map using the std::map
template class, which is part of the <map>
header.
Syntax to declare a map in C++ STL
std::map<KeyType, ValueType> mapName;
where,
KeyType
: This is the data type of the keys in the map.
ValueType
: This is the data type of the values associated with the keys in the map.
mapName
: This is the name you give to your map variable.
C++ Program to Declare a Map
C++
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
map<string, int > mp;
mp[ "one" ] = 1;
mp[ "two" ] = 2;
mp[ "three" ] = 3;
map<string, int >::iterator it = mp.begin();
while (it != mp.end()) {
cout << "Key: " << it->first
<< ", Value: " << it->second << endl;
++it;
}
return 0;
}
|
Output
Key: one, Value: 1
Key: three, Value: 3
Key: two, Value: 2
Share your thoughts in the comments
Please Login to comment...