
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create an Empty Dictionary in C++
A map is a data structure in C++ and can be found in the STL class std::map. It is similar to the dictionaries that we see in Python. Each entry in a map object has a pair of values, one of which is the key value and the other is the mapped value. An entry on the map is found and uniquely identified using the key value. The key value in a map must always be unique, but the mapped value is not required to be. In this article, we focus on creating an empty map object.
Creating an empty map
We just create a map object and the result is an empty map. The syntax is given below.
Syntax
#include <map> map <data_type 1, data_type 2> myMap;
Let's take an example ?
Example
#include <iostream> #include <map> using namespace std; int main() { //initialising the map map <int, string> myMap; //displaying the contents, it returns nothing as it is empty for (auto itr = myMap.begin(); itr != myMap.end(); ++itr) { cout << itr->first << " " << itr->second << endl; } return 0; }
Output
Running the code will display nothing as the map is empty.
Creating a zero-initialized map
This can only be done when the mapped value has the type integer. Even if we reference a key that is not in the map, the returned value is 0.
Syntax
#include <map> map <data_type 1, int> myMap;
Example
#include <iostream> #include <map> using namespace std; int main() { //initialising the map map <string, int> myMap; //displaying the contents, it returns 0 as it is empty for (auto itr = myMap.begin(); itr != myMap.end(); ++itr) { cout << itr->first << " " << itr->second << endl; } cout<< myMap["test"] << endl; return 0; }
Output
0
Conclusion
Maps are ordered collections in C++, which means the elements are sorted according to their key values. Maps are implemented using red?black trees in memory. All maps are empty when a map object is initialized, but the zero-initialized maps are only available if the mapped value is of type integer.