官术网_书友最值得收藏!

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:

主站蜘蛛池模板: 大庆市| 木兰县| 高密市| 陆河县| 谢通门县| 太原市| 丹东市| 施甸县| 巢湖市| 泽州县| 延边| 舞阳县| 晋宁县| 巴东县| 外汇| 宁津县| 武穴市| 措勤县| 松江区| 台山市| 铜川市| 大石桥市| 科尔| 安国市| 宁海县| 南康市| 娄烦县| 景谷| 西吉县| 宜良县| 渝中区| 镇安县| 元江| 泰安市| 竹山县| 合水县| 永春县| 临夏市| 仁寿县| 延寿县| 攀枝花市|