๐ŸŽ“ A1Learner
๐Ÿ”

C++ Maps

A map is a collection that stores pairs of a key and a value. A program reads a value by naming its key.

Inserting and reading pairs

Three pairs go into the map in an unsorted order. The last line reads the value for the key Ana.

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

int main() {
  std::map<std::string, int> ages;
  ages["Hana"] = 31;
  ages["Ana"] = 25;
  ages["Bo"] = 28;
  std::cout << ages["Ana"] << std::endl;
  return 0;
}

Keys print in sorted order

auto lets the compiler work out the pair's type. The pairs print with keys in sorted order, Ana, Bo, and Hana.

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

int main() {
  std::map<std::string, int> ages;
  ages["Bo"] = 28;
  ages["Hana"] = 31;
  ages["Ana"] = 25;
  for (auto pair : ages) {
    std::cout << pair.first << " " << pair.second << std::endl;
  }
  return 0;
}

Checking keys with count

count gives 1 for a key that is present. count gives 0 for a key that is absent.

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

int main() {
  std::map<std::string, int> ages;
  ages["Ana"] = 25;
  ages["Bo"] = 28;
  ages["Hana"] = 31;
  std::cout << ages.count("Bo") << std::endl;
  std::cout << ages.count("Zoe") << std::endl;
  return 0;
}

Erasing a pair

erase removes the pair for Bo. size prints 3 before the removal and 2 after it.

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

int main() {
  std::map<std::string, int> ages;
  ages["Ana"] = 25;
  ages["Bo"] = 28;
  ages["Hana"] = 31;
  std::cout << ages.size() << std::endl;
  ages.erase("Bo");
  std::cout << ages.size() << std::endl;
  return 0;
}

Example

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

int main() {
  std::map<std::string, int> stock;
  stock["Pen"] = 10;
  stock["Ruler"] = 5;
  stock["Notebook"] = 8;
  int total = 0;
  for (auto pair : stock) {
    std::cout << pair.first << " " << pair.second << std::endl;
    total += pair.second;
  }
  std::cout << "Total items: " << total << std::endl;
  return 0;
}

Key points

  • The <map> header gives the program std::map.
  • std::map stores pairs of a key and a value.
  • Square brackets with a key set or read the value for that key.
  • Each pair holds its key as first and its value as second.
  • The count method gives 1 when a key is present and 0 when it is absent.
  • The erase method removes the pair for a key.
  • The size method gives the number of pairs in the map.

In this example, the stock map holds counts for three items. The loop prints each pair in sorted key order and adds each count to total. The last line prints Total items: 23.

Note

std::map keeps its keys in sorted order.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C++ Compiler

Exercise

A map holds the keys Hana, Ana, and Bo. In which order does a range-for loop visit them?