设为首页 加入收藏

TOP

C++11 新特性之 tuple
2015-07-24 05:57:15 来源: 作者: 【 】 浏览:6
Tags:特性 tuple

我们在C++中都用过pair.pair是一种模板类型,其中包含两个数据值,两个数据的类型可以不同.pair可以使用make_pair构造

pair
  
    p = make_pair(1, "a1");
  

如果传入的参数为多个,那么就需要嵌套pair,如下代码


#include 
  
   
#include 
    using namespace std; int main() { //
    
      ,注意:在嵌套模板实参列表中应当使用‘> >’而非‘>>’ map
     
       > > m; map
      
        temp1; temp1.insert(make_pair("b1", "c1")); map
       
         > temp2; temp2.insert(make_pair("a1", temp1)); m.insert(make_pair(1, temp2)); map
        
          temp3; temp3.insert(make_pair("b2", "c2")); map
         
           > temp4; temp4.insert(make_pair("a2", temp3)); m.insert(make_pair(2, temp4)); //遍历 map
          
            > >::const_iterator itr1; map
           
             >::const_iterator itr2; map
            
             ::const_iterator itr3; for (itr1=m.begin(); itr1!=m.end(); itr1++) { cout << itr1->first << " "; itr2 = (itr1->second).begin(); cout << itr2->first << " "; itr3 = (itr2->second).begin(); cout << itr3->first << " "; cout << itr3->second << endl; } pair
             
               p = make_pair(1, "a1"); return 0; }
             
            
           
          
         
        
       
      
     
    
  

上面的做法明显很麻烦,在C++11中引入了变长参数模板,所以发明了新的数据类型:tuple,tuple是一个N元组,可以传入1个, 2个甚至多个不同类型的数据,避免了嵌套pair的丑陋做法,通过make_tuple()创建元组,通过get<>()来访问元组的元素

#include 
  
   
#include 
   
     #include 
    
      using namespace std; int main() { auto t1 = make_tuple(1, "a1", "b1", "c1"); cout << get<0>(t1) << " "; cout << get<1>(t1) << " "; cout << get<2>(t1) << " "; cout << get<3>(t1) << " "; cout << endl; vector
     
       > tv; tv.push_back(make_tuple(1, "a1", "b1", "c1")); tv.push_back(make_tuple(2, "a2", "b2", "c2")); vector
      
        >::iterator itr; for (itr=tv.begin(); itr!=tv.end(); itr++) { cout << get<0>(*itr) << " "; cout << get<1>(*itr) << " "; cout << get<2>(*itr) << " "; cout << get<3>(*itr) << endl; } return 0; }
      
     
    
   
  



】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇SRM 620 D2L3: RandomGraph, dp 下一篇Longest Common Prefix

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: