WeCodeAcademy

C++ map, set and algorithms

The standard library gives you ready-made containers and algorithms. map stores key-value pairs in sorted order; set keeps unique values.

ExampleC++
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
  map<string, int> ages = {{"Sam", 22}, {"Ada", 36}};
  ages["Lee"] = 41;
  for (const auto &[name, age] : ages) {
    cout << name << " -> " << age << endl;
  }

  set<int> s = {3, 1, 3, 2, 1};
  cout << s.size() << endl;

  vector<int> v = {4, 8, 15, 16};
  cout << count_if(v.begin(), v.end(), [](int n) { return n % 2 == 0; }) << endl;
  return 0;
}
Output
Ada -> 36
Lee -> 41
Sam -> 22
3
3

The [](int n) { ... } part is a lambda: a small function written in place.

Quick check

In what order does std::map keep its keys?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.