struct
===
結構(struct)是一種使用者自定的型態,它可將不同的資料型態串在一起。
舉例來說,我們要記錄每個學生成績的三種資訊,國文成績,數學成績,和總分,我們可以這樣紀錄
``` cpp
int chinese[105], math[105], sum[105];
```
對於編號`i`的學生,他的國文,數學成績,以及總分,分別為
`chinese[i], math[i], sum[i]`
這樣的資料儲存方式太**散**了,這裡介紹另一種儲存方法
1. struct 創建基本架構
```cpp
struct 結構型態
{
欄項資料型態 欄項變數名稱;
欄項資料型態 欄項變數名稱;
欄項資料型態 欄項變數名稱;
: :
} [變數Ⅰ,變數Ⅱ……];
```
舉例
```cpp
struct Student {
int chinese;
int math;
int sum;
};
```
1. 第一行struct說明這是一個struct型態的東西
2. Student是這種結構型態的命名
3. 括號內的變數是指,對於這種結構,裡面存放了哪些資料
2. 宣告自訂結構型態
宣告一個屬於Student這個資料結構的變數
```cpp
Student student1;
\\ 資料型態 變數名稱
\\ 就像一班的變數宣告 int a;
```
也可以在這個時機點宣告
```cpp
struct Student {
...
} student1; // 宣告在這邊
```
3. 如何使用?
輸入student1的國文,數學成績,以及總分
`cin >> student1.chinese >> student1.math >> student1.sum;`
4. 初始化
```cpp
struct Point {
double a, b;
};
int main() {
Point p;
//一個一個賦予值
p.a = 13.2; p.b = 24.3;
//用大括號賦予值,第一個變數對應到struct裡的第一個變數(a)
//適用於很多個變數
p = (Point){19.0, 29.3};
p = {19.0, 29.3}; //c++11以上才可以用
}
```
```cpp
struct Point {
double a, b, c;
//使用建構子
Point(const double &a, const double &b) : a(a), b(b) {
//初始化同時加上其他操作
c = a + b;
}
};
int main() {
Point p(20.5, 70.1);
}
```
5. Pair
只用兩個變數的struct,可以用pair來取代,方便許多
```cpp
struct Point {
double first;
double second;
};
```
```cpp
pair<double, double> point;
point = {10.5, 23.4}; //c++11
cout << point.first << " " << point.second << endl;
```
競賽中常把first和second替換掉
```cpp
#define X first
#define Y second
```
這樣就方便多啦
```cpp
point.X = point.X * 10 + point.Y * 20;
cout << point.X << " " << point.Y << endl;
```
6. 用pair走訪map
```cpp
map<int, string> mp = {{12, "Hello"}, {203, "fun"}, {29, "CHSH"}};
for(pair<int, string> cur : mp) // 或寫成for(auto cur : mp)
cout << cur.first << " " << cur.second << endl;
```