# C++ 語法細節
---
# 常用語法
----
```cpp!
signed main(){
for (操作一;條件;操作二)
// 條件符合繼續執行
// 回圈開始前進行操作一
// 每輪結束進行操作二
// 操作內不能放分號
}
```
----
```cpp!
#define int long long
typedef long long ll;
const int N = 1e5+5;
signed main(){
#define f(a,b) a*x+b
int x = 10,y=20;
cout << f(2,1) * f(1,2);
// define 直接複製貼上 2*10+1*1*10+2不是21*12
// define 當函式用要將輸入輸出加括號
#define f(a,b) ((a)*x+(b))
int a = x > y ? 10 : 20 + 3;
if (x>y) a = 10;
else a=23;
}
```
----
初始化陣列
```cpp!
#define INF 0x3f3f3f3f
int ar[100];
signed main(){
fill(ar,ar+n,INF);
memset(ar,INF,sizeof(ar));
memset(ar,INF, n << 2);
//一個char為單位初始化,不能初始是1
vector<int> br(n,vl);
br.resize(n*2,3); //超出部分補3
br.assign(n*2,4); //全部變4
iota(ar,ar+50,0); // ar[i]=i,升序初始化
}
```
---
# 指標與參考
----
```cpp!
int *a,**b,*ar;
int _ar[201]
signed main(){
ar = _ar + 100;
a = new int[10];
b = new int*[10];
for (int i=0;i<10;i++)b[i] = new int [10];
}
```
----
```cpp!
void f(vector<int> &ar,const string &s){}
//避免陣列複製一份
signed main(){
int x=10;
int &y=x;
y = 20; //x 也會變成20,避免動到可以用const
int *a;
int *&b=a;
b = new int[10];// a被開了10格
}
```
---
# struct & operator
----
```cpp!
struct P{
int u=10,v=20;
int a,b;
P *ch
P():a(10),b(20){}
P(int _a,int _b):a(_a),b(_b){}
P(int k){
if (k==0){
a=b=0;
}
else {
ch = new P(k-1);
a=ch->a+ch->b;
b=ch->a-ch->b;
}
}
bool operator<(const P &rh)const {return u<rh.u}
int operator()(int x){return a*x+b;}
P operator+(const P &rh)const {return P(a+rh.a,b+rh.b);}
void operator+=(const P &rh){a+=rh.a,b+=rh.b;}
}ar[100];
P b[100];
```
----
```cpp!
#define F first
#define S second
typedef pair<int,int> pii;
pii operator+(const pii &a,const pii &b){
return make_pair(a.F+b.F,a.S+b.S);
}
int operator*(const pii &a,const pii &b){
return a.F*b.F+a.S*b.S;
}
pii operator*(const pii &a,const int r){
return make_pair(a.F*r,a.S*r);
}
ostream& operator<<(ostream &os,const pii &a){
return os<<'('<<a.F<<','<<a.S<<')';
}
signed main(){
pii tp={3,5};
cout<<(tp*5);
}
```
---
# 匿名函式
----
```cpp!
#define iter(a) (a).begin(),(a).end()
#define pb emplace_back
int w[100];
bool cmp(int a,int b){return w[a]<w[b];}
signed main(){
vector<int> od(n);
iota(iter(od),0);
sort(iter(od),cmp);
sort(iter(od),[&](const int &a,const int &b){
return w[a]>w[b]; }) //1代表a前b後是正確排序
}
```
----
函式裡定義函式
```cpp!
int sz[100],f[100];
vector<int> eg[100];
signed main()
{
int x = 10,n; //好處:可以用區域變數
function<int(int, int)> f = [&](int a, int b)
{
return a * x + b;
};
auto ff = [&](int a, int b) -> int
{
return a * x + b;
};
auto dfs = [&](int u,int fa)->void
{
sz[u]=1;
for (const int v:eg[u])
if (v!=fa)
sz[u]+=sz[v];
f[u]=n-sz[u];
};
cout << ff(3, 2);
}
```
{"title":"C++ 語法細節","description":"位元運算:對數字的二進位操作","contributors":"[{\"id\":\"33757841-f501-406f-a770-4a908423f414\",\"add\":3165,\"del\":135}]"}