C++11元组(tuple)的浅谈
最近在看代码时,看到了tuple,之前没使用过,决定简单探索一下
先看原型
// 模板类
template< class... Types >
class tuple;
// 构造函数(有很多,就不一一罗列了,可以自行去reference查看)
tuple( const Types&... args );
template< class... UTypes >
tuple( UTypes&&... args );
template< class U1, class U2 >
tuple( const pair<U1,U2>& p );
...
cppreference对其描述如下
Class template std::tuple is a fixed-size collection of heterogeneous values.
It is a generalization of std::pair.
英文水平不太好的翻译:
类模板std::tuple是一个固定大小的异构值集合。这是std::pair的一般化!
Types... - the types of the elements that the tuple stores. Empty list is supported.
英文水平不太好的翻译:
元组存储的元素类型。支持空列表。
一般会将其当做通用结构来用,取代结构体让代码变得简洁些!
基本用法
元组的创建
-
使用函数make_tuple()
// 原型 template< class... Types > tuple<VTypes...> make_tuple( Types&&... args );
示例:tuple<int, double, char> tp = make_tuple(10, 2.2, 'a'); // 其实就类似于结构体 struct TEST { int a; double b; char c; };
-
还有一个函数也可以创建元组tie()
// 原型 Defined in header <tuple> template< class... Types > tuple<Types&...> tie( Types&... args ) noexcept; // 描述 Creates a tuple of lvalue references to its arguments or instances of std::ignore. // Parameters args - zero or more lvalue arguments to construct the tuple from // Return value A std::tuple object containing lvalue references.
// 示例: int a = 10; double b = 1.1; auto tp = tie(a, b);
-
也可以使用forward_as_tuple()创建
std::forward_as_tuple template< class... Types > tuple<Types&&...> forward_as_tuple( Types&&... args ) noexcept; // 描述:Constructs a tuple of references to the arguments in args suitable for forwarding as an argument to a function. The tuple has rvalue reference data members when rvalues are used as arguments, and otherwise has lvalue reference data members.
//示例: map<int, string> mp; // piecewise_construct是 piecewise_construct_t的实例, // piecewise_construct_t是一个空的结构标记类型,用于消除采用两个元组参数的不同函数之间的歧义。 mp.emplace(piecewise_construct, forward_as_tuple(2), forward_as_tuple(10, 'a')); cout << "m[2] = " << mp[2] << endl;
元组值得获取
-
使用函数std::get(std::tuple)函数
// 获取元祖的第一个值 cout << "tp.get<0> = " << get<0>(tp) << endl; // 获取第二个,第三个值 cout << "tp.get<1> = " << get<1>(tp) << endl; cout << "tp.get<1> = " << get<2>(tp) << endl;
-
还可以使用tie函数解包tuple
int myInt = 0; char myChar = '\0'; // tie解包tuple, std::ignore 忽略解该值 tie(myInt, std::ignore, myChar) = make_tuple(10, 2.2, 'a'); cout << "myInt = " << myInt << ", myChar = " << myChar << endl;
-
输出元组元素个数
cout << tuple_size<decltype(tp)>::value << endl;
如果本文对你有帮助,记得一键三连哦!
本人能力有限,如有错误,望不吝指正;原创不易,欢迎转载,转载请注明出处!
参考博文:https://www.cnblogs.com/qicosmos/p/3318070.html