The subscript operator accesses an element associated with a key or index. For std::map, it can query an existing value, insert a missing key with a default value, or replace an existing value. section 7.1.1 section 7.4
Use operator[] with a mutable map when its insertion behavior is appropriate:
- Assigning dictionary["assume"] adds the key and value. section 7.1.1
- Reading dictionary["fictional"] inserts the missing key with a defaulted std::string, producing an empty value. section 7.1.1
- Assigning an existing key replaces its value because a map stores one value per key. section 7.1.1
- Avoid operator[] on a const map; use at instead when a missing key should throw std::out_of_range rather than modify the map. section 7.1.1
Tallying values
A map can count categories compactly: ++last_digits[number % 10] obtains the existing count or creates a missing digit with the default size_t value 0, then increments it. section 9.1.4
Building a dictionary game
A mutable map can be populated with keyword definitions using assignments such as keywords["char"] = "type for character representation...". Once initialized, a const map prevents accidental changes, while at retrieves definitions safely. section 7.1.3
Listing 7.1 Creating and displaying a map
#include <iostream>
#include <map>
#include <string>
void warm_up()
{
std::map<std::string, std::string> dictionary; #1
dictionary["assume"] = "take for granted, take to be the case"; #2
std::string new_value = dictionary["fictional"]; #3
for (const auto & item : dictionary) #4
{
std::cout << item.first << " : " << item.second << '\n'; #5
}
}
int main()
{
warm_up();
}
Inspect a complete warm-up that creates a string map, inserts an entry, accidentally inserts a missing key through lookup, and prints the resulting pairs. section 7.1.1
