当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ std::find()用法及代码示例


find() 作为 STL 函数

find() 是一个 STL 函数,它位于 <algorithm> 头文件下,它返回一个迭代器,指向范围内搜索元素的第一次出现。

用法:

InputIterator find(
    InputIterator first, 
    InputIterator last, 
    const T& val);

其中,

  • InputIterator first- 搜索范围开始的迭代器
  • InputIterator last- 到搜索范围结束的迭代器
  • const T& val- 要搜索的数据类型 T 的值

什么是输入迭代器?
迭代器到我们找到搜索元素的范围的第一个位置。如果未找到搜索元素,则将迭代器返回到末尾

返回类型: bool

无论是否找到搜索元素,都使用上述语法搜索相应范围内的元素。

时间复杂度:线性时间,O(n)

之间的区别binary_search()和 find() 函数

  • std::binary_search() 函数返回布尔值,告诉它是否找到。它不会返回位置。但是,std::find() 也搜索位置。它返回一个迭代器到第一个位置。
  • std::binary_search() 在 O(logn) 时间内搜索是否 std::find() 在线性时间内搜索。

范例1:当搜索到的元素被找到并且在搜索范围内只有一个实例时

#include <bits/stdc++.h>
using namespace std;

int main()
{
    vector<int> arr{ 1, 2, 3, 8, 4, 3 };

    int searching_element = 8;
    vector<int>::iterator it;
    //starting iterator of range= arr.begin()
    //end iterator of range =arr.end()

    it = find(arr.begin(), arr.end(), searching_element);
    if (it != arr.end())
        cout << searching_element << " is at position:" << it - arr.begin() << endl;
    else
        cout << searching_element << "not found";

    return 0;
}

输出:

8 is at position:3

在上面的程序中,我们检查了搜索元素,发现它在3rd索引(0-索引)

范例2:当搜索到的元素被找到并且在搜索范围内有多个实例时

#include <bits/stdc++.h>
using namespace std;

int main()
{
    vector<int> arr{ 1, 2, 3, 8, 4, 3 };

    int searching_element = 3;
    vector<int>::iterator it;
    //starting iterator of range= arr.begin()
    //end iterator of range =arr.end()

    it = find(arr.begin(), arr.end(), searching_element);
    if (it != arr.end())
        cout << searching_element << " is at position:" << it - arr.begin() << endl;
    else
        cout << searching_element << "not found";

    return 0;
}

输出:

3 is at position:2 

在上面的例子中,我们在数组中搜索 3,该数组有两个实例,一个在位置索引 2,另一个在位置 5。由于 std::find()在找到搜索元素时停止搜索,因此它返回索引 2(检查我们如何找到它返回的迭代器的位置)。

范例3:当在搜索范围内未找到搜索元素时

#include <bits/stdc++.h>
using namespace std;

int main()
{
    vector<int> arr{ 1, 2, 3, 8, 4, 3 };

    int searching_element = 7;
    vector<int>::iterator it;
    //starting iterator of range= arr.begin()
    //end iterator of range =arr.end()
 
    it = find(arr.begin(), arr.end(), searching_element);
    if (it != arr.end())
        cout << searching_element << " is at position:" << it - arr.begin() << endl;
    else
        cout << searching_element << " not found";

    return 0;
}

输出:

7 not found

在上述情况下,搜索元素不存在,这就是它返回 arr.end() 的原因,这意味着迭代器到范围的末尾。



相关用法


注:本文由纯净天空筛选整理自 std::find() with examples in C++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。