当前位置: 代码迷 >> 综合 >> c++ tuple 用法
  详细解决方案

c++ tuple 用法

热度:5   发布时间:2024-01-19 06:37:44.0

tuple 主要作用是可以省去临时结构体的定义,看起来也比较清爽。

比如想获取年月日,常规做法是定义一个结构体:

struct tm
{int tm_mday;  // day of the month - [1, 31]int tm_mon;   // months since January - [0, 11]int tm_year;  // years since 1900
};

但是,使用 tuple 可以简化

std::tuple<int, int, int> get_day()
{std::time_t t = std::time(0); std::tm* now = std::localtime(&t);return (std::tuple<int, int, int>(now->tm_year + 1900, now->tm_mon + 1, now->tm_mday) );
}// 使用的时候,只要:
auto d = get_day()// 获取值:
std::cout<<std::get<0>(d)<<"-"<<std::get<1>(d)<<"-"<<std::get<2>(d)<<std::endl;