# struct、STL(1)
## 11/3 社課
---
# struct
----
### 什麼是 struct?
- 自己定義的新資料型態
- 把不同資料型態(變數)綁在一起
----
### 建立結構
```cpp=
struct st{
int x, y;
char c;
string s;
};
```
在這裡 st 是一個新的資料結構
就像 int, double 一樣
#### 要注意大括號後要加分號
----
### 宣告結構變數
```cpp=
struct st{
int x, y;
char c;
string s;
} a;
st b={1, 0, 'a', "Hi"};
```
----
### 結構變數賦值與取值
```cpp=
struct st{
int x, y;
char c;
string s;
} a;
a.x=1;
a.y=50;
cout << a.x+a.y;
```
----
### 自定義運算子
```cpp=
struct st{
int x, y;
bool operator <(st tmp){
return x<tmp.x;
}
st operator +(st tmp){
return {x+tmp.x, y+tmp.y};
}
}
```
----
通常會用在一個東西有很多資料
像座標 $(x, y, z)$ 等
---
# STL
----
### 標準函式庫(模板庫)
Standard Template Library
簡稱 STL
裡面有很多已經寫好的 function 或 container 等
---
## [cmath](https://cplusplus.com/reference/cmath/)
----
### 常用的
- pow(a, b)、sqrt(a)
- sin(a)、cos(a)、tan(a)
- log(a)、log10(a)
以上都是回傳 double
---
## pair、tuple
----
- pair - \<utility>
- tuple - \<tuple>
----
### 語法
```cpp=
pair<type_1, type_2> name_1;
tuple<T1, T2, T3, T4> name_2;
```
----
### 賦值方法
```cpp=
pair<int, int> p;
tuple<int, int, int> t;
// 方法1
p.first=1, p.second=2; // p=(1, 2)
get<0>(t)=1, get<1>(t)=2, get<2>(t)=3; // t=(1, 2, 3)
// 方法2
p={1, 2};
t={1, 2, 3};
// 方法3
p=make_pair(1, 2);
t=make_tuple(1, 2, 3);
```
----
比較大小時預設為先比前面再比後面
---
## vector
----
靜態陣列(大小不能變)
```cpp=
int arr[10];
```
動態陣列(大小可以變)
```cpp=
vector<int> v;
```
----
### 宣告
```cpp=
vector<int> v1;
vector<int> v2(10, 100); // 宣告大小為 10,每格都為 100
vector<vector<int>> v3; // 二維 vector
vector<vector<int>> v4(10, vector<int>());
```
----
### 賦值、插入與刪除
```cpp=
vector<int> v(10);
v[3]=10;
v.push_back(15); // 在陣列最後面多放進一個數
v.pop_back(); // 把陣列最後面的數刪掉
// 以下操作都很慢,盡量不要使用
v.insert(v.begin()+k, a); // 把a插入第k個元素
v.erase(v.begin()+k) // 刪除第k個元素
```
----
### 其他東西
```cpp=
v.size() // 回傳陣列大小
v.clear() // 清空陣列
v.resize(a, b) // 把陣列長度變成a,如果比原本長度長,就把新的都填上b
v.assign(a, b) // 把陣列長度變成a,把所有元素改為b
```
----
### sort
```cpp=
sort(v.begin(), v.end(), cmp);
```
---
## deque
----
類似於 vector
但可以在頭尾插入刪除
```cpp=
deque<int> dq;
dq.push_back(1);
dq.pop_back();
dq.push_front(2);
dq.pop_front();
```
----
優點:可以支持頭尾操作
缺點:比 vector 慢
---
可以把以前的陣列題用 vector 寫寫看
{"description":"","contributors":"[{\"id\":\"1a0296c8-ce58-4742-acda-22c02ae81a74\",\"add\":2262,\"del\":2}]","title":"11/03 C++社課"}