C++ Pairs and Tuples
Pairs
pair<int, string> pr1; // declare
pr1 = {23, "helllo"}; // initialise or update
cout << pr1.first << " " << pr1.second << endl; // print
pr1 = {100, "Sarthak"};
pr1.second = "Sid";
cout << pr1.first << " " << pr1.second << endl;
Tuples
tuple<DataType x1, DataType x2, ...DataType xN> tupleName
tuple<int, string, double> pl1 = {12, "hello", 56.10};
cout << get<0>(pl1) << get<1>(pl1) << get<2>(pl1) << endl;
// must initialise the variables of the same size of the tuple whose value are to be assigned to them
// here tuple `tpl1` has 3 values so three variables of those respective "types" are declared
int x;
string str;
double d;
tie(x, str, d) = pl1;// giving values of tuple `tpl1` to the `s1`, `s2`, `s3`
cout << x << str << d << endl;
tie()
- giving all
tuple<>
values to separate variables usingtie()
// must initialise the variables of the same size of the tuple whose value are to be assigned to them
// here tuple `tpl1` has 3 values so three strings are declared
string s1;
string s2;
string s3;
tie(s1, s2, s3) = tpl1; // giving values of tuple `tpl1` to the `s1`, `s2`, `s3`
tie()
can also be used to initialisetuple<>
But Best way is to usetupleName = {..., .., ...} ⏩
tuple<int, string, double> pl1 = {12, "hello", 56.10};`
tuple<int, int, int> t = tie(a, b, c);