STL lower_bound upper_bound 用法
1.lower_bound(begin,end,x)
返回第一个>=x的位置,找不到return .end()
2.upper_bound (begin,end,x)
返回第一个>x的位置,找不到return .end()
减掉begin得到下标
vector版
#include<cstdio> #include<iostream> #include<cstdlib> #include<cstring> #include<algorithm> #include<cmath> #include<vector> using namespace std; vector<int>a; int b[10]; int main(){ a.push_back(1); a.push_back(1); a.push_back(2); a.push_back(3); int p=lower_bound(a.begin(),a.end(),1)-a.begin(); int q=lower_bound(a.begin(),a.end(),2)-a.begin(); printf("%d %d\n",p,q);// 0 2 p=upper_bound(a.begin(),a.end(),1)-a.begin(); q=upper_bound(a.begin(),a.end(),2)-a.begin(); int r=upper_bound(a.begin(),a.end(),3)-a.begin(); printf("%d %d %d\n",p,q,r);// 2 3 4 return 0; }
数组版
#include<cstdio> #include<iostream> #include<cstdlib> #include<cstring> #include<algorithm> #include<cmath> #include<vector> using namespace std; vector<int>a; int b[4]={1,1,2,3}; int main(){ int p=lower_bound(b,b+4,1)-b; int q=lower_bound(b,b+4,2)-b; printf("%d %d\n",p,q);// 0 2 p=upper_bound(b,b+4,1)-b; q=upper_bound(b,b+4,2)-b; int r=upper_bound(b,b+4,3)-b; printf("%d %d %d\n",p,q,r);// 2 3 4 return 0; }
set (直接返回值)
#include<cstdio> #include<iostream> #include<cstdlib> #include<cstring> #include<algorithm> #include<cmath> #include<vector> #include<set> using namespace std; multiset<int>s; int main(){ s.insert(1); s.insert(1); s.insert(2); s.insert(3); set<int>::iterator p=s.lower_bound(1); set<int>::iterator q=s.lower_bound(2); printf("%d %d\n",*p,*q);// 1 2 return 0; }