- #include<bits/stdc++.h>
- using namespace std;
- int main(){
- vector<int> v;
- v.push_back(7);
- v.push_back(2);
- v.push_back(1);
- v.push_back(3);
- v.push_back(11);
- v.push_back(5);
- sort(v.begin(),v.end());
- for(int i: v)
- cout<<i<<" ";
- cout<<endl;
- cout<<"------------"<<endl;
- auto it=lower_bound(v.begin(),v.end(),7); //大於等於目標對象的最小值的位址
- cout<<*it<<endl; //該位址的值
- it=upper_bound(v.begin(),v.end(),7); //大於目標對象的最小值的位址
- cout<<*it<<endl;
- cout<<"------------"<<endl;
- it=upper_bound(v.begin(),v.end(),9);
- cout<<*it<<endl;
- cout<<*(--it)<<endl;
- it=lower_bound(v.begin(), v.end(), 3);
- cout<<*(++it)<<endl;
- cout<<"------------"<<endl;
- it=lower_bound(v.begin(),v.end(),3);
- cout<<it-v.begin()<<endl;//取得索引值
- it=find(v.begin(),v.end(),2);//非二分搜尋法, 效能較差, 適合未排序的資料。
- cout<<it-v.begin()<<endl;
- cout<<"------------"<<endl;
- it=find(v.begin(), v.end(), 12);//找不到時會回傳end()指向的位址
- if(it==v.end())
- cout<<"no find"<<endl;
- it=upper_bound(v.begin(), v.end(), 12);
- if(it==v.end())
- cout<<"no find"<<endl;
- return 0;
- }
複製代碼 |