C語言反轉字符串函數reverse()


The behavior of this function template is equivalent to:

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:

myvector contains: 9 8 7 6 5 4 3 2 1

實例:PAT乙級

1008 數組元素循環右移問題 (20 分)

一個數組A中存有N(>0)個整數,在不允許使用另外數組的前提下,將每個整數循環向右移M(≥0)個位置,即將A中的數據由(A​0​​A​1​​⋯A​N−1​​)變換為(A​N−M​​⋯A​N−1​​A​0​​A​1​​⋯A​N−M−1​​)(最后M個數循環移至最前面的M個位置)。如果需要考慮程序移動數據的次數盡量少,要如何設計移動的方法?

輸入格式:

每個輸入包含一個測試用例,第1行輸入N(1≤N≤100)和M(≥0);第2行輸入N個整數,之間用空格分隔。

輸出格式:

在一行中輸出循環右移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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM