---
# System prepended metadata

title: '【程式】C++函式 `std::find()`'
tags: [筆記, 學習, 程式]

---

# 【程式】C++函式 `std::find()`

## 前言
每次在刷LeetCode常常需要用到find()函式，但每次用每次都不熟悉，已經造訪別人的網站無數次了還是記不起來，所以只好先篇筆記讓自己銘記在心了。
這篇筆記我也只舉我自己最常用的情況，就是**find()搭配STL中的vector容器**

---

## Syntax
要先在標頭檔中加上 **`#include <algorithm>`**
```cpp=
InputIterator find (InputIterator first, InputIterator last, const T& val)
```
find()函式裡面要放的參數是 **(iterator的頭, iterator的尾, 要找到目標)** 
然後回傳 => if(找到) return (找到的iterator位址) else return (iterator的尾)

---

## 範例
it是一個迭代器，要得到值的話，必須要用**取值運算子(*)** => `*it`
用另一個函數`std::distance(v.begin(), it)`得到目標的index值
也可以用`it-v.begin()`代替
```cpp=
int main() {
    vector<int> v = {23,76,34,9,31,5};

    vector<int>::iterator it = std::find(v.begin(), v.end(), 34); // find 34
    if (it != v.end()){
        cout << "found: " << *it << endl;
        cout << "index: " << std::distance(v.begin(), it) << endl;
    }
    else{
        cout << "not found" << endl;
    }
    return 0;
}
```
如果想要遍歷目標之後所有的值可以用for迴圈
```cpp=
for (auto i = it; i != v.end() ;i++){
    cout << *i << " ";
}
```

---

## 統整
1. `#include <algorithm>`
2. `vector<int>::iterator it = std::find(v.begin(), v.end(), target);`
3. `*it` 取值
4. `it-v.begin()`或`std::distance(v.begin(), it)` 取索引值

---

## 參考
1. [Cpp Reference](https://cplusplus.com/reference/algorithm/find/)
2. [C++ std::find 搜尋用法與範例｜ShengYu Talk](https://shengyu7697.github.io/std-find/)
###### tags: `程式` `學習` `筆記`