In this C++ tutorial, you will learn how to unpack a given tuple into a list of variables using tie() function, with example programs.
Unpack Tuple Elements into Separate Variables in C++
tie() function unpacks the elements of a Tuple into variables.
In this tutorial, we will learn how to use tie() function to unpack a given tuple into a list of variables.
Syntax
The syntax of tie() function to unpack tuple x
into variables v1, v2, v3, and so on is
</>
Copy
tie(v1, v2, v3, .. ) = x
Examples
1. Unpack a three item tuple into three variables
In the following program, we declared a Tuple with three elements. We shall unpack this tuple into three separate variables.
C++ Program
</>
Copy
#include <iostream>
#include<tuple>
using namespace std;
int main() {
tuple<int, string, bool> fruit(3, "apple", true);
int id;
string name;
bool isAvailable;
tie(id, name, isAvailable) = fruit;
cout << "id : " << id << endl;
cout << "name : " << name << endl;
cout << "isAvailable : " << isAvailable << endl;
}
Output
id : 3
name : apple
isAvailable : 1
Program ended with exit code: 0
Conclusion
In this C++ Tutorial, we learned how to unpack elements of a tuple into separate variables using tie() function, with the help of example.