在C++中,lower_bound函数用于返回在已排序的区间中,第一个不小于给定值的元素的位置
在C++中,lower_bound
函数用于返回在已排序的区间中,第一个不小于给定值的元素的位置。
下面是lower_bound
函数的语法:
std::vector<int>::iteratorlower_bound(std::vector<int>::iteratorfirst,std::vector<int>::iteratorlast,constint&val);
在使用lower_bound
函数时,首先需要确保区间已经按照升序排序。然后传入函数三个参数:指向区间起始位置的迭代器first
,指向区间末尾位置的迭代器last
,以及要查找的值val
。
lower_bound
函数会在指定区间内搜索不小于给定值val
的第一个元素,并返回指向该元素的迭代器。如果找不到符合条件的元素,则返回指向区间末尾的迭代器last
。
以下是一个简单的示例代码,演示如何使用lower_bound
函数:
#include<iostream>
#include<vector>
#include<algorithm>
intmain(){
std::vector<int>vec={1,2,3,4,5,6,7,8,9};
//查找不小于5的第一个元素的位置
std::vector<int>::iteratorit=std::lower_bound(vec.begin(),vec.end(),5);
if(it!=vec.end()){
std::cout<<"第一个不小于5的元素位置为:"<<std::distance(vec.begin(),it)<<std::endl;
}else{
std::cout<<"未找到符合条件的元素"<<std::endl;
}
return0;
}
在上面的示例中,lower_bound
函数会在vec
中查找不小于5的第一个元素,因为vec已经是升序排序的,所以返回的迭代器指向5。
版权声明
本文仅代表作者观点,不代表博信信息网立场。