本帖最後由 tonyh 於 2022-12-22 20:06 編輯
vector<int> v={5,7,3,9,8,1,2};
練習以各種可能的方式,針對 vector 做遞增與遞減排序。- #include<bits/stdc++.h>
- using namespace std;
- vector<int> v= {5,7,3,9,8,1,2};
- int len;
- bool compare(int a, int b)
- {
- return a>b;
- }
- void show()
- {
- for(int i: v)
- cout<<i<<" ";
- cout<<endl;
- }
- void show2()
- {
- for(int i=0; i<len; i++)
- cout<<v[i]<<" ";
- //cout<<v.at(i)<<" ";
- cout<<endl;
- }
- void show3()
- {
- //for(vector<int>::iterator it=begin(v); it!=end(v); it++)
- for(auto it=begin(v); it!=end(v); it++)
- cout<<*it<<" ";
- cout<<endl;
- }
- int main()
- {
- show();
- len=v.size();
- //遞增
- //sort(v.begin(), v.end());
- sort(begin(v), end(v));
- //show();
- show3();
- //遞減
- //sort(v.rbegin(), v.rend());
- //sort(rbegin(v), rend(v));
- sort(begin(v), end(v), compare);
- show();
- return 0;
- }
複製代碼 |