access elements of tuple c++ code example

Example 1: get elements of tuple c++

#include <tuple>
#include <iostream>
int main()
{
    auto t = std::make_tuple(1, "Foo", 3.14);
    // index-based access
    std::cout << "(" << std::get<0>(t) << ", " << std::get<1>(t)
              << ", " << std::get<2>(t) << ")\n";
}

Example 2: get first element of tuple c++

#include <iostream>
#include <string>
#include <tuple>
 
auto t = std::make_tuple(1, "Foo", 3.14);
// index-based access
std::cout << "(" << std::get<0>(t) << ", " << std::get<1>(t)<< ", " << std::get<2>(t) << ")\n";
// type-based access (C++14 or later)
std::cout << "(" << std::get<int>(t) << ", " << std::get<const char*>(t) << ", " << std::get<double>(t) << ")\n";

Tags:

Cpp Example