情境
當我們在寫 python 時,可以看到以下這種方便的寫法, 可以直接拿到 x,y ,而不用先寫個變數去接函數回傳,再分別取出 x, y
1
2
3
4
5
6
# Multiple return values unpacking
def get_coordinates():
return (10, 20)
x, y = get_coordinates()
print(f"x: {x}, y: {y}")
C++17 也可以做到這點了。
C++17 引入了結構化綁定(structured bindings),這是一種新語法,允許我們將元組、結構或陣列等複合型別的成員分解並綁定到獨立的變量上,使代碼更加簡潔和易讀。
語法 結構化綁定的基本語法如下:
1
auto [var1, var2, ..., varN] = expression;
Tuple 例子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <tuple>
std::tuple<int, int, std::string> getPerson() {
return { 35, 35, "KD" };
}
int main() {
auto [age, number, name] = getPerson();
std::cout << "Age: " << age << '\n';
std::cout << "Number: " << number << '\n';
std::cout << "Name: " << name << '\n';
return 0;
}
結構例子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
struct Person {
int age;
int number;
std::string name;
};
int main() {
Person person = {39, 23, "LBJ"};
auto [age, number, name] = person;
std::cout << "Age: " << age << '\n';
std::cout << "Number: " << number << '\n';
std::cout << "Name: " << name << '\n';
return 0;
}
陣列例子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
int main() {
int arr[3] = {1, 2, 3};
auto [a, b, c] = arr;
std::cout << "a: " << a << '\n';
std::cout << "b: " << b << '\n';
std::cout << "c: " << c << '\n';
return 0;
}
好處
提高代碼可讀性:結構化綁定可以使代碼更簡潔、更易讀,特別是在處理複合型別時。
簡化變量聲明:當需要從返回多個值的函數中提取值時,結構化綁定可以避免多次變量聲明,簡化代碼。
