返回列表 發帖

vector 練習 2

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. vector<int> v;
  4. int main()
  5. {
  6.     v.push_back(7);   //新增元素
  7.     v.push_back(2);
  8.     v.push_back(1);
  9.     v.push_back(3);
  10.     v.push_back(11);
  11.     v.push_back(5);
  12.     sort(v.begin(), v.end());   //基礎排序
  13.     for(int i: v)
  14.         cout<<i<<" ";
  15.     cout<<endl;
  16.     cout<<"------------"<<endl;
  17.     auto it=lower_bound(v.begin(), v.end(), 7);  //大於或等於目標對象的最小值的位址
  18.     cout<<*it<<endl;     //該位址的值
  19.     it=upper_bound(v.begin(), v.end(), 7);      //大於目標對象的最小值的位址
  20.     cout<<*it<<endl;
  21.     cout<<"------------"<<endl;
  22.     it=upper_bound(v.begin(), v.end(), 9);
  23.     cout<<*it<<endl;   //11
  24.     cout<<*(--it)<<endl;   //7
  25.     it=lower_bound(v.begin(), v.end(), 3);
  26.     cout<<*(++it)<<endl;   //5
  27.     cout<<"------------"<<endl;
  28.     it=lower_bound(v.begin(), v.end(), 3);
  29.     cout<<it-v.begin()<<endl;  //取得索引值
  30.     it=find(v.begin(), v.end(), 2);   //非二分搜尋法, 效能較差, 適合用於未排序的資料。
  31.     cout<<it-v.begin()<<endl;
  32.     cout<<"------------"<<endl;
  33.     it=find(v.begin(), v.end(), 12);   //找不到時會回傳end()指向的位址
  34.     if(it==v.end())
  35.         cout<<"no find"<<endl;
  36.     it=upper_bound(v.begin(), v.end(), 12);
  37.     if(it==v.end())
  38.         cout<<"no find"<<endl;
  39.     return 0;
  40. }
  41. //1 2 3 5 7 11
複製代碼

返回列表