首页 C++系列19:tuple与tie
文章
取消

C++系列19:tuple与tie

用于存储多个不同类型的值。它常用于需要将多个值组合在一起传递或返回的场景。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <tuple>
#include <string>

// 返回多个值的函数
std::tuple<int, double, std::string> getPersonInfo() {
return std::make_tuple(25, 180.5, "John Doe");
}

int main() {
auto personInfo = getPersonInfo();
int age;
double height;
std::string name;

// 解构 tuple
std::tie(age, height, name) = personInfo;

std::cout << "Age: " << age << ", Height: " << height << ", Name: " << name << std::endl;
return 0;
}

void printTuple(const std::tuple<int, double, std::string>& t) {
    std::cout << "Age: " << std::get<0>(t) << ", Height: " << std::get<1>(t) << ", Name: " << std::get<2>(t) << std::endl;
}

欢迎评论交流

本文由作者按照 CC BY 4.0 进行授权