以下是小可关于tuple的理解有不对之处希望大家指正
tuple简单测试
tuple和struct的功能类似,它是以std::get<0>(pos)方式取值它不限变量个数
测试代码
#include <algorithm>
#include <map>
int main()
{
std::cout << "------------tuple test ----------\n";
std::tuple<int, int, int> pos;
pos = std::make_tuple(100, 110, 120);
std::cout << "tuple_size " << std::tuple_size<decltype(pos)>::value << "\n";
std::cout << std::get<0>(pos) << " " << std::get<1>(pos) << " " << std::get<2>(pos) << " \n";
std::cout << "------------tuple vector test ----------\n";
std::vector<std::tuple<int, float, double>> tupVec;
typedef decltype(std::vector<std::tuple<int, float, double>>::value_type()) tupVecType;
for (int i = 0; i < 3; i++)
tupVec.push_back(tupVecType(i * 1, i * 10, i * 100));
std::cout << "------------for test ----------\n";
for (int i = 0; i < 3; i++)
std::cout << std::get<0>(tupVec[i]) << " " << std::get<1>(tupVec[i]) << " " << std::get<2>(tupVec[i]) << "\n";
std::cout << "------------std::for_each test ----------\n";
std::for_each(tupVec.begin(), tupVec.end(), [&](tupVecType var) {
std::cout << std::get<0>(var) <<" "<< std::get<1>(var) << " " << std::get<2>(var) << "\n";
});
std::cout << "------------new for test ----------\n";
for (tupVecType var:tupVec)
{
std::cout << std::get<0>(var) << " " << std::get<1>(var) << " " << std::get<2>(var) << "\n";
}
std::cout << "------------tuple map test ----------\n";
std::map<std::string, std::tuple<int, float, double>> tupMap;
for (int i = 0; i < 3; i++)
tupMap.insert(std::pair<std::string, std::tuple<int, float, double>>(std::string("test")+std::to_string(i), tupVecType(i * 1, i * 10, i * 100)));
for (auto& var: tupMap)
{
std::cout <<var.first <<" "<< std::get<0>(var.second) << " " << std::get<1>(var.second) << " " << std::get<2>(var.second) << "\n";
}
system("pause");
return 0;
}
结果如下
------------tuple test ----------
tuple_size 3
100 110 120
------------tuple vector test ----------
------------for test ----------
0 0 0
1 10 100
2 20 200
------------std::for_each test ----------
0 0 0
1 10 100
2 20 200
------------new for test ----------
0 0 0
1 10 100
2 20 200
------------tuple map test ----------
test0 0 0 0
test1 1 10 100
test2 2 20 200
请按任意键继续. .