In this C++ tutorial, you will learn how to initialize a tuple with values during declaration or using tuple::make_tuple() function, with example programs.
Initialise a Tuple in C++
There are two ways in which we can initialise a Tuple.
- Specify the elements of Tuple in the declaration of Tuple.
- Use make_tuple() function to initialise a tuple variable.
In this tutorial, we will learn how to initialise a tuple using these two methods.
1. Initialise tuple in declaration
To initialise a Tuple during its declaration, provide the elements of Tuple as comma separated values after the tuple name in parenthesis.
tuple<datatype, datatype> fruit(element1, element2);
In the following program, we initialise a tuple named fruit
.
C++ Program
#include <iostream>
#include<tuple>
using namespace std;
int main() {
tuple<int, string, bool> fruit(3, "apple", true);
cout << "Tuple : "
<< get<0>(fruit) << " "
<< get<1>(fruit) << " "
<< get<2>(fruit) << " "
<< endl;
}
Output
Tuple : 3 apple 1
Program ended with exit code: 0
2. Initialise tuple using make_tuple()
make_tuple() function creates a tuple from given elements.
make_tuple(element1, element2);
In the following program, we initialise a tuple named fruit
using make_tuple() function.
C++ Program
#include <iostream>
#include<tuple>
using namespace std;
int main() {
tuple<int, string, bool> fruit;
fruit = make_tuple(3, "apple", true);
cout << "Tuple : "
<< get<0>(fruit) << " "
<< get<1>(fruit) << " "
<< get<2>(fruit) << " "
<< endl;
}
Output
Tuple : 3 apple 1
Program ended with exit code: 0
Conclusion
In this C++ Tutorial, we learned how to initialise a Tuple during declaration or using make_tuple() function, with examples.