STL--map中的用法:std::map::lower_bound与td::map::upper_boundios
iterator lower_bound( const key_type &key ): 返回一个迭代器,指向键值>= key的第一个元素。
iterator upper_bound( const key_type &key ):返回一个迭代器,指向键值> key的第一个元素。
post
lower_bound 返回值是一个指向容器中第一个元素的迭代器,该容器中的元素知足不在k的前面,(返回元素的键值>=k)
测试
upper_bound返回值是一个指向容器中第一个元素的迭代器,该容器中的元素知足在k的后面,(返回元素的键值>k)
spa
STL中的用法:std::lower_bound与std::upper_bound
code
ForwardIter lower_bound(ForwardIter first, ForwardIter last,const _Tp& val)blog
返回一个非递减序列[first, last)中的第一个>= 值val的位置。ip
ForwardIter upper_bound(ForwardIter first, ForwardIter last, const _Tp& val)ci
返回一个非递减序列[first, last)中的第一个>值val的位置。string
【代码】std::lower_bound与std::upper_bound用法示例1:it
#include <iostream> #include <algorithm> using namespace std; int a[15]; int main() { int t; cin>>t; while (t--) { int n; scanf("%d", &n); for (int i = 0; i < n; i++){ cin>>a[i]; } int lb = lower_bound(a, a + n + 1, 2)-a; //在[a,a+n+1)中找出大于等于2的位置,这个位置是从0开始 int ub = upper_bound(a, a + n + 1, 2)-a; //在[a,a+n+1)中找出大于2的位置,这个位置是从0开始 cout<<"序列中大于等于2第一个元素的位置:"<<lb+1<<endl; cout<<"序列中大于2第一个元素的位置:"<<ub+1<<endl; return 0; } }
【测试结果】
【代码】std::lower_bound与std::upper_bound用法示例2:
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { int a[]={10,20,30,20,10,10,20}; vector<int> v(a,a+8); // 10 20 30 30 20 10 10 20 sort(v.begin(),v.end()); // 10 10 10 20 20 20 30 30 vector<int>::iterator lb,ub; lb=lower_bound(v.begin(),v.end(),20); ub=upper_bound(v.begin(),v.end(),20); cout<<"lower_bound at position " << (lb- v.begin()) << '\n'; cout<<"upper_bound at position " << (ub- v.begin()) << '\n'; return 0; }【测试结果】
lower_bound at position 3 upper_bound at position 6 |
#include <iostream> #include <map> using namespace std; int main() { map<int,string> mp; mp[1]="a"; mp[2]="b"; mp[3]="f"; mp[4]="c"; mp[5]="d"; map<int,string>::iterator it,p1,p2; p1 = mp.lower_bound(3); p2 = mp.upper_bound(3); cout<<"lower_bound"<<p1->first<<"=>"<<p1->second.c_str()<<endl; cout<<"upper_bound"<<p2->first<<"=>"<<p2->second.c_str()<<endl; return 0; }【测试结果1】
lower_bound3=>f upper_bound4=>c |
#include <iostream> #include <map> using namespace std; int main() { map<int,string> mp; mp[1]="a"; mp[2]="b"; //mp[3]="f"; mp[4]="c"; mp[5]="d"; map<int,string>::iterator it,p1,p2; p1 = mp.lower_bound(3); p2 = mp.upper_bound(3); cout<<"lower_bound"<<p1->first<<"=>"<<p1->second.c_str()<<endl; cout<<"upper_bound"<<p2->first<<"=>"<<p2->second.c_str()<<endl; return 0; }【测试结果1】
lower_bound4=>c upper_bound4=>c |