What is a Map in the Computer?
The term map has three different meanings in the computer:
- A geographical map of a physical location, which is the meaning we're used to. This includes maps of real places in the world, which we can find on websites like Google Maps, or even mini-maps found in games.
- In functional programming, the term of a method that creates a list of values by transforming all the values of another list. This likely comes from the same sense in mathematics: a function that "maps" values of one set to another.
- An associative data structure of key-value pairs, also called a "mapping." In this case, we say the keys are "mapped" to the values.
Usually, the unusual sense we may hear about is the third one. For example, when we talk about "mapping the keys of the keyboard," i.e. a key map, we are talking about a mapping of keys to their respective functions. We can also map the buttons of the mouse to some function that they perform when pressed.
The term "map" is used for the standard associative data structured in C++, a popular programming language. Similar concepts exist in other languages, where they get other names, e.g. a dictionary (or dict) in Python, or an associative array in PHP.
#include <map>
int main () {
std::map<int, const char*> digits_to_words;
digits_to_words[1] = "one";
digits_to_words[2] = "two";
digits_to_words[3] = "three";
}
A "key" in a map isn't necessarily an key of the keyboard. The term simply means the key of a key-value pair. All keys in a map are unique. This means you can't have two keys that are the same. The values, on the other hand, aren't necessarily unique. For example, we could map countries to their respective countries, then we would have Brazil => South America as one key => value pair, and Argentina => South America as another pair. The value is the same but the key is different.