返回列表 發帖
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int main(){
  4.     vector<int> v;
  5.     v.push_back(7);
  6.     v.push_back(2);
  7.     v.push_back(1);
  8.     v.push_back(3);
  9.     v.push_back(11);
  10.     v.push_back(5);

  11.     sort(v.begin(),v.end());
  12.     for(int i: v)
  13.         cout<<i<<" ";
  14.     cout<<endl;
  15.     cout<<"------------"<<endl;

  16.     auto it=lower_bound(v.begin(),v.end(),7);  //大於等於目標對象的最小值的位址
  17.     cout<<*it<<endl;     //該位址的值
  18.     it=upper_bound(v.begin(),v.end(),7);      //大於目標對象的最小值的位址
  19.     cout<<*it<<endl;
  20.     cout<<"------------"<<endl;

  21.     it=upper_bound(v.begin(),v.end(),9);
  22.     cout<<*it<<endl;   
  23.     cout<<*(--it)<<endl;
  24.     it=lower_bound(v.begin(), v.end(), 3);
  25.     cout<<*(++it)<<endl;  

  26.     cout<<"------------"<<endl;
  27.     it=lower_bound(v.begin(),v.end(),3);
  28.     cout<<it-v.begin()<<endl;//取得索引值
  29.     it=find(v.begin(),v.end(),2);//非二分搜尋法, 效能較差, 適合未排序的資料。
  30.     cout<<it-v.begin()<<endl;
  31.     cout<<"------------"<<endl;
  32.      it=find(v.begin(), v.end(), 12);//找不到時會回傳end()指向的位址
  33.     if(it==v.end())
  34.         cout<<"no find"<<endl;
  35.     it=upper_bound(v.begin(), v.end(), 12);
  36.     if(it==v.end())
  37.         cout<<"no find"<<endl;
  38.     return 0;
  39. }
複製代碼

TOP

返回列表