返回列表 發帖
本帖最後由 林祐霆 於 2023-10-27 19:14 編輯
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. vector<int> v;
  4. bool compare(int a, int b)
  5. {
  6.     return a>b;
  7. }
  8. int main()
  9. {
  10.     v.push_back(7);
  11.     v.push_back(2);
  12.     v.push_back(1);
  13.     v.push_back(3);
  14.     v.push_back(11);
  15.     v.push_back(5);

  16.     sort(v.begin(), v.end());

  17.     for(int i: v)
  18.         cout<<i<<" ";
  19.     cout<<endl;
  20.     cout<<"-------"<<endl;
  21.     auto it=lower_bound(v.begin(), v.end(),7); //>=9最接近的位置
  22.     cout<<*it<<endl;  //*: 取該位置的值
  23.     it=upper_bound(v.begin(), v.end(), 7); //>9最接近的位置
  24.     cout<<*it<<endl;

  25.     cout<<"-------"<<endl;
  26.     it=upper_bound(v.begin(), v.end(), 9);
  27.     cout<<*it<<endl;
  28.     cout<<*(--it)<<endl;

  29.     cout<<"-------"<<endl;
  30.     it=lower_bound(v.begin(), v.end(),3);
  31.     cout<<*(++it)<<endl;
  32.     cout<<it-v.begin()<<endl;

  33.     cout<<"------------"<<endl;
  34.     it=find(v.begin(), v.end(), 12);   //找不到時會回傳end()指向的位址
  35.     if(it==v.end())
  36.         cout<<"no find"<<endl;
  37.     it=upper_bound(v.begin(), v.end(), 12);
  38.     if(it==v.end())
  39.         cout<<"no find"<<endl;
  40.     return 0;
  41.     //1 2 3 5 7 11
  42. }
複製代碼
林祐霆

TOP

返回列表