Saturday, May 15, 2010

STL MAP

STL MAP


  • Maps are a kind of associative containers that stores elements formed by the combination of a key value and a mapped value.
  • In a map, the key value is generally used to uniquely identify the element, while the mapped value is some sort of value associated to this key. Types of key and mappedvalue may differ. For example, a typical example of a map is a telephone guide where the name is the key and the telephone number is the mapped value.
  • Internally, the elements in the map are sorted from lower to higher key value following a specific strict weak ordering criterion set on construction.
  • They are especially designed to be efficient accessing its elements by their key (unlike sequence containers, which are more efficient accessing elements by their relative or absolute position).
  • Maps are also unique among associative containers in that the implement the direct access operator (operator[]) which allows for direct access of the mapped value.
EXAMPLE:

// accessing mapped values
# include < iostream >
# include < map >
# include < string >
using namespace std;

int main ()
{
  map< char,string > mymap;

  mymap['a']="an element";
  mymap['b']="another element";
  mymap['c']=mymap['b'];

  cout << "mymap['a'] is " << mymap['a'] << endl;
  cout << "mymap['b'] is " << mymap['b'] << endl;
  cout << "mymap['c'] is " << mymap['c'] << endl;
  cout << "mymap['d'] is " << mymap['d'] << endl;

  cout << "mymap now contains " << (int) mymap.size() << " elements." << endl;

  return 0;
}

Notice how the last access (to element 'd') inserts a new element in the set with that key and initialized to its default value (an empty string) even though it is accessed only to retrieve its value. Member function map::find does not produce this effect.
Output:
mymap['a'] is an element
mymap['b'] is another element
mymap['c'] is another element
mymap['d'] is
mymap now contains 4 elements.

No comments:

Post a Comment