Files
Obsidian-Main/02. PARA/03. Resources(資源)/C++17/Structured binding declaration.md
Awin Huang b9da824cf9 vault backup: 2022-07-06 20:43:32
Affected files:
02. PARA/03. Resources(資源)/C++17/Structured binding declaration.md
2022-07-06 20:43:32 +08:00

37 lines
861 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
Structured binding declaration 可以把對應的 tuple、pair、vector 展開,讓 code 更好讀。
## 展開 tuple
假設我們有一個 tuple
```cpp
std::tuple<std::string, uint32_t, uint32_t> person{ "John", 32, 170 };
auto& [name, age, tall] = person;
```
name 會是 "John"
age 是 32
tall 是 170
但比較好用的時候還是用來展開 function 的回傳值,假設我們有一個 function 會回傳 tuple
```cpp
std::tuple<std::string, uint32_t, uint32_t> getPersonData(uint32_t id) {
return std::make_tuple("John", 32, 170);
}
auto [name, age, tall] = getPersonData(id);
```
## 展開 array
`std::vector` 也是一樣的用法:
```cpp
#include <array>
std::array<int, 3> my_vec = { 5, 7, 10 };
auto& [num1, num2, num3] = my_vec;
```
或是:
```cpp
float rect[4]{ 5.0f, 6.0f, 120.0f, 200.0f };
auto& [x, y, w, h] = rect;
```