C++ tuple用法
时间: 2024-02-15 07:00:23 浏览: 59
C++中的tuple是一个固定大小的、异构的、不可变的数据结构,可以存储多个不同类型的值。下面是两个关于C++ tuple的例子:
1. 使用tuple存储不同类型的值
```cpp
#include <iostream>
#include <tuple>
#include <string>
int main() {
std::tuple<int, std::string, double> myTuple(10, "Hello", 3.14);
int intValue = std::get<0>(myTuple);
std::string stringValue = std::get<1>(myTuple);
double doubleValue = std::get<2>(myTuple);
std::cout << "Int value: " << intValue << std::endl;
std::cout << "String value: " << stringValue << std::endl;
std::cout << "Double value: " << doubleValue << std::endl;
return 0;
}
```
2. 使用tuple进行类型检查
```cpp
#include <iostream>
#include <tuple>
#include <type_traits>
int main() {
std::tuple<int, double, std::string> myTuple(10, 3.14, "Hello");
static_assert(std::is_same_v<std::tuple_element_t<0, decltype(myTuple)>, int>);
static_assert(std::is_same_v<std::tuple_element_t<1, decltype(myTuple)>, double>);
static_assert(std::is_same_v<std::tuple_element_t<2, decltype(myTuple)>, std::string>);
std::cout << "Type check passed!" << std::endl;
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)