Tuple Type in C++

Level 5343 keystrokes

A tuple groups values of different types. Elements are read with get<index>, unpacked with structured bindings (auto [a, b, c]), and make_tuple builds a tuple with deduced types.

C++ code

// A tuple of three different types: name, age and height
1tuple<string, int, double> person("Alice", 30, 5.6);
2
// get<0> reads the first element (the index must be a compile-time constant)
3cout << "Name: " << get<0>(person) << endl;
// Prints "Age: 30"
4cout << "Age: " << get<1>(person) << endl;
// Prints "Height: 5.6"
5cout << "Height: " << get<2>(person) << endl;
6
// Structured binding (C++17) unpacks the tuple into three variables (as copies)
7auto [name, age, height] = person;
// Prints "Alice is 30 years old"
8cout << name << " is " << age << " years old" << endl;
9
// make_tuple deduces the types: tuple<const char*, int>
10auto info = make_tuple("Bob", 25);
// Prints "Bob"
11cout << get<0>(info) << endl;

Output

Name: Alice
Age: 30
Height: 5.6
Alice is 30 years old
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.

  • <× 37
  • "× 14
  • ;× 8
  • ,× 7
  • (× 6
  • )× 6
  • >× 5
  • :× 3
  • =× 2
  • _× 1

More C++ examples at level 5

← C++ typing practice