c++ pair和tuple的操作

来源:互联网 发布:苏州单片机培训班 编辑:程序博客网 时间:2024/06/16 05:37

//c++ pair和tuple的操作
//1.初始化见函数Init() tupleTopair() class Foo;
//2.pair的输出 见print()
//3.pair关于tuple的接口 见函数 tupleInpair()
//4.make_pair() 见mp()
//5.pair c++11 注意点 pair<>里类型若只有一个
//nonconstant copy函数编译器将报错

#include<iostream>#include<tuple>using namespace std;void Init(){    //初始化    //常规初始化    pair<int, double> p1(4, 4.22);//...    //用tuple初始化//更多见函数tupleTopair和class Foo    pair<int, double> p2(piecewise_construct, make_tuple(2), make_tuple(2.33));}class Foo{public:    Foo(tuple<int, double>)    {        cout << "Foo::Foo(tuple)" << endl;    }    template<typename ...Args>    Foo(Args...args)    {        cout << "Foo::Foo(args...)" << endl;    }};void tupleTopair(){    tuple<int, double> t(4, 4.33);    pair<int, Foo> p1(43, t);//调用Foo(tuple<int,double>)    //因Class pair<>提供逐块构造函数则指明piecewise_construct会调用    //Foo(Arg...args)    pair<int, Foo> p2(piecewise_construct, make_tuple(43), make_tuple(45, 37));}template<typename T1,typename T2>ostream& operator <<(ostream& os, const pair<T1, T2>& p){    return os << "[" << p.first << "," << p.second << "]";}void print(){    pair<int, double> p(2, 3.444);    cout << p;}void tupleInpair(){    pair<int, double> p(2, 4.333);    //用get<0>(p) get<1>(p)得到p.first p.second    cout << get<0>(p) << ends << get<1>(p) << endl;    //得到类型的个数    cout << tuple_size<pair<int, double>>::value << endl;    //得到特定位置的类型    tuple_element<0, pair<int, double>>::type a = 4;    cout << a << endl;    //使用tuple的tie()接口抽取pair的value    double d;    tie(ignore, d) = p;    cout << d << endl;}void mp(){    int a = 3;    int b = 4;    auto p1 = make_pair(a, b);    ++a;//a = 4;    --b;//b = 3;    cout << p1.first << ends << p1.second << endl;    auto p2 = make_pair(ref(a), ref(b));//a = 4; b = 3;    --a;    ++b;    //a = 3 b = 4;    cout << p2.first << ends << p2.second << endl;}int main(){    //tupleTopair();    //print();    //tupleInpair();    mp();    system("pause");    return 0;}
0 0