Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/container/map"

From cppreference.com
< cpp‎ | container
(expand code example to show iterating with legacy iterators too)
m (roll over comment line to 2 lines)
Line 132: Line 132:
 
     std::cout << "\n";
 
     std::cout << "\n";
  
     // 2. Use `auto` for the iterator; notice we use `cbegin()` and `cend()` here to force `auto`
+
     // 2. Use `auto` for the iterator; notice we use `cbegin()` and `cend()`  
    // to be a `const_iterator`
+
    // here to force `auto` to be a `const_iterator`
 
     for (auto it = m.cbegin(); it != m.cend(); it++) {
 
     for (auto it = m.cbegin(); it != m.cend(); it++) {
 
         std::cout << it->first << " = " << it->second << "; ";
 
         std::cout << it->first << " = " << it->second << "; ";

Revision as of 16:28, 24 January 2022

 
 
 
 
Defined in header <map>
template<

    class Key,
    class T,
    class Compare = std::less<Key>,
    class Allocator = std::allocator<std::pair<const Key, T> >

> class map;
(1)
namespace pmr {

    template <class Key, class T, class Compare = std::less<Key>>
    using map = std::map<Key, T, Compare,
                         std::pmr::polymorphic_allocator<std::pair<const Key,T>>>

}
(2) (since C++17)

std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare. Search, removal, and insertion operations have logarithmic complexity. Maps are usually implemented as red-black trees.

Everywhere the standard library uses the Compare requirements, uniqueness is determined by using the equivalence relation. In imprecise terms, two objects a and b are considered equivalent (not unique) if neither compares less than the other: !comp(a, b) && !comp(b, a).

std::map meets the requirements of Container, AllocatorAwareContainer, AssociativeContainer and ReversibleContainer.

Contents

Member types

Member type Definition
key_type Key[edit]
mapped_type T[edit]
value_type std::pair<const Key, T>[edit]
size_type Unsigned integer type (usually std::size_t)[edit]
difference_type Signed integer type (usually std::ptrdiff_t)[edit]
key_compare Compare[edit]
allocator_type Allocator[edit]
reference value_type&[edit]
const_reference const value_type&[edit]
pointer

Allocator::pointer

(until C++11)

std::allocator_traits<Allocator>::pointer

(since C++11)
[edit]
const_pointer

Allocator::const_pointer

(until C++11)

std::allocator_traits<Allocator>::const_pointer

(since C++11)
[edit]
iterator LegacyBidirectionalIterator to value_type[edit]
const_iterator LegacyBidirectionalIterator to const value_type[edit]
reverse_iterator std::reverse_iterator<iterator>[edit]
const_reverse_iterator std::reverse_iterator<const_iterator>[edit]
node_type (since C++17) a specialization of node handle representing a container node[edit]
insert_return_type (since C++17) type describing the result of inserting a node_type, a specialization of

template<class Iter, class NodeType>
struct /*unspecified*/
{
    Iter     position;
    bool     inserted;
    NodeType node;
};

instantiated with template arguments iterator and node_type.[edit]

Member classes

compares objects of type value_type
(class) [edit]

Member functions

constructs the map
(public member function) [edit]
destructs the map
(public member function) [edit]
assigns values to the container
(public member function) [edit]
returns the associated allocator
(public member function) [edit]
Element access
access specified element with bounds checking
(public member function) [edit]
access or insert specified element
(public member function) [edit]
Iterators
returns an iterator to the beginning
(public member function) [edit]
(C++11)
returns an iterator to the end
(public member function) [edit]
returns a reverse iterator to the beginning
(public member function) [edit]
(C++11)
returns a reverse iterator to the end
(public member function) [edit]
Capacity
checks whether the container is empty
(public member function) [edit]
returns the number of elements
(public member function) [edit]
returns the maximum possible number of elements
(public member function) [edit]
Modifiers
clears the contents
(public member function) [edit]
inserts elements or nodes(since C++17)
(public member function) [edit]
inserts an element or assigns to the current element if the key already exists
(public member function) [edit]
(C++11)
constructs element in-place
(public member function) [edit]
constructs elements in-place using a hint
(public member function) [edit]
inserts in-place if the key does not exist, does nothing if the key exists
(public member function) [edit]
erases elements
(public member function) [edit]
swaps the contents
(public member function) [edit]
(C++17)
extracts nodes from the container
(public member function) [edit]
(C++17)
splices nodes from another container
(public member function) [edit]
Lookup
returns the number of elements matching specific key
(public member function) [edit]
finds element with specific key
(public member function) [edit]
(C++20)
checks if the container contains element with specific key
(public member function) [edit]
returns range of elements matching a specific key
(public member function) [edit]
returns an iterator to the first element not less than the given key
(public member function) [edit]
returns an iterator to the first element greater than the given key
(public member function) [edit]
Observers
returns the function that compares keys
(public member function) [edit]
returns the function that compares keys in objects of type value_type
(public member function) [edit]

Non-member functions

(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20)
lexicographically compares the values of two maps
(function template) [edit]
specializes the std::swap algorithm
(function template) [edit]
erases all elements satisfying specific criteria
(function template) [edit]

Deduction guides (since C++17)

Example

#include <iostream>
#include <map>
#include <string>
#include <string_view>
 
void print_map(std::string_view comment, const std::map<std::string, int>& m)
{
    std::cout << comment << "\n";
 
    // Demonstrate multiple ways to iterate over the `std::map`
 
    // ----------------------------
    // Legacy iterators
    // ----------------------------
 
    // 1. Use explicit iterator
    for (std::map<std::string, int>::const_iterator it = m.begin(); it != m.end(); it++) {
        std::cout << it->first << " = " << it->second << "; ";
    }
    std::cout << "\n";
 
    // 2. Use `auto` for the iterator; notice we use `cbegin()` and `cend()` 
    // here to force `auto` to be a `const_iterator`
    for (auto it = m.cbegin(); it != m.cend(); it++) {
        std::cout << it->first << " = " << it->second << "; ";
    }
    std::cout << "\n";
 
    // ----------------------------
    // Range-based for loops
    // ----------------------------
 
    // 1. Explicitly specify the `std::pair` iterator 
    for (const std::pair<const std::string, int>& n : m) {
        std::cout << n.first << " = " << n.second << "; ";
    }
    std::cout << "\n";
 
    // 2. Use `auto` for the `std::pair` iterator 
    for (const auto& n : m) {
        std::cout << n.first << " = " << n.second << "; ";
    }
    std::cout << "\n";
 
    // 3. Iterate using automatic "structured binding" to `key`, `value` variables
    //    (since C++17)
    for (const auto& [key, value] : m) {
        std::cout << key << " = " << value << "; ";
    }
    std::cout << "\n";
}
 
int main()
{
    // Create a map of three (strings, int) pairs
    std::map<std::string, int> m { {"CPU", 10}, {"GPU", 15}, {"RAM", 20}, };
 
    print_map("Initial map: ", m);
    std::cout << "\n";
 
    m["CPU"] = 25;  // update an existing value
    m["SSD"] = 30;  // insert a new value
    print_map("Updated map: ", m);
    std::cout << "\n";
 
    // using operator[] with non-existent key always performs an insert
    std::cout << "m[new_key] = " << m["new_key"] << "\n";
    print_map("Updated map: ", m);
}

Output:

Initial map: 
CPU = 10; GPU = 15; RAM = 20; 
CPU = 10; GPU = 15; RAM = 20; 
CPU = 10; GPU = 15; RAM = 20; 
CPU = 10; GPU = 15; RAM = 20; 
CPU = 10; GPU = 15; RAM = 20; 
 
Updated map: 
CPU = 25; GPU = 15; RAM = 20; SSD = 30; 
CPU = 25; GPU = 15; RAM = 20; SSD = 30; 
CPU = 25; GPU = 15; RAM = 20; SSD = 30; 
CPU = 25; GPU = 15; RAM = 20; SSD = 30; 
CPU = 25; GPU = 15; RAM = 20; SSD = 30; 
 
m[new_key] = 0
Updated map: 
CPU = 25; GPU = 15; RAM = 20; SSD = 30; new_key = 0; 
CPU = 25; GPU = 15; RAM = 20; SSD = 30; new_key = 0; 
CPU = 25; GPU = 15; RAM = 20; SSD = 30; new_key = 0; 
CPU = 25; GPU = 15; RAM = 20; SSD = 30; new_key = 0; 
CPU = 25; GPU = 15; RAM = 20; SSD = 30; new_key = 0;

Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
LWG 464 C++98 accessing a const map by key was inconvenient at function provided

See also

collection of key-value pairs, hashed by keys, keys are unique
(class template) [edit]