21xrx.com
2024-09-19 09:26:54 Thursday
登录
文章检索 我的文章 写文章
C++ lower_bound函数使用方法介绍
2023-07-05 18:20:47 深夜i     --     --
C++ lower_bound函数 使用方法 介绍

C++中的lower_bound函数是一种用于在已排序的数组或容器中查找某个值的函数。该函数可以帮助我们快速定位某个值在数组或容器中第一次出现的位置。

下面介绍一下lower_bound函数的具体使用方法。

一、函数原型

lower_bound函数的原型为:

template

ForwardIt lower_bound(ForwardIt first, ForwardIt last, const T& value);

其中,first和last分别表示要搜索的起始位置和结束位置,value表示要查找的值。该函数返回一个指向第一个大于等于value的元素的迭代器。如果查找失败,则返回last。

二、使用示例

下面通过一些示例来更好地理解lower_bound函数的使用方法。

1.在数字数组中查找某一个值的位置:

#include

#include

using namespace std;

int main()

{

  int arr[] = 9;

  int n = sizeof(arr) / sizeof(arr[0]);

  int target = 4;

  int* it = lower_bound(arr, arr + n, target);

  if (it == arr + n || *it != target)

    cout << "未找到 " << target << endl;

  else

    cout << "找到 " << target << " 的位置为 " << it - arr << endl;

  return 0;

}

输出结果为:

找到 4 的位置为 4

其中,arr + n等于数组的末尾位置,如果lower_bound函数返回值等于末尾位置,则说明未找到目标值。

2.在字符串数组中查找某一字符串:

#include

#include

#include

using namespace std;

int main()

{

  string arr[] = "banana";

  int n = sizeof(arr) / sizeof(arr[0]);

  string target = "grape";

  string* it = lower_bound(arr, arr + n, target);

  if (it == arr + n || *it != target)

    cout << "未找到 " << target << endl;

  else

    cout << "找到 " << target << " 的位置为 " << it - arr << endl;

  return 0;

}

输出结果为:

找到 grape 的位置为 2

3.在自定义结构体数组中查找满足某一条件的元素:

#include

#include

#include

using namespace std;

struct Person

  string name;

  int age;

;

int main()

{

  vector persons = { 18 , "Jerry", "Bob", "Amy" };

  Person target = "Bob";

  auto it = lower_bound(persons.begin(), persons.end(), target, [](Person& a, Person& b) return a.age < b.age; );

  if (it == persons.end() || it->name != target.name)

    cout << "未找到 " << target.name << endl;

  else {

    cout << "找到 " << target.name << " 的位置为 " << it - persons.begin() << endl;

  }

  return 0;

}

输出结果为:

找到 Bob 的位置为 2

通过上述示例,我们可以看到lower_bound函数在不同数据类型的数组或容器中都能够正常使用,并快速找到目标值的位置。

需要注意的是,lower_bound函数只适用于有序的数组或容器。如果搜索的数组或容器未排序,则需要先对其进行排序。此外,lower_bound函数返回的是迭代器,需要注意其类型是否和数组或容器的类型匹配。

总的来说,lower_bound函数是C++的一个简单但实用的搜索函数,它可以在有限的时间内找到目标值所在的位置,为我们编写高效的算法提供了便利。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复