赞
踩
std::tuple是一个固定大小的不同类型值的集合,是泛化的std::pair。和c#中的tuple类似,但是比c#中的tuple强大得多。我们也可以把他当做一个通用的结构体来用,不需要创建结构体又获取结构体的特征,在某些情况下可以取代结构体使程序更简洁,直观。
样例:
- // std::tuple
- class CTuple
- {
- public:
- CTuple() {}
- ~CTuple() {}
- void Run();
- private:
- };
- // 元组使用
- void CTuple::Run()
- {
- //创建tuple
- //auto t1 = make_tuple(1, "a1", "b1", "c1");
- std::tuple<int,string,string,string> t1 = std::make_tuple(1, "China", "中国", "北京");
- cout << get<0>(t1) << " "; //取值
- cout << get<1>(t1) << " ";
- cout << get<2>(t1) << " ";
- cout << get<3>(t1) << " ";
- cout << endl;
-
- std::vector<tuple<int, string, string, string> > tv;
- tv.push_back(t1);
- tv.push_back(std::make_tuple(2, "ShanXI", "陕西", "西安"));
- tv.push_back(std::make_tuple(3, "SiChuan", "四川", "成都"));
- for (auto iter = tv.begin(); iter != tv.end(); iter++)
- {
- cout << get<0>(*iter) << " ";
- cout << get<1>(*iter) << " ";
- cout << get<2>(*iter) << " ";
- cout << get<3>(*iter) << endl;
- }
-
- // 解析tuple
- std::tuple<int, string, string, string> t3(10, "ShanXi", "山西", "太原");
- int nID;
- std::string strName1;
- std::string strName2;
- std::string strName3;
- std::tie(nID, strName1, strName2, strName3) = t3; //则自动赋值到三个变量也可以只解析第三个值:
- std::tie(std::ignore, std::ignore, std::ignore, strName3) = t3; //std::ignore为占位符
- cout << "解析tuple:" << strName3 << endl;
- }
调用:
- int main()
- {
- //测试std::tuple
- std::shared_ptr<CTuple> pTuple = std::make_shared<CTuple>();
- pTuple->Run();
- return 0;
- }
运行结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。