example2_unpacking_bindings.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <tuple>
#include <string>

std::tuple<std::string, int, double> getPersonInfo() {
    return std::make_tuple("Alice", 25, 1.65);
}

int main() {
    // Using std::tie for unpacking
    std::string name;
    int age;
    double height;
    std::tie(name, age, height) = getPersonInfo();
    std::cout << "Name: " << name << ", Age: " << age << ", Height: " << height << " m" << std::endl;

    // Using structured bindings (C++17)
    auto [name2, age2, height2] = getPersonInfo();
    std::cout << "Name: " << name2 << ", Age: " << age2 << ", Height: " << height2 << " m" << std::endl;

    // Ignoring some values
    std::string title;
    int year;
    std::tie(title, std::ignore, year) = std::make_tuple("The Catcher in the Rye", "J.D. Salinger", 1951);
    std::cout << "Book: " << title << ", Year: " << year << std::endl;

    return 0;
}
Back to tuple