1.4 KiB
1.4 KiB
Structured binding declaration 可以把對應的 tuple、pair、vector 展開,讓 code 更好讀。
展開 tuple
假設我們有一個 tuple:
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:
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 也是一樣的用法:
#include <array>
std::array<int, 3> my_vec = { 5, 7, 10 };
auto& [num1, num2, num3] = my_vec;
或是:
float rect[4]{ 5.0f, 6.0f, 120.0f, 200.0f };
auto& [x, y, w, h] = rect;
但是不能用來展開 std::vector。
展開 pair
std::pair<std::string, int32_t> name_phone{ "John", 912345678 };
auto& [name, phone_number] = name_phone;
用在 for-loop 裡也比較好懂,假設我們有一個 vector 用來存剛剛的姓名跟電話:
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;
}