---
# System prepended metadata

title: Array v.s. Vector

---

# Array v.s. Vector

## 初始化

### 1D Array

```cpp
int a1[3] = {0};      // {0,0,0}
int a2[3] = {1};      // {1,0,0}
int a3[3] = {1,2,3};  // {1,2,3}
```

### 1D Vector
`vector<int> v(n, m)`: n 個 m

```cpp
vector<int> v1;           // {}
vector<int> v2(3);        // {0,0,0}
vector<int> v3(3,1);      // {1,1,1}
vector<int> v4({1,2,3});  // {1,2,3}  (c++11 only)
```

### 2D Array

```cpp
int aa1[2][3] = {0};  // {{0,0,0}, {0,0,0}}
int aa2[2][3] = {1};  // {{1,0,0}, {0,0,0}}
int aa3[2][3] = {{1,2,3}, {4,5,6}};  // {{1,2,3}, {4,5,6}}
```

### 2D Vector

```cpp
vector<vector<int> > vv1;     // {}
vector<vector<int> > vv2(2);  // {{}, {}}
vector<vector<int> > vv3(2, vector<int>(3));        // {{0,0,0}, {0,0,0}}
vector<vector<int> > vv4(2, vector<int>(3,1));      // {{1,1,1}, {1,1,1}}
vector<vector<int> > vv5(2, vector<int>({1,2,3}));  // {{1,2,3}, {1,2,3}}  (c++11 only)
vector<vector<int> > vv6({{1,2,3}, {4,5,6}});       // {{1,2,3}, {4,5,6}}  (c++11 only)
```

## Function

```cpp
void passArray(int arr[], int size) {}          // arr[size]
void passArrayByPointer(int* arr, int size) {}  // arr[size]
void passArray2D(int arr[][3], int size) {}     // arr[size][3]

void passVector(vector<int>& vec) {}
void passVector2D(vector<vector<int> >& vec) {}
```

## Vector 基本操作

- 讀取 element: `vec[i]`
- 長度: `vec.size()`
- 後面增加一個 element: `vec.push_back(element)`
- 刪除最後一個 element: `vec.pop_back()`


```cpp
#include <vector>
using namespace std;

vector<int> vec;   // {}

vec.push_back(3);  // {3}
vec.push_back(5);  // {3,5}
vec.pop_back();    // {3}

// iterate through vector
for (int i=0;i<vec.size();i++) {
    cout << vec[i] << " ";
}
```

## C++11 設定

- DevC++:
  請在 tools->complier options 的第一格 Add the following commands... 打勾
  並增加一行 `-std=c++11`
  
- Codeblocks:
  請在 setting->complier 勾第4個 (-std=c++11)
  