This content is archived!
For the 2018-2019 school year, we have switched to using the WLMOJ judge for all MCPT related content. This is an archive of our old website and will not be updated.Introduction
Primitive arrays map the key type (int
) to a value (the type of the array). In this lesson, we will explore mapping with letters as keys.
Notice the 0
as the accessing index. This is the key. With arrays, the key is always an int
.
However, we can take advantage of the fact that a char
can be easily cast to an int
.
Example
Let’s try a problem:
Find the number of occurrences of each letter in a word.
We need to map each letter to an index in the array. Let’s use a
to 0
, b
to 1
, c
to 2
, … , z
to 25
. Conveniently, ASCII values of letters are in the same order, just with a different starting number.
Mapping isn’t limited to only letters though. Just use a bigger array to support more characters.
Array mapping can also be used with other keys such as digits: counting the occurrences of digits. Later on, we will learn mapping with other data types, such as double
, String
, and even custom classes.