c++ 11 tuple

生活百科 2023-01-25 19:31生活百科www.aizhengw.cn

c++ 11 tuple

tuple元组定义了一个有固定数目元素的容器,其中的每个元素类型都可以不相同,这与其他容器有着本质的区别.是对pair的泛化。

首先来介绍元组的创建和元组元素的访问。通过make_tuple()创建元组,通过get<>()来访问元组的元素。通过下面这段程式来认识这两个函式的用法:
#include <iostream>
#include <tuple>
#include <functional>
int main()
{
auto t1 = std::make_tuple(10, "Test", 3.14);
std::cout << "The value of t1 is "
<< "(" << std::get<0>(t1) << ", " << std::get<1>(t1)
<< ", " << std::get<2>(t1) << ")\n";
int n = 1;
auto t2 = std::make_tuple(std::ref(n), n);//ref表示引用
n = 7;
std::cout << "The value of t2 is "
<< "(" << std::get<0>(t2) << ", " << std::get<1>(t2) << ")\n";
}
运行结果为:
The value of t1 is (10, Test, 3.14)
The value of t2 is (7, 1)

Copyright@2015-2025 www.aizhengw.cn 癌症网版板所有