The map container implements a classic map data structure. The object can be accessed fast directly. (Be sure to study the requirements for objects that are stored in STL containers.) The map container is defined as a template class, meaning that it can be customized to hold objects of any type. Here is a simple example:
#include<map> // map class library ... // Now create a "map" type, specifying the key as "long" and the value as "std::string". typedef std::map<long, std::string, less<long> > MyMapType; // comparison object: less<long> typedef MyMapType::value_type ValuePair; ... MyMapType aMap; // Add some values aMap.insert( ValuePair(836361136, "Andrew") ); aMap.insert( ValuePair(274635328, "Berni") ); aMap.insert( ValuePair(534534345, "John") ); aMap.insert( ValuePair(184092144, "Karen") ); aMap.insert( ValuePair(785643523, "Thomas") ); aMap.insert( ValuePair(923452344, "William") ); // insetrion of Tom is not executed, because the key // already exists! aMap.insert( ValuePair(785643523, "Tom") ); // Due to the underlying implementation, the output of the names // is sorted by numbers: std::out << "Output: " << std::endl; MyMapType::const_iterator iter = aMap.begin(); while( iter != aMap.end() ) { std::out << (*iter).first << ":" // number << (*iter).second << std::endl; // name ++iter; } std::out << "Output of the name after entering the number: "; long number; std::cin >> number; iter = aMap.find( number ); // O(log N) if( iter!=aMap.find(number) ) { std::cout << (*iter).second << ' ' // O(1) << aMap[number] // O(log N) << std::endl; } else { std::cout << "not found!" << std::endl; } |
Some commonly used member functions of the map class are:
size |
size_type size() const; // Loop as long as there are still elements in the map. while( map.size() > 0) { ... } |
empty |
bool empty() const; if( map.empty() ) { ... } |
begin |
iterator begin(); |
end |
iterator end(); |
rbegin |
iterator rbegin(); |
rend |
iterator rend(); |
insert |
pair<iterator, bool> insert( const value_type &x ); MyMapType aMap; aMap.insert( MyMapType::value_type(836361136, "Andrew") ); |
erase |
void erase(iterator position); nums.erase( nums.begin(), nums.end() ); // Remove all elements; ... nums_iter = find( nums.begin(), nums.end(), 3 ); // Search the map. // If we found the element, erase it from the map. if( nums_iter != nums.end() ) nums.erase( nums_iter ); |
clear | void clear(); nums.clear(); // Remove all elements; |
---|
In addition to these member functions, some STL algorithms (e.g., find) can be applied to the map container.
Some of the operators defined for the map container are:
More information on iterators is available. Here, we will consider only a few simple uses of iterators with map containers.
Copyright 2002 by Patrick Meier
Last updated on 26.08.2002 by Patrick Meier