当前位置:   article > 正文

C++11——std::tuple_std::tuple取值

std::tuple取值

std::tuple是一个固定大小的不同类型值的集合,是泛化的std::pair。和c#中的tuple类似,但是比c#中的tuple强大得多。我们也可以把他当做一个通用的结构体来用,不需要创建结构体又获取结构体的特征,在某些情况下可以取代结构体使程序更简洁,直观。

样例:

  1. // std::tuple
  2. class CTuple
  3. {
  4. public:
  5. CTuple() {}
  6. ~CTuple() {}
  7. void Run();
  8. private:
  9. };
  1. // 元组使用
  2. void CTuple::Run()
  3. {
  4. //创建tuple
  5. //auto t1 = make_tuple(1, "a1", "b1", "c1");
  6. std::tuple<int,string,string,string> t1 = std::make_tuple(1, "China", "中国", "北京");
  7. cout << get<0>(t1) << " "; //取值
  8. cout << get<1>(t1) << " ";
  9. cout << get<2>(t1) << " ";
  10. cout << get<3>(t1) << " ";
  11. cout << endl;
  12. std::vector<tuple<int, string, string, string> > tv;
  13. tv.push_back(t1);
  14. tv.push_back(std::make_tuple(2, "ShanXI", "陕西", "西安"));
  15. tv.push_back(std::make_tuple(3, "SiChuan", "四川", "成都"));
  16. for (auto iter = tv.begin(); iter != tv.end(); iter++)
  17. {
  18. cout << get<0>(*iter) << " ";
  19. cout << get<1>(*iter) << " ";
  20. cout << get<2>(*iter) << " ";
  21. cout << get<3>(*iter) << endl;
  22. }
  23. // 解析tuple
  24. std::tuple<int, string, string, string> t3(10, "ShanXi", "山西", "太原");
  25. int nID;
  26. std::string strName1;
  27. std::string strName2;
  28. std::string strName3;
  29. std::tie(nID, strName1, strName2, strName3) = t3; //则自动赋值到三个变量也可以只解析第三个值:
  30. std::tie(std::ignore, std::ignore, std::ignore, strName3) = t3; //std::ignore为占位符
  31. cout << "解析tuple:" << strName3 << endl;
  32. }

调用:

  1. int main()
  2. {
  3. //测试std::tuple
  4. std::shared_ptr<CTuple> pTuple = std::make_shared<CTuple>();
  5. pTuple->Run();
  6. return 0;
  7. }

运行结果:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/305954
推荐阅读
相关标签
  

闽ICP备14008679号