除了用pair还能用啥
时间: 2024-02-28 08:57:49 浏览: 17
除了 `std::pair`,你还可以使用 C++11 引入的 `std::tuple` 来表示键值对。`std::tuple` 可以包含任意数量的元素,并且元素的类型可以不同。在 `std::map` 中,你可以使用 `std::tuple` 作为值类型,其中 `tuple` 的第一个元素是键,后面的元素是值。例如:
```cpp
#include <iostream>
#include <map>
#include <tuple>
int main()
{
std::map<int, std::tuple<std::string, double, int>> my_map;
my_map[1] = std::make_tuple("apple", 1.23, 10);
my_map[2] = std::make_tuple("banana", 2.34, 20);
my_map[3] = std::make_tuple("cherry", 3.45, 30);
for (const auto& item : my_map)
{
std::cout << item.first << ": " << std::get<0>(item.second) << ", " << std::get<1>(item.second) << ", " << std::get<2>(item.second) << std::endl;
}
return 0;
}
```
输出:
```
1: apple, 1.23, 10
2: banana, 2.34, 20
3: cherry, 3.45, 30
```
在这个例子中,`std::map` 的键是 `int` 类型,值是 `std::tuple<std::string, double, int>` 类型,其中 `tuple` 的第一个元素是 `std::string` 类型的水果名称,第二个元素是 `double` 类型的价格,第三个元素是 `int` 类型的库存数量。
相关推荐
![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)