Skip to content

Tuples

Tuples

Class template std::tuple is a fixed-size collection of heterogeneous values. It is a generalization of std::pair for more than 2 values.

1
#include <tuple>

1
2
3
4
5
6
7
8
9
void reference_minmax(int a, int b, int &min, int &max) {
    if (a < b) {
        min = a;
        max = b;
    } else {
        min = b;
        max = a;
    }
}

1
2
3
4
5
6
7
std::tuple<int, int> tuple_minmax(int a, int b) {
    if (a < b) {
        return std::make_tuple(a, b);
    } else {
        return std::make_tuple(b, a);
    }
}

1
2
3
4
5
int min;
int max;
reference_minmax(3, 2, min, max);
std::cout << "min : " << min << '\n';
std::cout << "max : " << max << '\n';

1
2
3
auto t4 = tuple_minmax(3, 2);
std::cout << "min : " << std::get<0>(t4) << '\n';
std::cout << "max : " << std::get<1>(t4) << '\n';

1
2
3
4
5
6
7
struct my_pair {
    char first;
    int second;
};
// ...
my_pair s{'c', 15};
std::cout << "s.first: " << s.first << ", s.second: " << s.second << '\n';

1
2
std::pair<char, int> p{'c', 15};
std::cout << "p.first: " << p.first << ", p.second: " << p.second << '\n';

1
2
std::pair<char, int> t('c', 15);
std::cout << "t.first: " << t.first << ", t.second: " << t.second << '\n';

1
2
3
auto t2 = std::make_pair<char, int>('c', 15);
std::cout << "t2.first: " << t2.first << ", t2.second: " << t2.second
          << '\n';

1
2
3
4
5
auto t3 = std::make_tuple(6.3, "text", 2, 'o');
char x = std::get<3>(t3);
std::cout << "x: " << x << '\n';
std::cout << "std::get<0>(t3): " << std::get<0>(t3)
          << ", std::get<1>(t3): " << std::get<1>(t3) << '\n';

1
2
3
4
5
int a;
char b;
std::tie(std::ignore, std::ignore, a, b) = t3;
std::cout << "a: " << a << '\n';
std::cout << "b: " << b << '\n';

1
2
3
4
5
int min2;
int max2;
std::tie(min2, max2) = tuple_minmax(3, 2);
std::cout << "min : " << min2 << '\n';
std::cout << "max : " << max2 << '\n';

1
2
3
auto [min3, max3] = tuple_minmax(3, 2);
std::cout << "min : " << min3 << '\n';
std::cout << "max : " << max3 << '\n';

Share Snippets