C++ Pair和Tuple
2021-01-24 13:12
标签:pen font more auto pair const div temp image 1.Pair 1.1 Pair定义: 两个成员都是public。 实现一个泛型类函数模板,将一个pair写入一个stream内: C++11起,可以对pair使用类似Tuple的操作。 当时用tuple作为参数传递给first或/和second时,需要将std::piecewise_construct作为额外的第一个参数。 便捷函数make_pair() 2.Tuple tuple可以拥有任意数量的元素。 make_tuple() 和 tie() tie()是建立一个由引用构成的tuple。 tuple_size:可获取元素个数 tuple_element tuple_cat:可以将多个tuple串成一个tuple tuple的输入输出 tuple和pair的转化 C++ Pair和Tuple 标签:pen font more auto pair const div temp image 原文地址:https://www.cnblogs.com/xiaoaofengyue/p/12865409.htmlnamespace std {
templateclass _T1, class _T2>
struct pair
{
_T1 first;
_T2 second;
}
}
#include
using namespace std;
template
typedef pairint,float> IntFloatPair;
IntFloatPair p(10,20.3);
coutendl;
coutget0>(p)endl;
coutget1>(p)endl;
cout::valueendl;
tuple_element0,IntFloatPair>::type tmp=12.3;
cout
class Foo{
public:
Foo(tupleint,float> t){
cout"Foo::Foo(tuple)"endl;
}
template
pairint,string> mp=make_pair(10,"aaa");
#include
using namespace std;
int main(){
tuplestring,int,int,complexdouble>> t_tmp;
tupleint,float,string> t_tmp1(41,6.3,"nico");
coutget0>(t_tmp1)" ";
coutget1>(t_tmp1)" ";
coutget2>(t_tmp1)endl;
auto t_tmp2=make_tuple(22,44,"nico");
get1>(t_tmp1)=get1>(t_tmp2);
if(t_tmp1t_tmp2){
t_tmp1=t_tmp2;
}
}tupleint,float,string> t1(77,1.1,"more light");
int i;
float f;
string s;
cout"i="" f="" s="endl;
make_tuple(ref(i),ref(f),ref(s))=t1;
cout"t1: ";
coutget0>(t1)" ";
coutget1>(t1)" ";
coutget2>(t1)" "endl;
cout"i="" f="" s="endl;
int i2;
float f2;
string s2;
cout"i2="" f2="" s2="endl;
tie(i2,f2,s2)=t1;
cout"i2="" f2="" s2="
tupleint,float,string> t2(1,3.2,"aaa");
cout"t2 size="::valueendl;
tuple_element0,decltype(t2)>::type first=1;
cout"t2‘s first element="endl;
auto t3=tuple_cat(t1,t2);
cout"t3: ";
coutget0>(t3)" ";
coutget1>(t3)" ";
coutget2>(t3)" ";
coutget3>(t3)" ";
coutget4>(t3)" ";
coutget5>(t3)" "
#include "printtuple.hpp"
#include
tupleint,float> t4=make_pair(1,2.1);
cout"t4: "