#include <bits/stdc++.h>
using namespace std;
const int N=1e4+10;
vector<int> a(N);
int main(){
a={1,2,3,3,3,7,8};
int target=5;//将要查找的值设为3.
vector<int>::iterator ret1=lower_bound(a.begin(),a.begin()+7,target);//返回数组中第一次出现3的位置的下标。
//如果数组中没有找到这个元素,就返回数组中第一次出现大于3的位置的下标
vector<int>::iterator ret2=upper_bound(a.begin(),a.begin()+7,target);//返回数组中第一次出现大于3的位置的下标
cout<<*ret1<<endl<<*ret2<<endl;
if(target==*ret1) cout<<"在数组中可以找到目标值:"<<target<<endl;
else cout<<"在数组中不可以找到目标值"<<endl;
}
运行结果:
lower_bound -a.begin()→ 指向第一个 3的下标
upper_bound -a.begin()→ 指向第一个比 3 大的数(7)的下标
【得到目标值第一次出现的下标和目标值最后一次出现下标的下一个位置】可执行代码:
cpp复制代码
#include <bits/stdc++.h>
using namespace std;
const int N=1e4+10;
vector<int> a(N);
int main(){
a={1,2,3,3,3,7,8};
int target=3;//将要查找的值设为3.
int ret1=lower_bound(a.begin(),a.begin()+7,target)-a.begin();//返回数组中第一次出现3的位置的下标。
//如果数组中没有找到这个元素,就返回数组中第一次出现大于3的位置的下标
int ret2=upper_bound(a.begin(),a.begin()+7,target)-a.begin();//返回数组中第一次出现大于3的位置的下标
cout<<ret1<<endl<<ret2;
}
#include <bits/stdc++.h>
using namespace std;
const int N=1e4+10;
vector<int> a(N);
int main(){
a={1,2,3,3,3,7,8};
int target=5;//将要查找的值设为5.
int ret1=lower_bound(a.begin(),a.begin()+7,target)-a.begin();//返回数组中第一次出现3的位置的下标。
//如果数组中没有找到这个元素,就返回数组中第一次出现大于5的位置的下标
int ret2=upper_bound(a.begin(),a.begin()+7,target)-a.begin();//返回数组中第一次出现大于5的位置的下标
cout<<ret1<<endl<<ret2;
}