Friday, December 2, 2011

associative arrays c++

Maps as Associative Arrays

In the previous example, if you replace type multimap with map  you would get the output without duplicate keys (the values might still be the same). However, a collection of key/value pairs with unique keys could also be thought of as an associative array.  Consider the following example:

Example:

The declaration of the container type must specify both the type of the key and the type of the value:

typedef map<string,float> StringFloatMap;

Maps enable you to insert elements by using the subscript operator [ ]:

coll["VAT"] = 0.15;
coll["Pi"] = 3.1415;
coll["an arbitrary number"] = 4983.223;
coll["Null"] = 0;

Here, the index is used as the key and may have any type. This is the interface of an associative array. An associative array is an array in which the index may be of an arbitrary type.

Note that the subscript operator behaves differently than the usual subscript operator for arrays:

Not having an element for an index is not an error. A new index (or key) is taken as a reason to create and to insert a new element of the map that has the index as the key. Thus, you can't have a wrong index. Therefore, in this example in the statement 

coll["Null"] = 0;

the expression

coll["Null"]

creates a new element that has the key "Null". The assignment operator assigns 0 (which gets converted into float) as the  value. You can't use the subscript operator for multimaps. Multimaps allow multiple elements that have the same key, so the subscript operator makes no sense because it can handle only one value.

Similar to multimaps, for maps to access the key and the value of an element you have to use the first and second members of the pair structure. The output of the program is as follows:

key: "Null" value: 0
key: "Pi" value: 3.1415
key: "VAT" value: 0.15
key: "an arbitrary number" value: 4983.22

See Also:

1 comment:

  1. nice concept. thanks for sharing. waiting for to get more for STL.

    ReplyDelete