pair in C++

Level 4219 keystrokes

Creates pairs with a constructor and with make_pair, reads them through first and second, and unpacks one with a structured binding.

C++ code

// A pair holds two values, here a string and an int
1pair<string, int> person("Alice", 25);
// first and second access the two values: prints Alice: 25
2cout << person.first << ": " << person.second << endl;
3
// make_pair deduces the types: here pair<const char*, int>
4auto p2 = make_pair("Bob", 30);
// Prints Bob: 30
5cout << p2.first << ": " << p2.second << endl;
6
// Structured binding (C++17) copies first into name and second into age
7auto [name, age] = p2;
// Prints Bob
8cout << name << endl;

Output

Alice: 25
Bob: 30
Bob
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 21
  • "× 8
  • ;× 6
  • ,× 4
  • .× 4
  • :× 2
  • (× 2
  • )× 2
  • =× 2
  • _× 1

More C++ examples at level 4

← C++ typing practice