【C++】C++中的find与find_if函数

目录

    • 一、find
      • 1.1 在 vector 中查询
      • 1.2 在 string 中查询
    • 二、find_if

在C++编程语言中, find()find_if() 函数都可以用来在容器中查找指定元素,但它们有一些区别

一、find

find 函数用于查找容器中第一个等于指定值的元素,并返回指向该元素的迭代器。如果在容器中找不到指定值,则返回指向容器末尾的迭代器。

1.1 在 vector 中查询

例如,下面的代码使用 find 函数在 vector 容器中查找值为 42 的元素:

#include 
#include 
#include 
using namespace std;

int main()
{
    vector<int> v = {1, 2, 3, 42, 5, 6};
    
    auto it = find(v.begin(), v.end(), 42);
    
    if (it != v.end())
        cout << "Found " << *it << endl;
    else
        cout << "Not found" << endl;
    
    return 0;
}
输出为:Found 42

1.2 在 string 中查询

查询单个字符

  • 存在:输出第一个查找到的字符的下标
  • 不存在:输出 string::npos
string s = "aaabbb";
cout << s.find('b') << endl;	// 3
cout << s.find('c') << endl;	// string::npos

查询整个子串

  • 存在:输出母串中第一个匹配到的字符的下标
  • 不存在:输出 string::npos
string s = "bcabcggabcg";
cout << s.find("abc") << endl;	// 2
cout << s.find("xyz") << endl;		// string::npos

二、find_if

find_if 函数则用于查找容器中第一个满足指定条件的元素,并返回指向该元素的迭代器。这个条件是一个可调用对象,接受一个容器元素作为参数,并返回一个布尔值。

例如,下面的代码使用 find_if 函数在 vector 容器中查找第一个偶数:

#include 
#include 
#include 
using namespace std;

int main()
{
    vector<int> v = {1, 3, 5, 2, 7, 6};
    
    auto is_even = [](int x) { return x % 2 == 0; };
    auto it = find_if(v.begin(), v.end(), is_even);

    if (it != v.end())
        cout << "Found " << *it << endl;
    else
        cout << "Not found" << endl;
    
    return 0;
}
输出为:Found 2

总之,find 函数是根据给定值查找容器中的元素,而 find_if 函数是根据给定条件查找容器中的元素

你可能感兴趣的:(C++,c++,算法,c语言,开发语言)