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

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:

主站蜘蛛池模板: 古交市| 外汇| 甘肃省| 玉山县| 保康县| 镇雄县| 南郑县| 大冶市| 瑞丽市| 三穗县| 万安县| 平乡县| 榕江县| 北安市| 股票| 安福县| 桃园市| 峨眉山市| 浙江省| 堆龙德庆县| 佛教| 元谋县| 江山市| 桐城市| 九龙坡区| 林西县| 太湖县| 丽水市| 渭南市| 兴海县| 永清县| 新密市| 丹寨县| 稷山县| 娄烦县| 定兴县| 泽州县| 北辰区| 双桥区| 凤庆县| 永仁县|