pair and tuple

The STL (Standard Template Library) is the big toolbox that comes with C++. You've already used two of its tools: vector and string. This module shows the rest of the most useful ones.

pair: two values together

#include <iostream>
#include <string>
#include <utility>
using namespace std;

int main() {
    pair<string, int> item = {"apples", 6};
    cout << item.first << ": " << item.second << "\n";
    item.second += 4;
    cout << item.first << ": " << item.second << "\n";

    auto p = make_pair(3.5, 'x');
    cout << p.first << " " << p.second << "\n";
    return 0;
}

Output

apples: 6
apples: 10
3.5 x

The two parts are always called first and second.

tuple: more values together

#include <iostream>
#include <string>
#include <tuple>
using namespace std;

tuple<string, int, double> getPlayer() {
    return {"Zara", 12, 98.5};
}

int main() {
    auto t = getPlayer();
    cout << get<0>(t) << " " << get<1>(t) << " " << get<2>(t) << "\n";

    auto [name, level, health] = getPlayer();    // structured binding
    cout << name << " is on level " << level << " with " << health << " health\n";
    return 0;
}

Output

Zara 12 98.5
Zara is on level 12 with 98.5 health

Tip: auto [a, b, c] = ...; (a structured binding) unpacks a pair, tuple or struct into separate named variables. It's much easier to read than get<0>.

HOME LABS COMMUNITY DASHBOARD