C++中的tuple
时间: 2023-12-07 10:40:01 浏览: 28
C++中的tuple是一个固定大小的不同类型元素的集合,类似于结构体,但是tuple的元素可以是不同的类型。可以使用std::make_tuple()函数创建一个tuple对象,也可以使用std::get()函数获取tuple对象中的元素。以下是一个创建和使用tuple的例子:
```c++
#include <iostream>
#include <tuple>
#include <string>
int main() {
// 创建一个tuple对象
std::tuple<int, std::string, double> mytuple(10, "hello", 3.14);
// 获取tuple对象中的元素
int myint = std::get<0>(mytuple);
std::string mystr = std::get<1>(mytuple);
double mydouble = std::get<2>(mytuple);
// 输出元素
std::cout << "myint = " << myint << std::endl;
std::cout << "mystr = " << mystr << std::endl;
std::cout << "mydouble = " << mydouble << std::endl;
// 修改元素
std::get<0>(mytuple) = 20;
std::get<1>(mytuple) = "world";
std::get<2>(mytuple) = 6.28;
// 输出修改后的元素
std::cout << "myint = " << std::get<0>(mytuple) << std::endl;
std::cout << "mystr = " << std::get<1>(mytuple) << std::endl;
std::cout << "mydouble = " << std::get<2>(mytuple) << std::endl;
return 0;
}
```
输出结果为:
```
myint = 10
mystr = hello
mydouble = 3.14
myint = 20
mystr = world
mydouble = 6.28
```