I am trying to r开发者_StackOverflow社区ound up cases when it makes sense to use a map (set of key-value entries). So far I have two categories (see below). Assuming more exist, what are they?
Please limit each answer to one unique category and put up an example.
Property values (like a bean)
age -> 30
sex -> male
loc -> calgary
Presence, with O(1) performance
peter -> 1
john -> 1
paul -> 1
Sparse Data Structures (e.g. a sparse array or a matrix):
0 -> value
1 -> value
100 -> value
105 -> value
Also, I would argue that the "Presence" example you listed is better done with a Set data structure (e.g. HashSet in Java or .NET) since the "mapping" part of the map is really not necessary.
Remembering function results (caching, buffering, memoization)
10 -> 2
20 -> 7
30 -> zeroesIn(factorial(30))
Conversion
peter -> pierre
john -> jean
paul -> paul
If your language allows both associative arrays and pointer to functions/procedures, you can use maps to build something similar to Object Oriented (see Perl for a classical example).
See here for a more detailed explanation.
Passing arbitrary number of optional parameters to a function, in a language which doesn't support them:
cars = findAvailableCars(make -> 'Toyota', model -> 'Prius', color -> 'green')
As Eric Petroelje said, your "presence" example is better suited to a Set than a Map.
However, if you want to keep track of the number of occurrences of things, use a Map. For example, you want to know how many times a given word appears in a document:
pseudocode:
wordMap = map()
for word in document:
if wordMap.containsKey(word):
wordMap[word]++
else:
wordMap[word] = 1
then if I want to know how many times the word 'map' appears in the document, it would just be wordMap["map"]
A Map is one way of representing a graph. The keys are the nodes in the graph, and the value for a particular node N is a list of all the nodes that N connects to.
(Thanks for the retag, MatrixFrog.)
Dictionary (mapping a term to a definition)
"postulate" -> "demand or claim"
"consulate" -> "residence of a foreign official"
Also in this category
EADDRINUSE -> "Address in use."
EADDRNOTAVAIL -> "Address not available."
精彩评论