1.Pair
1.1 Pair定义:
namespace std { template<class _T1, class _T2> struct pair { _T1 first; _T2 second; } }
两个成员都是public。
实现一个泛型类函数模板,将一个pair写入一个stream内:
#include <iostream>
using namespace std;
template <typename T1,typename T2> ostream& operator<< (ostream& strm,const pair<T1,T2>& p){ return strm<<"["<<p.first<<","<<p.second<<"]"; }
C++11起,可以对pair使用类似Tuple的操作。
typedef pair<int,float> IntFloatPair;
IntFloatPair p(10,20.3); cout<<p<<endl; cout<<get<0>(p)<<endl; cout<<get<1>(p)<<endl; cout<<tuple_size<IntFloatPair>::value<<endl; tuple_element<0,IntFloatPair>::type tmp=12.3; cout<<tmp<<endl;
当时用tuple作为参数传递给first或/和second时,需要将std::piecewise_construct作为额外的第一个参数。
class Foo{ public: Foo(tuple<int,float> t){ cout<<"Foo::Foo(tuple)"<<endl; } template<typename... Args> Foo(Args... args){ cout<<"Foo::Foo(args...)"<<endl; } }; int main() { tuple<int,float> t(1,2.22); pair<int,Foo> p1(42,t); pair<int,Foo> p2(piecewise_construct,make_tuple(42),t); }
便捷函数make_pair()
pair<int,string> mp=make_pair(10,"aaa");
2.Tuple
tuple可以拥有任意数量的元素。
#include <tuple> #include <string> #include <complex>
using namespace std; int main(){ tuple<string,int,int,complex<double>> t_tmp; tuple<int,float,string> t_tmp1(41,6.3,"nico"); cout<<get<0>(t_tmp1)<<" "; cout<<get<1>(t_tmp1)<<" "; cout<<get<2>(t_tmp1)<<endl; auto t_tmp2=make_tuple(22,44,"nico"); get<1>(t_tmp1)=get<1>(t_tmp2); if(t_tmp1<t_tmp2){ t_tmp1=t_tmp2; } }
make_tuple() 和 tie()
tie()是建立一个由引用构成的tuple。
tuple<int,float,string> t1(77,1.1,"more light"); int i; float f; string s; cout<<"i="<<i<<" f="<<f<<" s="<<s<<endl; make_tuple(ref(i),ref(f),ref(s))=t1; cout<<"t1: "; cout<<get<0>(t1)<<" "; cout<<get<1>(t1)<<" "; cout<<get<2>(t1)<<" "<<endl; cout<<"i="<<i<<" f="<<f<<" s="<<s<<endl; int i2; float f2; string s2; cout<<"i2="<<i2<<" f2="<<f2<<" s2="<<s2<<endl; tie(i2,f2,s2)=t1; cout<<"i2="<<i2<<" f2="<<f2<<" s2="<<s2<<endl;
tuple_size:可获取元素个数
tuple_element<idx,tupletype>::type:可获取第idx个元素的类型
tuple_cat:可以将多个tuple串成一个tuple
tuple<int,float,string> t2(1,3.2,"aaa"); cout<<"t2 size="<<tuple_size<decltype(t2)>::value<<endl; tuple_element<0,decltype(t2)>::type first=1; cout<<"t2's first element="<<first<<endl; auto t3=tuple_cat(t1,t2); cout<<"t3: "; cout<<get<0>(t3)<<" "; cout<<get<1>(t3)<<" "; cout<<get<2>(t3)<<" "; cout<<get<3>(t3)<<" "; cout<<get<4>(t3)<<" "; cout<<get<5>(t3)<<" "<<endl;
tuple的输入输出
#include "printtuple.hpp" #include <iostream> #include <tuple> #include <string> int main() { tuple<int,float,string> tt(77,1.1,"more light"); cout<<"io: "<<tt<<endl; }
tuple和pair的转化
tuple<int,float> t4=make_pair(1,2.1); cout<<"t4: "<<t4<<endl;