#include <iostream>
#include <tuple>
// 使用tuple容器构造一个元组,可以返回多个值,返回值需要事先知道有多少个元素并各自对应的数据类型
std::tuple<int, double, std::string> f() {
return std::make_tuple(1, 2.3, "456");
}
void test1(){
std::tuple<int, double, std::string> t{1,2.1,"c++"};
int i;
double d;
std::string s;
std::tie(i,d,s) = t;
// 可以使用tie进行解包,但是必须知道tuple数量以及对应类型
std::cout<<i<<","<<d<<","<<s<<std::endl;
}
void test2(){
// 引进结构化绑定,使用auto自动推导
auto [x, y, z] = f();
std::cout << x << ", " << y << ", " << z << std::endl;
}
int main() {
test1();
test2();
return 0;
}
C++新特性tuple
于 2021-09-12 14:28:34 首次发布