Jump to content

Map (C++): Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
m Iterators: fixed capitalization
m Usage: fixed capitalization to one recommended by Stroustrup
Line 65: Line 65:
int main()
int main()
{
{
typedef std::map<char, int> mapType;
typedef std::map<char, int> MapType;
mapType myMap;
MapType my_map;


// insert elements using insert function
// insert elements using insert function
myMap.insert(std::pair<char, int>('a', 1));
my_map.insert(std::pair<char, int>('a', 1));
myMap.insert(std::pair<char, int>('b', 2));
my_map.insert(std::pair<char, int>('b', 2));
myMap.insert(std::pair<char, int>('c', 3));
my_map.insert(std::pair<char, int>('c', 3));
myMap.insert(mapType::value_type('d', 4)); // all standard containers provide this typedef
my_map.insert(MapType::value_type('d', 4)); // all standard containers provide this typedef
myMap.insert(std::make_pair('e', 5)); // can also use the utility function make_pair
my_map.insert(std::make_pair('e', 5)); // can also use the utility function make_pair


// erase the first element using the erase function
// erase the first element using the erase function
mapType::iterator iter = myMap.begin();
MapType::iterator iter = my_map.begin();
myMap.erase(iter);
my_map.erase(iter);


// output the size of the map
// output the size of the map
std::cout << "Size of myMap: " << myMap.size() << '\n';
std::cout << "Size of my_map: " << my_map.size() << '\n';


std::cout << "Enter a key to search for: ";
std::cout << "Enter a key to search for: ";
Line 88: Line 88:
// find will return an iterator to the matching element if it is found
// find will return an iterator to the matching element if it is found
// or to the end of the map if the key is not found
// or to the end of the map if the key is not found
iter = myMap.find(c);
iter = my_map.find(c);
if (iter != myMap.end() )
if (iter != my_map.end() )
std::cout << "Value is: " << iter->second << '\n';
std::cout << "Value is: " << iter->second << '\n';
else
else
std::cout << "Key is not in myMap" << '\n';
std::cout << "Key is not in my_map" << '\n';


// clear the entries in the map
// clear the entries in the map

Revision as of 20:16, 3 October 2010

The class template std::map<Key, Data, Compare, Alloc> is a standard C++ container. It is a sorted associative array of unique keys and associated data.[1] The types of key and data may differ, and the elements of the map are internally sorted from lowest to highest key value. Since each key value is unique, if an object is inserted with an already existing key, the object already present in the map does not change.[2] A variation on the map, called the multimap, allows duplicate keys.

Iterators and references are not invalidated by insert and erase operations, except for iterators and references to erased elements. The usual implementation is a self-balancing binary search tree (but any other data structure that respects the complexity constraints can be used, like a skip list).

Main characteristics

  • Each element has a unique key
  • Each element is composed of a key and a mapped value
  • Elements follow a strict weak ordering[2]

Performance

The time it takes to perform the following list of tasks, can be expressed as: O(log n)
Note that this performance cost applies to each task individually.

  • Searching for an element
  • Inserting a new element
  • Incrementing/decrementing an iterator
  • Removing a single map element

whereas the following operations have an asymptotic complexity of O(n)

  • Copying an entire map [2]
  • Iterating through all elements

Maps are designed to be especially efficient in accessing its elements by their key, as opposed to sequence containers which are more efficient in accessing elements by their position (although maps are able to directly access elements with the operator[] ).[2]

Usage

The map is declared in this format:

map <key_type, value_type [, comparing_option [, memory_allocator] ] > map_name

The following code demonstrates how to use the map<string, int> to count occurrences of words. It uses the word as the key and the count as the value.

#include <iostream>
#include <string>
#include <map>

int main()
{
    std::map<std::string, int> wordcounts;
    std::string s;

    while (std::cin >> s && s != "end")
        ++wordcounts[s];

    while (std::cin >> s && s != "end")
        std::cout << s << ' ' << wordcounts[s] << '\n';
}

When executed, the user first types a series of words separated by spaces, and a word "end" to signify the end of input; then the user can input words to query how many times each word occurred in the previous series.

The above example also demonstrates that the operator [] inserts new objects (using the default constructor) in the map if there isn't one associated with the key. So integral types are zero-initialized, strings are initialized to empty strings, etc.

The following example illustrates inserting elements into a map using the insert function and searching for a key using a map iterator and the find function:

#include <iostream>
#include <map>
#include <utility> // make_pair

int main()
{
    typedef std::map<char, int> MapType;
    MapType my_map;

    // insert elements using insert function
    my_map.insert(std::pair<char, int>('a', 1));
    my_map.insert(std::pair<char, int>('b', 2));
    my_map.insert(std::pair<char, int>('c', 3));
    my_map.insert(MapType::value_type('d', 4)); // all standard containers provide this typedef
    my_map.insert(std::make_pair('e', 5));           // can also use the utility function make_pair

    // erase the first element using the erase function
    MapType::iterator iter = my_map.begin();
    my_map.erase(iter);

    // output the size of the map
    std::cout << "Size of my_map: " << my_map.size() << '\n';

    std::cout << "Enter a key to search for: ";
    char c;
    std::cin >> c;

    // find will return an iterator to the matching element if it is found
    // or to the end of the map if the key is not found
    iter = my_map.find(c);
    if (iter != my_map.end() ) 
        std::cout << "Value is: " << iter->second << '\n';
    else
        std::cout << "Key is not in my_map" << '\n';

    // clear the entries in the map
    myMap.clear();
}

In the above example, five elements are entered using the insertion function, and then the first element is deleted. Then, the size of the map is output. Next, the user is prompted for a key to search for. Using the iterator, the find function searches for an element with the given key. If it finds the key, the program prints the element's value. If it does not find it, an iterator to the end of the map is returned and it outputs that the key could not be found. Finally all the elements in the tree are erased.

Iterators

Maps may use iterators to point to specific elements in the container. An iterator can access both the key and the mapped value of an element:[2]

map<Key,T>::iterator it; // declares a map iterator
it->first;               // the key value 
it->second;              // the mapped value
(*it);                   // the "element value", which is of type:  pair<const Key,T>

Below is an example of looping through a map to display all keys and values using iterators:

#include <iostream>
#include <string>
#include <map>

int main()
{
    typedef std::map <std::string, int> MapType;
    MapType data;
    
    // let's declare some initial values to this map
    data["Bobs score"] = 10;
    data["Martys score"] = 15;
    data["Mehmets score"] = 34;
    data["Rockys score"] = 22;
    data["Rockys score"] = 23;  /*overwrites the 22 as keys are unique */
    
    // Iterate over the map and print out all key/value pairs.
    // Using a const_iterator since we are not going to change the values.
    MapType::const_iterator end = data.end(); 
    for (MapType::const_iterator it = data.begin(); it != end; ++it)
    {
        std::cout << "Who(key = first): " << it->first;
        std::cout << " Score(value = second): " << it->second << '\n';
    }

    return 0;
}

This will output the keys and values of the entire map.

Member functions

What follows is a list of the public member functions in the map library:[2]

Name Description
(constructor) Construct a map object
(destructor) Destroys map object
operator= Copy content of container
Iterators:
begin Return iterator to beginning of map
end Return iterator to end of map
rbegin Return reverse iterator to reverse beginning (end)
rend Return reverse iterator to reverse end (beginning)
Capacity:
empty Test whether map is empty or not
size Return container size of map
max_size Return maximum size of map
Element access:
operator[] Access element
Modifiers:
insert Insert element
erase Erase element
swap Swap contents
clear Clear contents
Observers:
key_comp Return key comparison object
value_comp Return value comparison object
Operations:
find Return iterator to element
count Count elements with a specific key
lower_bound Return iterator to the lower bound
upper_bound Return iterator to the upper bound
equal_range Return range of equal elements
Allocator:
get_allocator Return allocator

Member types

What follows is a list of the member types of the map container:[2]

Member type Definition
key_type Key
mapped_type T
value_type pair<const Key,T>
key_compare Compare
value_compare Nested class to compare elements
allocator_type Allocator
reference Allocator::reference
const_reference Allocator::const_reference
iterator Bidirectional iterator
const_iterator Constant bidirectional iterator
size_type Unsigned integral type (usually same as size_t)
difference_type Signed integral type (usually same as ptrdiff_t)
pointer Allocator::pointer
const_pointer Allocator::const_pointer
reverse_iterator reverse_iterator<iterator>
const_reverse_iterator reverse_iterator<const_iterator>

Caveats

Because map requires a strict weak ordering, a map keyed on floating-point numbers can produce undefined behavior if any of the keys are NaNs.

References

See also