c++ pair和tuple的操作

//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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值