基础介绍
该特性于c++17版本引入。通俗的理解该特性与python中的解包功能有点类似。通过这个特性可以对哪些数据组合进行解包呢?请看下面的列表:
- 一些c++基本的数据类型进行解包,例如std::pair std::map等,
- 函数返回值也可以实现解包
- 数组
- 自定义类型解包
解包后的返回值类型是通过auto关键字推导得出的。结构化绑定的使用形式一般是:
auto [变量1, 变量2,变量3...] = 函数/基本是数据类型(pair/map等)/数组/自定义类型
基本的使用方法如下所示:
void basic_structured_bindings() {
// 1. 基本用法
std::pair<int, std::string> pair = {1, "hello"};
auto [id, name] = pair; // 解构pair
// 2. 用于函数返回值
auto [ptr, ec] = std::to_chars(/*...*/); // 解构to_chars_result
// 3. 用于数组
int array[3] = {1, 2, 3};
auto [x, y, z] = array; // 解构数组
// 4. 用于结构体
struct Point {
int x;
int y;
};
Point p{10, 20};
auto [px, py] = p; // 解构结构体
}
解包后获取的值方式也是有多种,种类如下:
- 值拷贝
- 值引用
- const 引用
- 右值引用
通过结构化绑定后特性解包后的数据也有如上几种方式:
void reference_types() {
std::pair<int, std::string> pair = {1, "hello"};
// 1. 值拷贝方式
auto [id1, name1] = pair;
// 2. 值引用方式
auto& [id2, name2] = pair;
// 3. const引用
const auto& [id3, name3] = pair;
// 4. 右值引用
auto&& [id4, name4] = std::make_pair(1, "hello");
}
常见的应用场景
// 1. 遍历map
void iterate_map() {
std::map<std::string, int> scores{
{"Alice", 95}, {"Bob", 87}};
for (const auto& [name, score] : scores) {
std::cout << name << ": " <<