stl:map:map_constructors

C++ Reference

Map Constructors & Destructors

Syntax:

    #include <map>
    map();
    map( const map& m );
    map( iterator start, iterator end );
    map( iterator start, iterator end, const key_compare& cmp );
    map( const key_compare& cmp );
    ~map();

The default constructor takes no arguments, creates a new instance of that map, and runs in constant time. The default copy constructor runs in linear time and can be used to create a new map that is a copy of the given map m.

You can also create a map that will contain a copy of the elements between start and end, or specify a comparison function cmp.

The default destructor is called when the map should be destroyed.

For example, the following code creates a map that associates a string with an integer:

    struct strCmp {
      bool operator()( const char* s1, const char* s2 ) const {
        return strcmp( s1, s2 ) < 0;
      }
    };
 
    ...
 
    map<const char*, int, strCmp> ages;
    ages["Homer"] = 38;
    ages["Marge"] = 37;
    ages["Lisa"] = 8;
    ages["Maggie"] = 1;
    ages["Bart"] = 11;
 
    cout << "Bart is " << ages["Bart"] << " years old" << endl;

Related Topics: Map operators