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++
// C++ Program to declare a map #include <iostream> #include <map> #include <string> using namespace std;
// Driver Code int main()
{ // Create a map of strings to integers
map<string, int > mp;
// Insert some values into the map
mp[ "one" ] = 1;
mp[ "two" ] = 2;
mp[ "three" ] = 3;
// Get an iterator pointing to the first element in the
// map
map<string, int >::iterator it = mp.begin();
// Iterate through the map and print the elements
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