58 lines
1.4 KiB
Markdown
58 lines
1.4 KiB
Markdown
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;
|
||
```
|
||
|
||
但是不能用來展開 `std::vector`。
|
||
|
||
## 展開 pair
|
||
```cpp
|
||
std::pair<std::string, int32_t> name_phone{ "John", 912345678 };
|
||
auto& [name, phone_number] = name_phone;
|
||
```
|
||
|
||
用在 for-loop 裡也比較好懂,假設我們有一個 vector 用來存剛剛的姓名跟電話:
|
||
```cpp
|
||
std::vector<std::pair<std::string, uint32_t>> phoneBook = {
|
||
{ "John", 912345678 },
|
||
{ "Andy", 912345679 },
|
||
};
|
||
|
||
for (const auto& [name, phone] : phoneBook) {
|
||
std::cout << "Name: " << name << ", phone: " << phone << std::endl;
|
||
}
|
||
```
|