结构化绑定

概述

结构化绑定是一个语法糖,它允许你从一个数组、结构体、元组或类似的拥有多个数据成员的对象中,一次性声明并初始化多个变量。这使得代码更简洁、更易读,特别是当你需要处理像 std::pairstd::tuple 这样的类型时。

注意

  • 结构化绑定的变量数量必须与表达式中的元素数量匹配
  • 结构化绑定的变量生命周期与绑定的对象相同
  • 结构化绑定的变量是表达式中对应元素的副本或引用
  • 结构化绑定不能用于类的私有成员,除非在类的成员函数内部
  • 结构化绑定不支持嵌套绑定
  • 必须使用 auto 关键字作为类型

例程

1
2
3
4
5
6
7
8
int arr[2] = { 1, 2 };
auto [x, y] = arr;
cout << x << ' ' << y << endl;
auto [m, n](arr);
cout << m << ' ' << n << endl;
auto [p, q]{arr};
cout << p << ' ' << q << endl;
return 0;

以上有三种初始化方式。

1
2
3
4
5
6
7
8
9
10
11
12
struct Point {
void func() {
auto [x1, y1] = *this;
cout << x1 << ' ' << y1 << endl;
}
double x;
double y;
};

Point p{ 1.1, 2.2 };
auto [x1, y1] = p;
cout << x1 << ' ' << y1 << endl;

也可以结构化绑定对象中的公有成员变量。

1
2
3
auto [[mm1, mm2], nn1] = std::make_tuple(p, 1); 
auto [m1, m2] = std::make_tuple(p, 1);
cout << m1.x << ' ' << m1.y << ' ' << m2 << endl;

不能嵌套结构化

1
2
3
4
5
std::map<std::string, int> m = { {"xxxx", 1}, {"yyyy", 2} };
for (const auto& [key, value] : m)
{
std::cout << key << ": " << value << "\n";
}

实践使用场景:范围 for 叠加结构化绑定使用遍历 map

1
2
3
4
5
6
std::tuple<int, double, std::string> t(1, 2.3, "hello");
auto [a1, b1, c1] = t;
auto& [a2, b2, c2] = t;
auto&& [a3, b3, c3] = move(t);
auto& [a4, b4] = std::make_tuple(1, 2);
auto&& [a5, b5] = std::make_tuple(1, 2);

只能绑定相同类型的引用。&&(万能转发)可以绑定左值引用或者右值引用。