返回列表 發帖

排序 - vector

本帖最後由 tonyh 於 2022-12-22 20:06 編輯

vector<int> v={5,7,3,9,8,1,2};

練習以各種可能的方式,針對 vector 做遞增與遞減排序。
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. vector<int> v= {5,7,3,9,8,1,2};
  4. int len;

  5. bool compare(int a, int b)
  6. {
  7.     return a>b;
  8. }

  9. void show()
  10. {
  11.     for(int i: v)
  12.         cout<<i<<" ";
  13.     cout<<endl;
  14. }

  15. void show2()
  16. {
  17.     for(int i=0; i<len; i++)
  18.         cout<<v[i]<<" ";
  19.     //cout<<v.at(i)<<" ";
  20.     cout<<endl;
  21. }

  22. void show3()
  23. {
  24.     //for(vector<int>::iterator it=begin(v); it!=end(v); it++)
  25.     for(auto it=begin(v); it!=end(v); it++)
  26.         cout<<*it<<" ";
  27.     cout<<endl;
  28. }

  29. int main()
  30. {
  31.     show();
  32.     len=v.size();
  33.     //遞增
  34.     //sort(v.begin(), v.end());
  35.     sort(begin(v), end(v));
  36.     //show();
  37.     show3();

  38.     //遞減
  39.     //sort(v.rbegin(), v.rend());
  40.     //sort(rbegin(v), rend(v));
  41.     sort(begin(v), end(v), compare);

  42.     show();

  43.     return 0;
  44. }
複製代碼

返回列表