---
# System prepended metadata

title: C++ Common Usage for Leetcode

---

# C++ Common Usage for Leetcode

## [Map](https://shengyu7697.github.io/std-map)
- map的實做方式會用red-black-tree實做，可以保證在 O(log n)時間內完成搜尋插入刪除等等。

### 常用功能

### Example 
- 初始化
1. 直接insert
```c++
std::map<int, std::string> studentMap;
studentMap.insert(std::pair<int, std::string>(1, "Tom"));
studentMap.insert(std::pair<int, std::string>(7, "Jack"));
studentMap.insert(std::pair<int, std::string>(15, "John"));
```
2. 使用陣列
```c++
std::map<int, std::string> studentMap;
studentMap[1] = "Tom";
studentMap[7] = "Jack";
studentMap[15] = "John";
```
3. or 
```c++
std::map<int, std::string> studentMap = {
    {1, "Tom"},
    {2, "Jack"},
    {3, "John"}
};
```

- 插入東東
1. 你可以直接給值 （直接覆蓋）
```c++
std::map<int, std::string> studentMap;
studentMap[1] = "Tom";
...
studentMap[1] = "John";
```
3. insert 函數（如果有的話會return flase）
```c++
#include <iostream>
#include <string>
#include <map>

int main() {
    std::map<int, std::string> studentMap;
    studentMap.insert(std::pair<int, std::string>(1, "Tom"));

    std::pair<std::map<int, std::string>::iterator, bool> retPair;
    retPair = studentMap.insert(std::pair<int, std::string>(1, "Tom"));  
    
    if (retPair.second == true)
        std::cout << "Insert Successfully\n";
    else
        std::cout << "Insert Failure\n";

    return 0;
}
```
### Example
```c++
#include <iostream>
#include <string>
#include <map>

using namespace std;

int main(){

    //declaration container and iterator
    map<string, string> mapStudent;
    map<string, string>::iterator iter;
    map<string, string>::reverse_iterator iter_r;

    //insert element
    mapStudent.insert(pair<string, string>("r000", "student_zero"));

    mapStudent["r123"] = "student_first";
    mapStudent["r456"] = "student_second";

    //traversal
    for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
                cout<<iter->first<<" "<<iter->second<<endl;
    for(iter_r = mapStudent.rbegin(); iter_r != mapStudent.rend(); iter_r++)
                cout<<iter_r->first<<" "<<iter_r->second<<endl;

    //find and erase the element
    iter = mapStudent.find("r123");
    mapStudent.erase(iter);

    iter = mapStudent.find("r123");

    if(iter != mapStudent.end())
       cout<<"Find, the value is "<<iter->second<<endl;
    else
       cout<<"Do not Find"<<endl;

    return 0;
}
```

## [Vector](https://shengyu7697.github.io/std-vector/)
- 底層為一個連續的記憶體空間，容量不夠會重新申請空間

### 常用功能
- push_back: 把元素加到尾巴，必要的時候進行記憶體配置
- pop_back : 移除尾巴元素
- insert : 插入元素
- erase: 移除某個位置或是一段位置的元素
- clear :　清除所有
- empty : 回傳是否為空
- [i] : 拿東西
- at(i) : 拿東西，越界了拋出例外
- reverse() ： 預先配備大小

### Example
- 初始化

```c++
#include <vector>
using namspace std;
int main(){
    vector<int> v1;
    v1.push_back_back(1); #把1推進去
    v1 = {1,2,3,4,5};
    vector<int> v2;
    v2(v1.begin()+2, v1.end()-1); //3,4
    #移除尾巴
    v2.pop_back();
    # 遍歷整個 vector
    #1. 使用loop
    for(int i=0; i< vec1.size(); i++){
        cout << vec1[i] << " ";
    }
    #2. 使用
    for(auto it=vec.begin(); it != vec.end(); ++it){
        cout << *it << " ";
    }
    return 0;
}
```

- 尋訪
```c++
for(int i=0;i<v.size();i++){
    cout << v[i] <<  " ";
    or 
    cout << v.at(i) << " ";
}

vector<int>::iterator it_i;
for(it_i=ff.begin();it_i!-ff.end();+_+it_i){
    cout << (*it_i) <<endl;
}
```
- Construction and Assignment

```c++
int array[] = {0,1,2,3,4}
vector v(10,0); // {0,0,0,0,0,0,0,0,0}
vector v1;
vector v3(v.begin(), v.end());
v1.assign(v.begin(), v.end()); v1 複製到 v
v1.assign(v.begin(), v.begin()+5); 複製v前五個元素到v1
v1.assign(array, array+5); 複製 array前五個元素到v1
```

- define 2D array
```c++
#include<iostream>
#include<vector>
using namespace std;

int main(){
    vector <vector<int> > array(3); // 先有三個空間
    for (int i = 0; i<3; i++){
        array[i].resize(3); // 給每個元素再開三個空間
        for(int j =0; j<3; j++){
            cin >> array[i][j]; // 直接對開闢的空間給值
        }
    }
}
```

- 使用者定義的資料型態
```c++
class NODE{
    public:
        char symbol;
        int count;
};

int main(){

    NODE temp;
    vector<NODE> gem_list;
    
    tmp.symbol = 'a';
    tmp.count = 0;
    gem_list.push_back(temp);
}
```