Array of maps in C++ with Examples
What is an array?
An array in any programming language is a data structure that is used to store elements or data items of similar data types at contiguous memory locations and elements can be accessed randomly using indices of an array. Arrays are efficient when we want to store a large number of elements that too of similar data types.
What is a Map?
In C++, a map is an associative container that is used to store elements in a mapped fashion. Internally, a map is implemented as a self-balancing binary tree. Each element of a map is treated as a pair. The first value is referred to as key and the second value is referred to as value. No two values can have the same key.
Functions associated with Map:
- begin(): Returns an iterator to the first element in the map
- end(): Returns an iterator to the theoretical element that follows the last element in the map
- size(): Returns the number of elements in the map
- max_size(): Returns the maximum number of elements that the map can hold
- empty(): Returns whether the map is empty
- insert(key, Value): Adds a new element to the map
- erase(iterator position): Removes the element at the position pointed by the iterator
- erase(const x): Removes the key-value ‘x’ from the map
- clear(): Removes all the elements from the map
Array of Maps
C++ allows us a facility to create an array of maps. An array of maps is an array in which each element is a map on its own.
map<<dataType1, dataType2>> myContainer[N];
N: The size of the array of maps
dataType1: The dataType for the key
dataType2: The dataType for the value
Example 1: Below is the C++ program to implement an array of maps.
The map elements stored at the index 0: Key Value 10 1 15 0 20 1 25 0 The map elements stored at the index 1: Key Value 30 1 35 0 40 1 45 0 The map elements stored at the index 2: Key Value 50 1 55 0 60 1 65 0
Example 2: Below is the C++ program to implement array of maps.
The map elements stored at the index 0: Key Value Code 1 HTML 0 Java 1 Solo 0 The map elements stored at the index 1: Key Value C++ 1 CSS 0 Lab 0 PHP 1 The map elements stored at the index 2: Key Value Cobol 0 Fizzy 1 Pizza 0 Swift 1
Please Login to comment...