get first element of tuple c++
To get the first element of a tuple in C++, you can follow these steps:
- Declare a tuple variable: Begin by declaring a tuple variable and assigning it a value.
- Access the first element: Use the
std::get<0>()
function template to access the first element of the tuple. Replace0
with the appropriate index if you want to access a different element.
Here's an example:
#include <iostream>
#include <tuple>
int main() {
// Declare a tuple variable
std::tuple<int, float, std::string> myTuple(42, 3.14, "Hello");
// Access the first element
int firstElement = std::get<0>(myTuple);
// Print the first element
std::cout << "First element: " << firstElement << std::endl;
return 0;
}
In this example, we declare a tuple myTuple
with three elements: an integer, a float, and a string. We then use std::get<0>(myTuple)
to access the first element, which is of type int
. Finally, we print the first element using std::cout
.
Output:
First element: 42
Note: Make sure to include the <tuple>
header to use tuples in C++.