Draft 2002-08-13

<map>

The <map> header is one of the standard container template headers. It declares the map and multimap class templates and a few global functions that operate on map and multimap objects.

A map is a container that stores pairs of keys and values. Looking up keys, inserting keys, and deleting keys can all be performed in logarithmic or better time. Maps support bidirectional iterators (no random access). In other languages and libraries, maps are also called dictionaries and associative arrays.

See Chapter 11 for information about containers in general. See the <utility> section, later in this chapter, for information about the pair class template.

map class template

Associative map container with unique keys

template <typename Key, typename T,
  typename Compare = less<Key>,
  typename Alloc = allocator<pair<const Key, T> > >
class map {
public:
  typedef Key key_type;
  typedef T mapped_type;
  typedef pair<const Key, T> value_type;
  typedef Compare key_compare;
  typedef Alloc allocator_type;
  typedef typename Alloc::reference reference;
  typedef typename Alloc::const_reference const_reference;
  typedef ... iterator;
  typedef ... const_iterator;
  typedef ... size_type;
  typedef ... difference_type;
  typedef typename Alloc::pointer pointer;
  typedef typename Alloc::const_pointer const_pointer;
  typedef std::reverse_iterator<iterator> reverse_iterator;
  typedef std::reverse_iterator<const_iterator>
    const_reverse_iterator;
  class value_compare :
      public binary_function<value_type,value_type,bool>
  {
     friend class map;
  protected:
    Compare comp;
    value_compare(Compare c) : comp(c) {}
  public:
    bool operator()(const value_type& x, const value_type& y)
      const
        { return comp(x.first, y.first); }
  };
  explicit map(const Compare& comp = Compare(),
    const Alloc& = Alloc());
  template <class InputIterator>
  map(InputIterator first, InputIterator last,
    const Compare& comp = Compare(), const Alloc& = Alloc());
  map(const map<Key,T,Compare,Alloc>& x);
  ~map();
  map<Key,T,Compare,Alloc>&
    operator=(const map<Key,T,Compare,Alloc>& x);
 
  allocator_type get_allocator() const;
  // iterators:
  iterator begin();
  const_iterator begin() const;
  iterator end();
  const_iterator end() const;
  reverse_iterator rbegin();
  const_reverse_iterator rbegin() const;
  reverse_iterator rend();
  const_reverse_iterator rend() const;
  // capacity:
  bool empty() const;
  size_type size() const;
  size_type max_size() const;
  // element access:
  T& operator[](const key_type& x);
  // modifiers:
  pair<iterator, bool> insert(const value_type& x);
  iterator insert(iterator position, const value_type& x);
  template <class InputIterator>
    void insert(InputIterator first, InputIterator last);
  void erase(iterator position);
  size_type erase(const key_type& x);
  void erase(iterator first, iterator last);
  void swap(map<Key,T,Compare,Alloc>&);
  void clear();
  // observers:
  key_compare key_comp() const;
  value_compare value_comp() const;
  // map operations:
  iterator find(const key_type& x);
  const_iterator find(const key_type& x) const;
  size_type count(const key_type& x) const;
  iterator lower_bound(const key_type& x);
  const_iterator lower_bound(const key_type& x) const;
  iterator upper_bound(const key_type& x);
  const_iterator upper_bound(const key_type& x) const;
  pair<iterator,iterator> equal_range(const key_type& x);
  pair<const_iterator,const_iterator>
    equal_range(const key_type& x) const;
};

The map class template represents a map container. A map stores pairs of unique keys and associated objects, where the key type is specified by the Key template parameter, and the associated type is the T template parameter. The values stored in the map are of type pair<const Key, T> (which has the convenience typedef value_type).

A map's iterators are bidirectional. They return value_type references; use the first member to access the key or second to access the associated object.

Note that keys are const in the map. You must not change the key while it is stored in a map. More precisely, you must not change the key in a way that alters its relative order with the other keys in the map. If you need to modify a key, erase the key from the map, modify the key, and insert the new key with its original associated value, as shown in Example 13-31.

Example 13-31: One way to modify a key

template <typename Key, typename T, typename C, typename A>
void change_key(std::map<Key, T, C, A>& m,
  const Key& oldkey, const Key& newkey)
{
  using ::std::map;
  typedef map<Key, T, C, A>::iterator map_iterator;
  map_iterator i = m.find(oldkey);
  if (i != m.end()) {
    // Save a copy of i->second because erase invalidates i.
    T tmp = i->second;
    m.erase(i);
    m[newkey] = tmp;
  }
  // Exercise for reader: What if newkey is already in m?
}

Within a map, keys are ordered in ascending order, according to the Compare template parameter (which can be a function pointer or functor that compares two objects of type Key and returns true if the first argument should come before the second). Keys must be unique, but note that uniqueness is determined only by calling Compare, not by using the == operator. That is, two objects, a and b, are different (and therefore can both be present in a single map object) if Compare(a, b) is true or Compare(b, a) is true. See multimap, later in this section, for a map container that can store non-unique keys.

Inserting into a map does not invalidate any iterators for that map. Erasing an element invalidates only iterators that refer to that element.

Insertion into a map and searching for an element in a map take logarithmic time. Erasing a single element, given an iterator, takes amortized constant time; erasing all elements in a range given by two iterators can be done in logarithmic time.

Example 13-32 shows a use of map for counting word frequencies in the standard input.

Example 13-32: Using a map to count word frequencies.

#include <iostream>
#include <istream>
#include <map>
#include <ostream>
#include <string>

typedef std::map<std::string, std::size_t> freqmap;

// Print a single word and its count.
void print(const freqmap::value_type info)
{
  std::cout << info.first << '\t' << info.second << '\n';
}

int main()
{
  freqmap fm;
  std::string word;
  // Count words: if a word is not in the map, add it.
  // When a new word is added, its count is initially zero.
  // Each time, including the first, increment the count.
  while (std::cin >> word)
    ++fm[word];
  // Print the frequencies of each word, in order.
  std::for_each(fm.begin(), fm.end(), print);
}

Following are the member functions of map:

explicit map (const Compare& comp = Compare(),
const Alloc& = Alloc())
The constructor creates an empty map.
template <class InputIterator>
map (InputIterator first, InputIterator last,
const Compare& comp = Compare(), const Alloc& = Alloc())
The constructor creates an empty map and then copies all pairs in the range [first, last) into the new map.
map (const map<Key,T,Compare,Alloc>& x)
The constructor creates a new map and copies all the pairs from x to the new map.
iterator begin ()
const_iterator begin () const
The begin function returns an iterator that points to the first item in the map.
void clear ()
The clear function erases every item in the map.
size_type count (const key_type& x) const
The count function returns the number of pairs whose keys are equivalent to x. This value is always zero or one.
bool empty () const
The empty function returns size() == 0.
iterator end ()
const_iterator end () const
The end function returns an iterator that points to one past the last item in the map.
pair<iterator,iterator> equal_range (const key_type& x)
pair<const_iterator,const_iterator>
equal_range (const key_type& x) const
The equal_range function returns the lower bound and upper bound as a pair, e.g.,
std::make_pair(lower_bound(x), upper_bound(x))
void erase (iterator position)
size_type erase (const key_type& x)
void erase (iterator first, iterator last)
The erase function erases one or more pairs from the map. The first version erases the pair at position in constant time (amortized over many calls). The second version erases the pair equivalent to x, if it is present, returning a count of the number of pairs erased, that is, zero or one. It runs in logarithmic time. The third version erases all elements in the range [first, last) in time proportional to log size() + (last - first).
iterator find (const key_type& x)
const_iterator find (const key_type& x) const
The find function searches for a pair whose key is equivalent to x and returns an iterator that points to that pair or end() if not found. It runs in logarithmic time.
allocator_type get_allocator () const
The get_allocator function returns the map's allocator.
pair<iterator, bool> insert (const value_type& x)
iterator insert (iterator pos, const value_type& x)
template <class InputIterator>
void insert (InputIterator first, InputIterator last)
The insert function inserts one or more pairs into the map, but only if an equivalent key is not already present in the map. If the key is already present, the insert attempt is ignored. The first version attempts to insert the pair x in logarithmic time.
The second version inserts the pair x, using pos as a position hint. If x is inserted immediately after pos, the performance is constant (amortized over many insertions); at any other position, the performance is logarithmic. Use this form when inserting many items that are already in the desired order.
The third version copies all the pairs in the range [first, last), which must be pointing to a different map object. If the items are already in the desired order, the performance is linear; otherwise it is N log (size() + N), where N is last - first.
key_compare key_comp () const
The key_comp function returns the comparator function pointer or functor object, which compares keys. The key_compare type is the same as the Compare template parameter. (See also the value_comp member).
iterator lower_bound (const key_type& x)
const_iterator lower_bound (const key_type& x) const
The lower_bound function returns an iterator that points to the first pair in the map that does not come before x. That is, if x is in the map, the iterator points to its position; otherwise the iterator points to the first position where x should be inserted. Performance is logarithmic.
size_type max_size () const
The max_size function returns the largest number of pairs that can be in a map.
reverse_iterator rbegin ()
const_reverse_iterator rbegin () const
The rbegin function returns a reverse iterator that points to the last element of the map.
reverse_iterator rend ()
const_reverse_iterator rend () const
The rend function returns a reverse iterator that points to the first element of the map.
size_type size () const
The size function returns the number of pairs in the map.
void swap (map<Key,T,Compare,Alloc>&)
The swap function swaps the contents of the map with the contents of x.
iterator upper_bound (const key_type& x)
const_iterator upper_bound (const key_type& x) const
The upper_bound function returns an iterator that points to the first pair in the map that comes after x. Performance is logarithmic.
value_compare value_comp () const
The value_comp function returns a value_compare object, which can be used to compare pairs. The value_compare object takes two value_type arguments and compares their keys, returning true if the first should come before the second in the map.
map<Key,T,Compare,Alloc>&
operator= (const map<Key,T,Compare,Alloc>& x)
The assignment operator erases all the elements of the map and replaces them with copies of the elements of x.
T& operator[] (const key_type& x)
The subscript operator returns a reference to the object associated with the key x. If x is not in the map, it is added with a default associated object, and a reference to that new object is returned.
That is, operator[] returns the following:
(*((insert(std::make_pair(x, T()))).first)).second
Note that there is no const version of this operator.

See Also

multimap class template, set in <set>

multimap class template

Associative map container with duplicate keys

template <class Key, class T, class Compare = less<Key>,
   class Alloc = allocator<pair<const Key, T> > >
class multimap {
public:
  typedef Key key_type;
  typedef T mapped_type;
  typedef pair<const Key,T> value_type;
  typedef Compare key_compare;
  typedef Alloc allocator_type;
  typedef typename Alloc::reference reference;
  typedef typename Alloc::const_reference const_reference;
  typedef ... iterator;
  typedef ... const_iterator;
  typedef ... size_type;
  typedef ... difference_type;
  typedef typename Alloc::pointer pointer;
  typedef typename Alloc::const_pointer const_pointer;
  typedef std::reverse_iterator<iterator> reverse_iterator;
  typedef std::reverse_iterator<const_iterator>
    const_reverse_iterator;
  class value_compare :
    public binary_function<value_type,value_type,bool>
  {
    friend class multimap;
  protected:
    Compare comp;
    value_compare(Compare c) : comp(c) {}
  public:
    bool operator()(const value_type& x, const value_type& y)
      const { return comp(x.first, y.first); }
  };

  explicit multimap(const Compare& comp = Compare(),
     const Alloc& = Alloc());
  template <class InputIterator>
  multimap(InputIterator first, InputIterator last,
    const Compare& comp = Compare(),
    const Alloc& = Alloc());
  multimap(const multimap<Key,T,Compare,Alloc>& x);
  ~multimap();
  multimap<Key,T,Compare,Alloc>&
    operator=(const multimap<Key,T,Compare,Alloc>& x);
  allocator_type get_allocator() const;
  // iterators:
  iterator begin();
  const_iterator begin() const;
  iterator end();
  const_iterator end() const;
  reverse_iterator rbegin();
  const_reverse_iterator rbegin() const;
  reverse_iterator rend();
  const_reverse_iterator rend() const;
  // capacity:
  bool empty() const;
  size_type size() const;
  size_type max_size() const;
  // modifiers:
  iterator insert(const value_type& x);
  iterator insert(iterator position, const value_type& x);
  template <class InputIterator>
  void insert(InputIterator first, InputIterator last);
  void erase(iterator position);
  size_type erase(const key_type& x);
  void erase(iterator first, iterator last);
  void swap(multimap<Key,T,Compare,Alloc>&);
  void clear();
  // observers:
  key_compare key_comp() const;
  value_compare value_comp() const;
  // map operations:
  iterator find(const key_type& x);
  const_iterator find(const key_type& x) const;
  size_type count(const key_type& x) const;
  iterator lower_bound(const key_type& x);
  const_iterator lower_bound(const key_type& x) const;
  iterator upper_bound(const key_type& x);
  const_iterator upper_bound(const key_type& x) const;
  pair<iterator,iterator> equal_range(const key_type& x);
  pair<const_iterator,const_iterator>
  equal_range(const key_type& x) const;
};

The multimap class template represents a map container that can store duplicate keys. A map stores pairs of keys and associated objects, where the key type is specified by the Key template parameter, and the associated type is the T template parameter. The values stored in the map are of type pair<const Key, T> (which has the convenience typedef value_type).

A map's iterators are bidirectional. They return value_type references; use the first member to access the key or second to access the associated object.

Note that keys are const in the map. You must not change the key while it is stored in a map. More precisely, you must not change the key in a way that alters its relative order with the other keys in the map. See Example 13-31, earlier in this chapter for an example of how to change a key by erasing and reinserting an object.

Within a map, keys are ordered in ascending order, according to the Compare template parameter (which can be a function pointer or functor that compares two objects of type Key and returns true if the first argument should come before the second).

Inserting into a map does not invalidate any iterators for that map. Erasing an element invalidates only iterators that refer to that element.

Insertion into a map and searching for an element in a map take logarithmic time. Erasing a single element, given an iterator, takes amortized constant time; erasing all elements in a range given by two iterators can be done in logarithmic time.

Following are the member functions of multimap. Note that multimap does not have a subscript operator.

explicit multimap (const Compare& comp = Compare(),
const Alloc& = Alloc())
The constructor creates an empty map.
template <class InputIterator>
m ultim ap (InputIterator first, InputIterator last,
const Compare& comp = Compare(), const Alloc& = Alloc())
The constructor creates an empty map and then copies all pairs in the range [first, last) into the new map.
m ultim ap (const multimap<Key,T,Compare,Alloc>& x)
The constructor creates a new map and copies all the pairs from x to the new map.
iterator begin ()
const_iterator begin () const
The begin function returns an iterator that points to the first item in the map.
void clear ()
The clear function erases every item in the map in logarithmic time.
size_type count (const key_type& x) const
The count function returns the number of pairs whose keys are equivalent to x.
bool empty () const
The empty function returns size() == 0.
iterator end ()
const_iterator end () const
The end function returns an iterator that points to one past the last item in the map.
pair<iterator,iterator> equal_range (const key_type& x)
pair<const_iterator,const_iterator>
equal_range (const key_type& x) const
The equal_range function returns the lower bound and upper bound as a pair, e.g.,
std::make_pair(lower_bound(x), upper_bound(x))
void erase (iterator position)
size_type erase (const key_type& x)
void erase (iterator first, iterator last)
The erase function erases one or more pairs from the map. The first version erases the pair at position in constant time (amortized over many calls). The second version erases all the pairs equivalent to x, if any are present, returning a count of the number of pairs erased. It runs in logarithmic time. The third version erases all elements in the range [first, last) in time proportional to log size().
iterator find (const key_type& x)
const_iterator find (const key_type& x) const
The find function searches for a pair whose key is equivalent to x and returns an iterator that points to that pair or end() if not found. If x occurs more than once, the iterator might point to any of the equivalent pairs.
allocator_type get_allocator () const
The get_allocator function returns the map's allocator.
pair<iterator, bool> insert (const value_type& x)
iterator insert (iterator pos, const value_type& x)
template <class InputIterator>
void insert (InputIterator first, InputIterator last)
The insert function inserts one or more pairs into the map. The first version inserts the pair x in logarithmic time.
The second version inserts the pair x, using pos as a position hint. If x is inserted immediately after pos, the performance is constant (amortized over many insertions); at any other position, the performance is logarithmic. Use this form when inserting many items that are already in the desired order.
The third version copies all the pairs in the range [first, last), which must be pointing to a different multimap object. If the items are already in the desired order, the performance is linear; otherwise it is N log (size() + N), where N is last - first.
key_compare key_comp () const
The key_comp function returns the comparator function pointer or functor object, which compares keys. The key_compare type is the same as the Compare template parameter. (See also the value_comp member).
iterator lower_bound (const key_type& x)
const_iterator lower_bound (const key_type& x) const
The lower_bound function returns an iterator that points to the first pair in the map that does not come before x. That is, if x is in the map, the iterator points to the position of its first occurrence; otherwise the iterator points to the first position where x should be inserted. Performance is logarithmic.
size_type max_size () const
The max_size function returns the largest number of pairs that can be in a map.
reverse_iterator rbegin ()
const_reverse_iterator rbegin () const
The rbegin function returns a reverse iterator that points to the last element of the map.
reverse_iterator rend ()
const_reverse_iterator rend () const
The rend function returns a reverse iterator that points to the first element of the map.
size_type size () const
The size function returns the number of pairs in the map.
void swap (multimap<Key,T,Compare,Alloc>&)
The swap function swaps the contents of the map with the contents of x.
iterator upper_bound (const key_type& x)
const_iterator upper_bound (const key_type& x) const
The upper_bound function returns an iterator that points to the first pair in the map that comes after all occurrences of x. Performance is logarithmic.
value_compare value_comp () const
The value_comp function returns a value_compare object, which can be used to compare pairs. The value_compare object takes two value_type arguments and compares their keys, returning true if the first should come before the second in the map.
multimap<Key,T,Compare,Alloc>&
operator= (const multimap<Key,T,Compare,Alloc>& x)
The assignment operator erases all the elements of the map and replaces them with copies of the elements of x.

See Also

map class template, multiset in <set>

operator== function template

Compare maps for equality

template <class Key, class T, class Comp, class Alloc>
bool operator==(const map<Key,T,Comp,Alloc>& x,
                const map<Key,T,Comp,Alloc>& y);
template <class Key, class T, class Comp, class Alloc>
bool operator==(const multimap<Key,T,Comp,Alloc>& x,
                const multimap<Key,T,Comp,Alloc>& y);

The == operator returns true if x and y have the same size and their elements are equal, that is, x.size() == y.size() && equals(x.begin(), x.end(), y.begin()).

See Also

equals in <algorithm>

operator!= function template

Compare maps for inequality

template <class Key, class T, class Comp, class Alloc>
bool operator!=(const map<Key,T,Comp,Alloc>& x,
                const map<Key,T,Comp,Alloc>& y);
template <class Key, class T, class Comp, class Alloc>
bool operator!=(const multimap<Key,T,Comp,Alloc>& x,
                const multimap<Key,T,Comp,Alloc>& y);

The != operator is equivalent to ! (x == y).

operator< function template

Compare maps for less than

template <class Key, class T, class Comp, class Alloc>
bool operator<(const map<Key,T,Comp,Alloc>& x,
               const map<Key,T,Comp,Alloc>& y);
template <class Key, class T, class Comp, class Alloc>
bool operator<(const multimap<Key,T,Comp,Alloc>& x,
               const multimap<Key,T,Comp,Alloc>& y);

The < operator determines whether x is less than y, using the same algorithm as lexicographic_compare(x.begin(), x.end(), y.begin(), y.end()).

See Also

lexicographic_compare in <algorithm>

operator<= function template

Compare maps for less than or equal

template <class Key, class T, class Comp, class Alloc>
bool operator<=(const map<Key,T,Comp,Alloc>& x,
                const map<Key,T,Comp,Alloc>& y);
template <class Key, class T, class Comp, class Alloc>
bool operator<=(const multimap<Key,T,Comp,Alloc>& x,
                const multimap<Key,T,Comp,Alloc>& y);

The <= operator is equivalent to ! (y < x).

operator> function template

Compare maps for greater than

template <class Key, class T, class Comp, class Alloc>
bool operator>(const map<Key,T,Comp,Alloc>& x,
               const map<Key,T,Comp,Alloc>& y);
template <class Key, class T, class Comp, class Alloc>
bool operator>(const multimap<Key,T,Comp,Alloc>& x,
               const multimap<Key,T,Comp,Alloc>& y);

The > operator is equivalent to (y < x).

operator>= function template

Compare maps for greater than or equal

template <class Key, class T, class Comp, class Alloc>
bool operator>=(const map<Key,T,Comp,Alloc>& x,
                const map<Key,T,Comp,Alloc>& y);
template <class Key, class T, class Comp, class Alloc>
bool operator>=(const multimap<Key,T,Comp,Alloc>& x,
                const multimap<Key,T,Comp,Alloc>& y);

The >= operator is equivalent to ! (x < y).

swap function template

Swap the contents of two maps

template <class Key, class T, class Comp, class Alloc>
 void swap(map<Key,T,Comp,Alloc>& x,
           map<Key,T,Comp,Alloc>& y);
template <class Key, class T, class Comp, class Alloc>
 void swap(multimap<Key,T,Comp,Alloc>& x,
           multimap<Key,T,Comp,Alloc>& y);

The swap function template specialization is equivalent to calling x.swap(y).

See Also

swap in <algorithm>