Understanding the Map
Understanding map
in C++
What is map
?
map
is an associative container in the C++ Standard Library that stores elements in key-value pairs. It allows for fast retrieval of values based on their keys, and it maintains the elements in a sorted order based on the keys.
Why Use map
?
Efficient Lookup: Provides logarithmic time complexity for search, insert, and delete operations.
Sorted Order: Maintains elements in a sorted order based on keys.
Key-Value Association: Ideal for situations where you need to associate values with unique keys.
Syntax
Here's the basic syntax for creating a map
:
#include <map>
using namespace std;
map<KeyType, ValueType> mapName;
KeyType
: The type of the keys.ValueType
: The type of the values.mapName
: The name of the map object.
Common map
Functions
insert
Description: Inserts a key-value pair into the map.
Syntax:
pair<iterator, bool> insert(const pair<KeyType, ValueType>& value);
Example:
#include <iostream>
#include <map>
using namespace std;
int main() {
map<int, string> myMap;
myMap.insert(pair<int, string>(1, "Apple"));
myMap.insert(pair<int, string>(2, "Banana"));
for (const auto& pair : myMap) {
cout << pair.first << ": " << pair.second << endl;
}
return 0;
}
operator[]
Description: Accesses the value corresponding to the given key. If the key does not exist, a new element with that key is inserted.
Syntax:
Example:
find
Description: Finds an element with the given key.
Syntax:
Example:
erase
Description: Removes elements from the map by key or by iterator.
Syntax:
Example:
size
Description: Returns the number of elements in the map.
Syntax:
Example:
clear
Description: Removes all elements from the map.
Syntax:
Example:
2024 - Programming 3 / Data Structures - Author: Dr. Kevin Roark