std::pair 和 std::tuple
1. 元素个数
- std::pair: 固定包含两个元素。常用来在关联容器中表示键值对。
- std::pair<int, std::string> p = {1, “Alice”};
std::map<int, std::string> people; people.insert(std::make_pair(1, "Alice"));
- std::pair<int, std::string> p = {1, “Alice”};
- std::tuple: 包含任意数量的元素,存储多个不同类型的值。
std::tuple<int, std::string, double> t = {30, "Alice", 75.5};
2. 元素访问
- std::pair: 用 first 和 second 成员来获取值。
std::pair<int, std::string> p = {1, "Alice"}; int id = p.first; std::string name = p.second; - std::tuple: 通过 std::get
访问指定位置的元素,索引从 0 开始。 std::tuple<int, std::string, double> person = {30, "Alice", 75.5}; int age = std::get<0>(person); std::string name = std::get<1>(person); double weight = std::get<2>(person);
3. 类型推导与自动解构
- std::pair 和 std::tuple 都可以与 C++17 的结构化绑定配合使用,进行自动解构:
- std::pair:
std::pair<int, std::string> p = {1, "Alice"}; auto [id, name] = p; std::cout << "ID: " << id << ", Name: " << name << std::endl; - std::tuple:
std::tuple<int, std::string, double> person = {30, "Alice", 75.5}; auto [age, name, weight] = person;
- std::pair: