目录

algorithm::lower_bound()

描述 (Description)

C ++函数std::algorithm::lower_bound()查找不小于给定值的第一个元素。 此函数排除了按排序顺序排列的元素。 它使用二进制函数进行比较。

声明 (Declaration)

以下是std :: algorithm :: lower_bound()函数形式std :: algorithm头的声明。

C++98

template <class ForwardIterator, class T, class Compare>
ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last,
   const T& val, Compare comp);

参数 (Parameters)

  • first - 将迭代器转发到初始位置。

  • last - 将迭代器转发到最终位置。

  • val - 要在范围内搜索的下限值。

  • comp - 一个二进制函数,它接受两个参数并返回bool。

返回值

返回不小于给定值的第一个元素的迭代器。 如果范围中的所有元素都比val小 ,那么函数最后返回。

异常 (Exceptions)

如果二元函数或迭代器上的操作抛出异常,则抛出异常。

请注意,无效参数会导致未定义的行为。

时间复杂

线性。

例子 (Example)

以下示例显示了std :: algorithm :: lower_bound()函数的用法。

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool ignore_case(char a, char b) {
   return(tolower(a) == tolower(b));
}
int main(void) {
   vector<char> v = {'A', 'b', 'C', 'd', 'E'};
   auto it = lower_bound(v.begin(), v.end(), 'C');
   cout << "First element which is greater than \'C\' is " << *it << endl;
   it = lower_bound(v.begin(), v.end(), 'C', ignore_case);
   cout << "First element which is greater than \'C\' is " << *it << endl;
   it = lower_bound(v.begin(), v.end(), 'z', ignore_case);
   cout << "All elements are less than \'z\'." << endl;
   return 0;
}

让我们编译并运行上面的程序,这将产生以下结果 -

First element which is greater than 'C' is b
First element which is greater than 'C' is d
All elements are less than 'z'.
↑回到顶部↑
WIKI教程 @2018