tuple容器(元组), 是暗示元组容器, 是不包括任何布局的,快速而低质(粗制滥造, quick and dirty)的, 可以用于函数返回多个返回值;
tuple容器, 可以利用直接初始化, 和"make_tuple()"初始化, 会见元素利用"get<>()"要领, 留意get内里的位置信息, 必需是常量表达式(const expression);
可以通过"std::tuple_size<decltype(t)>::value"获取元素数量; "std::tuple_element<0, decltype(t)>::type"获取元素范例;
假如tuple范例举办较量, 则需要保持元素数量沟通, 范例可以较量, 如沟通范例, 或可以彼此转换范例(int&double);
无法通过普通的要领遍历tuple容器, 因为"get<>()"要领, 无法利用变量获取值;
以下代码包括一些根基的用法, 详见注释;
代码:
/* * CppPrimer.cpp * * Created on: 2013.12.9 * Author: Caroline */ /*eclipse cdt, gcc 4.8.1*/ #include <iostream> #include <vector> #include <string> #include <tuple> using namespace std; std::tuple<std::string, int> giveName(void) { std::string cw("Caroline"); int a(2013); std::tuple<std::string, int> t = std::make_tuple(cw, a); return t; } int main() { std::tuple<int, double, std::string> t(64, 128.0, "Caroline"); std::tuple<std::string, std::string, int> t2 = std::make_tuple("Caroline", "Wendy", 1992); //返回元素个数 size_t num = std::tuple_size<decltype(t)>::value; std::cout << "num = " << num << std::endl; //获取第1个值的元素范例 std::tuple_element<1, decltype(t)>::type cnt = std::get<1>(t); std::cout << "cnt = " << cnt << std::endl; //较量 std::tuple<int, int> ti(24, 48); std::tuple<double, double> td(28.0, 56.0); bool b = (ti < td); std::cout << "b = " << b << std::endl; //tuple作为返回值 auto a = giveName(); std::cout << "name: " << get<0>(a) << " years: " << get<1>(a) << std::endl; return 0; }
输出:
num = 3 cnt = 128 b = 1 name: Caroline years: 2013
作者:csdn博客 Spike_King