C++2.0中引入了tuple类型,该类型的引入,该类型的引入使得开发人员不需要定义结构体,就可以在一个对象中存储不同的数据类型,极大的方便了代码编写,举例代码如下:
void TestTuple()
{
tuple<int, int, float, string> tp(1, 2, 3.1, "全世界");
cout << "第一个元素为:" << get<0>(tp) << endl;
cout << "第二个元素为:" << get<1>(tp) << endl;
cout << "第三个元素为:" << get<2>(tp) << endl;
cout << "第四个元素为:" << get<3>(tp).c_str() << endl;
vector<tuple<vector<string>, bool, string>> vecDeal;
vector<string> vecFile;
vecFile.push_back("123");
vecFile.push_back("456");
vecFile.push_back("789");
vecDeal.push_back(make_tuple(vecFile, true, "刘德华"));
vecDeal.push_back(make_tuple(vecFile, true, "刘德华"));
vecDeal.push_back(make_tuple(vecFile, true, "刘德华"));
//获取tupple中元素的个数
std::tuple<int, char, double> mytuple(10, 'a', 3.14);
std::cout << std::tuple_size<decltype(mytuple)>::value << endl;;
// make_tuple: 组包 tie: 解包
std::tuple<std::string, int, std::string, int> tp1;
tp1 = std::make_tuple("Sven", 25, "Shanghai", 21);
// 定义接收变量
std::string name;
std::string addr;
int ages;
int areaCode;
std::tie(name, ages, addr, areaCode) = tp1;
//修改其中某个元素
get<0>(tp1) = "hello world";
int iSize = std::tuple_size<decltype(tp1)>::value;
for (int i = 0; i < iSize; i++)
cout << i << " " << get<0>(tp1).c_str() << endl;
// 将一个DWORD中的每个字节数据存放在tupple中
DWORD dwData = 0x10111213;
iSize = sizeof(dwData);
tuple<int, vector<int>> tp2;
get<0>(tp2) = 110;
for (int i = 0; i < iSize; i++)
get<1>(tp2).push_back(((dwData >> (i) * 8) & 0xFF));
for (auto & item : get<1>(tp2))
cout << item << endl;
}
运行效果如下: