The behavior of this function template is equivalent to:ios
template <class BidirectionalIterator> void reverse (BidirectionalIterator first, BidirectionalIterator last) { while ((first!=last)&&(first!=--last)) { std::iter_swap (first,last); ++first; } }
Attention:數組
-
Bidirectional iterators to the initial and final positions of the sequence to be reversed. The range used is
[first,last)
, which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
BidirectionalIterator shall point to a type for which swap is properly defined.
Example:測試
// reverse algorithm example #include <iostream> // std::cout #include <algorithm> // std::reverse #include <vector> // std::vector int main () { std::vector<int> myvector; // set some values: for (int i=1; i<10; ++i) myvector.push_back(i); // 1 2 3 4 5 6 7 8 9 std::reverse(myvector.begin(),myvector.end()); // 9 8 7 6 5 4 3 2 1 // print out content: std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) std::cout << ' ' << *it; std::cout << '\n'; return 0; }
Output:ui
myvector contains: 9 8 7 6 5 4 3 2 1
實例:PAT乙級this
1008 數組元素循環右移問題 (20 分) url
一個數組A中存有N(>0)個整數,在不容許使用另外數組的前提下,將每一個整數循環向右移M(≥0)個位置,即將A中的數據由(A0A1⋯AN−1)變換爲(AN−M⋯AN−1A0A1⋯AN−M−1)(最後M個數循環移至最前面的M個位置)。若是須要考慮程序移動數據的次數儘可能少,要如何設計移動的方法? spa
輸入格式:
每一個輸入包含一個測試用例,第1行輸入N(1≤N≤100)和M(≥0);第2行輸入N個整數,之間用空格分隔。 .net
輸出格式:
在一行中輸出循環右移M位之後的整數序列,之間用空格分隔,序列結尾不能有多餘空格。 設計
輸入樣例:
6 2 1 2 3 4 5 6
輸出樣例:
5 6 1 2 3 4
代碼:
#include <iostream> #include <algorithm> using namespace std; int main(){ int n,m; int a[1000]; cin>>n>>m; m%=n; for(int i=0;i<n;i++){ cin>>a[i]; } reverse(a,a+n); reverse(a+m,a+n); reverse(a,a+m); for(int i=0;i<n;i++){ cout<<a[i]; if(i!=n-1) cout<<" "; } return 0; }