Why Tuple?

Why Tuple?

九月 21, 2021

C++ 11 introduces a template Tuple, similar to the one in Python, allows you to store data of different types in a single entity. But you may ask, in C/C++,we already have some mechaism called struct allows us to do the same thing, then why do we need tuple?

Case 1: One-Time Structure to Transfer Data

1
2
3
4
5
6
7
8
9
10
11
12
13
14
tuple<string,int> getNameAge()
{
//do something
return make_tuple("Bob",34);
}
int main()
{
struct Person{string name;int age;}p;
tuple<string,int> t;

string name;
int age;
tie(name,age) = getNameAge();
}

If we want to transfer a group of data for only one time, we may not want to define a struct, and using tuple get us away from these definitions.

Case 2: Fast Comparison Using Tuple Operators

1
2
3
tuple<int,int,int> time1,time2;
if(time1>time2)
cout<<"time1 is later"

Case 3: Multi-Index Map/Unordered Map

1
2
3
4
//define
map<tuple<int,char,float>,string> m;
//indexing
m[make_tuple(2,'a',1.0)] = "Test";

Case 4: Fast Swap

1
2
int a,b,c;
tie(b,c,a) = make_tuple(a,b,c);

Conclusion:

Tuple is not recommended to be overused. If needed, use struct instead.