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

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:

主站蜘蛛池模板: 会泽县| 晋江市| 合山市| 德州市| 政和县| 新田县| 安顺市| 车险| 宝山区| 伊春市| 厦门市| 莎车县| 安西县| 新晃| 渭源县| 海口市| 大悟县| 安康市| 徐水县| 灵丘县| 泸水县| 镇安县| 祥云县| 珠海市| 鹿邑县| 安图县| 丹巴县| 东乡县| 湖南省| 五河县| 宜丰县| 明水县| 东乌珠穆沁旗| 咸阳市| 赣州市| 龙里县| 和平区| 余干县| 林州市| 班玛县| 安福县|