- Learning C++ Functional Programming
- Wisnu Anggoro
- 207字
- 2021-07-02 20:51:39
Storing many different data types using tuples
We will get acquainted with tuples, an object that is able to hold a collection of elements, and each element can be of a different type. It is a new feature in C++11 and gives power to functional programming. The tuples will be most useful when creating a function that returns the value. Moreover, since functions don't change the global state in functional programming, we can return the tuples for all the values we need to change instead. Now, let's examine the following piece of code:
/* tuples_1.cpp */
#include <tuple>
#include <iostream>
using namespace std;
auto main() -> int
{
cout << "[tuples_1.cpp]" << endl;
// Initializing two Tuples
tuple<int, string, bool> t1(1, "Robert", true);
auto t2 = make_tuple(2, "Anna", false);
// Displaying t1 Tuple elements
cout << "t1 elements:" << endl;
cout << get<0>(t1) << endl;
cout << get<1>(t1) << endl;
cout << (get<2>(t1) == true ? "Male" : "Female") << endl;
cout << endl;
// Displaying t2 Tuple elements
cout << "t2 elements:" << endl;
cout << get<0>(t2) << endl;
cout << get<1>(t2) << endl;
cout << (get<2>(t2) == true ? "Male" : "Female") << endl;
cout << endl;
return 0;
}
In the preceding code, we created two tuples, t1 and t2, with different constructing techniques using tuple<int, string, bool> and make_tuple. However, these two different techniques will give the same result. Obviously, in the code, we access each element in tuples using get<x>(y), where x is the index and y is the tuple object. And, with confidence, we will get the following result on the console:
