- #include<bits/stdc++.h>
- using namespace std;
- vector<int> v;
- int main()
- {
- 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; //11
- cout<<*(--it)<<endl; //7
- it=lower_bound(v.begin(), v.end(), 3);
- cout<<*(++it)<<endl; //5
- 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;
- }
- //1 2 3 5 7 11
複製代碼 |