C++_3——库(tuple)

C++_3——库(tuple)

  这一系列文章的目的是在学习了C++基础后,继续补充一些C++基础和进阶的知识点,包括C++11的相关内容。
以C++11标准为基础。

C++网站:http://www.cplusplus.com/reference/

  1. tuple类似于C语言的结构体,tuple访问成员不用变量名而是变量顺序,tuple内的变量类型可不同
  2. 基本使用
    #include <tuple> 
    // 构造
    std::tuple<int,char> first;                             // default
    std::tuple<int,char> second (first);                    // copy
    std::tuple<int,char> third (std::make_tuple(20,'b'));   // move
    std::tuple<long,char> fourth (third);                   // implicit conversion
    std::tuple<int,char> fifth (10,'a');                    // initialization
    std::tuple<int,char> sixth (std::make_pair(30,'c'));    // from pair / move
    
    // std::make_tuple
    auto first = std::make_tuple (10,'a');             		// tuple < int, char >
    
    const int a = 0; int b[3];                         		// decayed types:
    auto second = std::make_tuple (a,b);               		// tuple < int, int* >
    
    auto third = std::make_tuple (std::ref(a),"abc");  		// tuple < const int&, const char* >
    
    // std::tie
    int myint;
    char mychar;
    
    std::tuple<int,float,char> mytuple;
    mytuple = std::make_tuple (10, 2.6, 'a');          // packing values into tuple
    std::tie (myint, std::ignore, mychar) = mytuple;   // unpacking tuple into variables
    
    // std::get 这里返回的是元素的引用
    std::tuple<int,char> mytuple (10,'a');
    std::get<0>(mytuple) = 20;
    std::cout << std::get<0>(mytuple) << " and " << std::get<1>(mytuple); // 20 and a
    
    // std::tuple_cat 串联不同的tuple
    std::tuple<float,std::string> mytuple (3.14,"pi");
    std::pair<int,char> mypair (10,'a');
    auto myauto = std::tuple_cat ( mytuple, std::tuple<int,char>(mypair) );
    
  3. 其他
    1. std::ref与std::cref的使用,参见这篇博客
      std::ref为引用传递,std::cref为const引用传递
    2. std::ignore
      一方面是作为std::tie的占位符,另一方面还可以避免一些未使用函数返回值的warning,如下,nodiscard用于提示这个函数的返回值很重要,不应丢弃,一旦丢弃则发出自定义的字符串以警告(“important…info output”),但如果使用std::ignore,则没有警告。
    #include <tuple>
     
    [[nodiscard("important...info output")]] int dontIgnoreMe(){
        return 42;
    }
     
    int main(){
        std::ignore = dontIgnoreMe();
    }
    
     **注. nodiscard是C++17的内容
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值